13
13
use ApiSkeletons \Laravel \Doctrine \ApiKey \Exception \InvalidName ;
14
14
use DateTime ;
15
15
use Doctrine \ORM \EntityRepository ;
16
+ use Doctrine \ORM \ORMException ;
16
17
use Illuminate \Support \Str ;
17
18
18
19
use function preg_match ;
19
20
use function request ;
20
21
21
22
class ApiKeyRepository extends EntityRepository
22
23
{
24
+ /**
25
+ * Create a new ApiKey entity
26
+ *
27
+ * @throws DuplicateName
28
+ * @throws InvalidName
29
+ * @throws ORMException
30
+ */
23
31
public function generate (string $ name ): ApiKey
24
32
{
25
33
// Verify name is unique
@@ -33,9 +41,7 @@ public function generate(string $name): ApiKey
33
41
throw new InvalidName ('Please provide a valid name: [a-z0-9-] ' );
34
42
}
35
43
36
- do {
37
- $ key = Str::random (64 );
38
- } while ($ this ->findBy (['api_key ' => $ key ]));
44
+ $ key = $ this ->generateKey ();
39
45
40
46
$ apiKey = new ApiKey ();
41
47
$ apiKey
@@ -51,6 +57,31 @@ public function generate(string $name): ApiKey
51
57
return $ apiKey ;
52
58
}
53
59
60
+ /**
61
+ * Assign a new api_key to an existing ApiKey entity
62
+ */
63
+ public function regenerate (ApiKey $ apiKey ): ApiKey
64
+ {
65
+ $ apiKey ->setApiKey ($ this ->generateKey ());
66
+
67
+ return $ apiKey ;
68
+ }
69
+
70
+ /**
71
+ * Generate a unique api_key
72
+ */
73
+ protected function generateKey (): string
74
+ {
75
+ do {
76
+ $ key = Str::random (64 );
77
+ } while ($ this ->findBy (['api_key ' => $ key ]));
78
+
79
+ return $ key ;
80
+ }
81
+
82
+ /**
83
+ * Change the active status of an ApiKey entity
84
+ */
54
85
public function updateActive (ApiKey $ apiKey , bool $ status ): ApiKey
55
86
{
56
87
$ apiKey
@@ -63,6 +94,11 @@ public function updateActive(ApiKey $apiKey, bool $status): ApiKey
63
94
return $ apiKey ;
64
95
}
65
96
97
+ /**
98
+ * Add an existing scope to an existing ApiKey entity
99
+ *
100
+ * @throws DuplicateScopeForApiKey
101
+ */
66
102
public function addScope (ApiKey $ apiKey , Scope $ scope ): ApiKey
67
103
{
68
104
// Do not add scopes twice
@@ -80,6 +116,11 @@ public function addScope(ApiKey $apiKey, Scope $scope): ApiKey
80
116
return $ apiKey ;
81
117
}
82
118
119
+ /**
120
+ * Remove a scope from an ApiKey
121
+ *
122
+ * @throws ApiKeyDoesNotHaveScope
123
+ */
83
124
public function removeScope (ApiKey $ apiKey , Scope $ scope ): ApiKey
84
125
{
85
126
$ found = false ;
@@ -104,11 +145,17 @@ public function removeScope(ApiKey $apiKey, Scope $scope): ApiKey
104
145
return $ apiKey ;
105
146
}
106
147
148
+ /**
149
+ * Validate an API key name
150
+ */
107
151
public function isValidName (string $ name ): bool
108
152
{
109
153
return (bool ) preg_match ('/^[a-z0-9-]{1,255}$/ ' , $ name );
110
154
}
111
155
156
+ /**
157
+ * Create a new entity for logging admin events whenever one is triggered
158
+ */
112
159
protected function logAdminEvent (ApiKey $ apiKey , string $ eventName ): AdminEvent
113
160
{
114
161
$ adminEvent = (new AdminEvent ())
0 commit comments