pelican-panel-banquise/app/Services/Api/KeyCreationService.php
Boy132 b3501be6ec
Refactor api key permissions (#361)
* use RESOURCE_NAME for requests

* use RESOURCE_NAME for transformers

* add permissions field to api key

* add migration for new permissions field

* update tests

* remove debug log

* set column type to "json"

* remove default attribute to fix tests

* fix default value for permissions

* fix after merge

* fix after merge

* allow to "register" custom permissions

* add "role" to default resource names

* fix after merge

* fix phpstan

* fix migrations
2024-11-06 09:09:10 +01:00

44 lines
1.2 KiB
PHP

<?php
namespace App\Services\Api;
use App\Models\ApiKey;
class KeyCreationService
{
private int $keyType = ApiKey::TYPE_NONE;
/**
* Set the type of key that should be created. By default, an orphaned key will be
* created. These keys cannot be used for anything, and will not render in the UI.
*/
public function setKeyType(int $type): self
{
$this->keyType = $type;
return $this;
}
/**
* Create a new API key for the Panel using the permissions passed in the data request.
* This will automatically generate an identifier and an encrypted token that are
* stored in the database.
*
* @throws \App\Exceptions\Model\DataValidationException
*/
public function handle(array $data, array $permissions = []): ApiKey
{
$data = array_merge($data, [
'key_type' => $this->keyType,
'identifier' => ApiKey::generateTokenIdentifier($this->keyType),
'token' => str_random(ApiKey::KEY_LENGTH),
]);
if ($this->keyType === ApiKey::TYPE_APPLICATION) {
$data['permissions'] = array_merge($data['permissions'], $permissions);
}
return ApiKey::query()->forceCreate($data);
}
}