2020-09-06 18:21:39 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
use App\Models\User;
|
2022-11-16 17:57:38 +00:00
|
|
|
use App\Values\CompositionToken;
|
|
|
|
use Illuminate\Cache\Repository as Cache;
|
2020-09-06 18:21:39 +00:00
|
|
|
use Laravel\Sanctum\NewAccessToken;
|
2020-09-06 21:11:48 +00:00
|
|
|
use Laravel\Sanctum\PersonalAccessToken;
|
2020-09-06 18:21:39 +00:00
|
|
|
|
|
|
|
class TokenManager
|
|
|
|
{
|
2022-11-16 17:57:38 +00:00
|
|
|
public function __construct(private Cache $cache)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2020-09-06 18:21:39 +00:00
|
|
|
public function createToken(User $user, array $abilities = ['*']): NewAccessToken
|
|
|
|
{
|
|
|
|
return $user->createToken(config('app.name'), $abilities);
|
|
|
|
}
|
|
|
|
|
2022-11-16 17:57:38 +00:00
|
|
|
public function createCompositionToken(User $user): CompositionToken
|
|
|
|
{
|
|
|
|
$token = CompositionToken::fromAccessTokens(
|
|
|
|
api: $this->createToken($user),
|
|
|
|
audio: $this->createToken($user, ['audio'])
|
|
|
|
);
|
|
|
|
|
|
|
|
$this->cache->rememberForever("app.composition-tokens.$token->apiToken", static fn () => $token->audioToken);
|
|
|
|
|
|
|
|
return $token;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function deleteCompositionToken(string $plainTextApiToken): void
|
|
|
|
{
|
|
|
|
/** @var string $audioToken */
|
|
|
|
$audioToken = $this->cache->get("app.composition-tokens.$plainTextApiToken");
|
|
|
|
|
|
|
|
if ($audioToken) {
|
|
|
|
self::deleteTokenByPlainTextToken($audioToken);
|
|
|
|
$this->cache->forget("app.composition-tokens.$plainTextApiToken");
|
|
|
|
}
|
|
|
|
|
|
|
|
self::deleteTokenByPlainTextToken($plainTextApiToken);
|
|
|
|
}
|
|
|
|
|
2020-09-06 18:21:39 +00:00
|
|
|
public function destroyTokens(User $user): void
|
|
|
|
{
|
|
|
|
$user->tokens()->delete();
|
|
|
|
}
|
2020-09-06 21:11:48 +00:00
|
|
|
|
2020-09-07 20:43:23 +00:00
|
|
|
public function deleteTokenByPlainTextToken(string $plainTextToken): void
|
|
|
|
{
|
2022-07-27 15:32:36 +00:00
|
|
|
PersonalAccessToken::findToken($plainTextToken)?->delete();
|
2020-09-07 20:43:23 +00:00
|
|
|
}
|
|
|
|
|
2020-09-06 21:11:48 +00:00
|
|
|
public function getUserFromPlainTextToken(string $plainTextToken): ?User
|
|
|
|
{
|
2022-07-27 15:32:36 +00:00
|
|
|
return PersonalAccessToken::findToken($plainTextToken)?->tokenable;
|
2020-09-06 21:11:48 +00:00
|
|
|
}
|
2021-01-31 17:21:57 +00:00
|
|
|
|
2022-11-16 17:57:38 +00:00
|
|
|
public function refreshApiToken(string $currentPlainTextToken): NewAccessToken
|
2021-01-31 17:21:57 +00:00
|
|
|
{
|
2022-11-16 17:57:38 +00:00
|
|
|
$newToken = $this->createToken($this->getUserFromPlainTextToken($currentPlainTextToken));
|
|
|
|
$this->deleteTokenByPlainTextToken($currentPlainTextToken);
|
2021-01-31 17:21:57 +00:00
|
|
|
|
2022-11-16 17:57:38 +00:00
|
|
|
return $newToken;
|
2021-01-31 17:21:57 +00:00
|
|
|
}
|
2020-09-06 18:21:39 +00:00
|
|
|
}
|