koel/app/Services/TokenManager.php

70 lines
2 KiB
PHP
Raw Normal View History

2020-09-06 18:21:39 +00:00
<?php
namespace App\Services;
use App\Models\User;
use App\Values\CompositeToken;
2022-11-16 17:57:38 +00:00
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
{
2024-04-18 14:36:28 +00:00
public function __construct(private readonly Cache $cache)
2022-11-16 17:57:38 +00:00
{
}
2020-09-06 18:21:39 +00:00
public function createToken(User $user, array $abilities = ['*']): NewAccessToken
{
return $user->createToken(config('app.name'), $abilities);
}
public function createCompositeToken(User $user): CompositeToken
2022-11-16 17:57:38 +00:00
{
$token = CompositeToken::fromAccessTokens(
2022-11-16 17:57:38 +00:00
api: $this->createToken($user),
audio: $this->createToken($user, ['audio'])
);
$this->cache->rememberForever("app.composite-tokens.$token->apiToken", static fn () => $token->audioToken);
2022-11-16 17:57:38 +00:00
return $token;
}
public function deleteCompositionToken(string $plainTextApiToken): void
{
/** @var string $audioToken */
$audioToken = $this->cache->get("app.composite-tokens.$plainTextApiToken");
2022-11-16 17:57:38 +00:00
if ($audioToken) {
self::deleteTokenByPlainTextToken($audioToken);
$this->cache->forget("app.composite-tokens.$plainTextApiToken");
2022-11-16 17:57:38 +00:00
}
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
public function deleteTokenByPlainTextToken(string $plainTextToken): void
{
2022-07-27 15:32:36 +00:00
PersonalAccessToken::findToken($plainTextToken)?->delete();
}
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
}
2022-11-16 17:57:38 +00:00
public function refreshApiToken(string $currentPlainTextToken): NewAccessToken
{
2022-11-16 17:57:38 +00:00
$newToken = $this->createToken($this->getUserFromPlainTextToken($currentPlainTextToken));
$this->deleteTokenByPlainTextToken($currentPlainTextToken);
2022-11-16 17:57:38 +00:00
return $newToken;
}
2020-09-06 18:21:39 +00:00
}