misc_pterodactyl-panel/app/Services/Api/KeyCreationService.php

80 lines
2.2 KiB
PHP
Raw Normal View History

<?php
2017-07-09 17:29:18 +00:00
namespace Pterodactyl\Services\Api;
2018-01-14 18:06:15 +00:00
use Pterodactyl\Models\ApiKey;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface;
class KeyCreationService
{
/**
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
private $encrypter;
/**
* @var int
*/
private $keyType = ApiKey::TYPE_NONE;
/**
* @var \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface
*/
private $repository;
/**
* ApiKeyService constructor.
*
* @param \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface $repository
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
*/
2018-01-13 22:23:43 +00:00
public function __construct(ApiKeyRepositoryInterface $repository, Encrypter $encrypter)
{
$this->encrypter = $encrypter;
2018-01-13 22:23:43 +00:00
$this->repository = $repository;
}
/**
* 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.
*
* @param int $type
* @return \Pterodactyl\Services\Api\KeyCreationService
*/
public function setKeyType(int $type)
{
$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 identifer and an encrypted token that are
* stored in the database.
*
2017-08-22 03:10:48 +00:00
* @param array $data
* @param array $permissions
2018-01-14 18:06:15 +00:00
* @return \Pterodactyl\Models\ApiKey
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
*/
public function handle(array $data, array $permissions = []): ApiKey
{
$data = array_merge($data, [
'key_type' => $this->keyType,
2018-01-14 18:06:15 +00:00
'identifier' => str_random(ApiKey::IDENTIFIER_LENGTH),
'token' => $this->encrypter->encrypt(str_random(ApiKey::KEY_LENGTH)),
]);
if ($this->keyType === ApiKey::TYPE_APPLICATION) {
$data = array_merge($data, $permissions);
}
$instance = $this->repository->create($data, true, true);
return $instance;
}
}