1313use ApiSkeletons \Laravel \Doctrine \ApiKey \Exception \InvalidName ;
1414use DateTime ;
1515use Doctrine \ORM \EntityRepository ;
16+ use Doctrine \ORM \ORMException ;
1617use Illuminate \Support \Str ;
1718
1819use function preg_match ;
1920use function request ;
2021
2122class ApiKeyRepository extends EntityRepository
2223{
24+ /**
25+ * Create a new ApiKey entity
26+ *
27+ * @throws DuplicateName
28+ * @throws InvalidName
29+ * @throws ORMException
30+ */
2331 public function generate (string $ name ): ApiKey
2432 {
2533 // Verify name is unique
@@ -33,9 +41,7 @@ public function generate(string $name): ApiKey
3341 throw new InvalidName ('Please provide a valid name: [a-z0-9-] ' );
3442 }
3543
36- do {
37- $ key = Str::random (64 );
38- } while ($ this ->findBy (['api_key ' => $ key ]));
44+ $ key = $ this ->generateKey ();
3945
4046 $ apiKey = new ApiKey ();
4147 $ apiKey
@@ -51,6 +57,31 @@ public function generate(string $name): ApiKey
5157 return $ apiKey ;
5258 }
5359
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+ */
5485 public function updateActive (ApiKey $ apiKey , bool $ status ): ApiKey
5586 {
5687 $ apiKey
@@ -63,6 +94,11 @@ public function updateActive(ApiKey $apiKey, bool $status): ApiKey
6394 return $ apiKey ;
6495 }
6596
97+ /**
98+ * Add an existing scope to an existing ApiKey entity
99+ *
100+ * @throws DuplicateScopeForApiKey
101+ */
66102 public function addScope (ApiKey $ apiKey , Scope $ scope ): ApiKey
67103 {
68104 // Do not add scopes twice
@@ -80,6 +116,11 @@ public function addScope(ApiKey $apiKey, Scope $scope): ApiKey
80116 return $ apiKey ;
81117 }
82118
119+ /**
120+ * Remove a scope from an ApiKey
121+ *
122+ * @throws ApiKeyDoesNotHaveScope
123+ */
83124 public function removeScope (ApiKey $ apiKey , Scope $ scope ): ApiKey
84125 {
85126 $ found = false ;
@@ -104,11 +145,17 @@ public function removeScope(ApiKey $apiKey, Scope $scope): ApiKey
104145 return $ apiKey ;
105146 }
106147
148+ /**
149+ * Validate an API key name
150+ */
107151 public function isValidName (string $ name ): bool
108152 {
109153 return (bool ) preg_match ('/^[a-z0-9-]{1,255}$/ ' , $ name );
110154 }
111155
156+ /**
157+ * Create a new entity for logging admin events whenever one is triggered
158+ */
112159 protected function logAdminEvent (ApiKey $ apiKey , string $ eventName ): AdminEvent
113160 {
114161 $ adminEvent = (new AdminEvent ())
0 commit comments