2017-06-25 20:31:50 +00:00
|
|
|
<?php
|
|
|
|
|
2017-07-09 17:29:18 +00:00
|
|
|
namespace Pterodactyl\Services\Api;
|
2017-06-25 20:31:50 +00:00
|
|
|
|
2018-01-14 18:06:15 +00:00
|
|
|
use Pterodactyl\Models\ApiKey;
|
2018-01-13 22:06:19 +00:00
|
|
|
use Illuminate\Contracts\Encryption\Encrypter;
|
2017-07-08 19:07:51 +00:00
|
|
|
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
|
2017-06-25 20:31:50 +00:00
|
|
|
|
2017-08-31 02:11:14 +00:00
|
|
|
class KeyCreationService
|
2017-06-25 20:31:50 +00:00
|
|
|
{
|
2022-10-14 16:59:20 +00:00
|
|
|
private int $keyType = ApiKey::TYPE_NONE;
|
2017-07-08 19:07:51 +00:00
|
|
|
|
2017-06-25 20:31:50 +00:00
|
|
|
/**
|
|
|
|
* ApiKeyService constructor.
|
|
|
|
*/
|
2022-10-14 16:59:20 +00:00
|
|
|
public function __construct(private ApiKeyRepositoryInterface $repository, private Encrypter $encrypter)
|
2018-01-13 22:23:43 +00:00
|
|
|
{
|
2017-06-25 20:31:50 +00:00
|
|
|
}
|
|
|
|
|
2018-01-14 19:30:55 +00:00
|
|
|
/**
|
|
|
|
* 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.
|
|
|
|
*/
|
2022-10-14 16:59:20 +00:00
|
|
|
public function setKeyType(int $type): self
|
2018-01-14 19:30:55 +00:00
|
|
|
{
|
|
|
|
$this->keyType = $type;
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2017-06-25 20:31:50 +00:00
|
|
|
/**
|
2018-01-13 22:06:19 +00:00
|
|
|
* Create a new API key for the Panel using the permissions passed in the data request.
|
2018-05-13 14:50:56 +00:00
|
|
|
* This will automatically generate an identifier and an encrypted token that are
|
2018-01-13 22:06:19 +00:00
|
|
|
* stored in the database.
|
2017-06-25 20:31:50 +00:00
|
|
|
*
|
|
|
|
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
|
|
|
|
*/
|
2018-01-14 19:30:55 +00:00
|
|
|
public function handle(array $data, array $permissions = []): ApiKey
|
2017-06-25 20:31:50 +00:00
|
|
|
{
|
2018-01-13 22:06:19 +00:00
|
|
|
$data = array_merge($data, [
|
2018-01-14 19:30:55 +00:00
|
|
|
'key_type' => $this->keyType,
|
2022-05-22 23:03:51 +00:00
|
|
|
'identifier' => ApiKey::generateTokenIdentifier($this->keyType),
|
2018-01-14 18:06:15 +00:00
|
|
|
'token' => $this->encrypter->encrypt(str_random(ApiKey::KEY_LENGTH)),
|
2018-01-13 22:06:19 +00:00
|
|
|
]);
|
2017-06-25 20:31:50 +00:00
|
|
|
|
2018-01-14 19:30:55 +00:00
|
|
|
if ($this->keyType === ApiKey::TYPE_APPLICATION) {
|
|
|
|
$data = array_merge($data, $permissions);
|
|
|
|
}
|
|
|
|
|
2020-03-23 01:15:38 +00:00
|
|
|
return $this->repository->create($data, true, true);
|
2017-06-25 20:31:50 +00:00
|
|
|
}
|
|
|
|
}
|