koel/app/Services/TokenManager.php

66 lines
1.8 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;
2024-06-04 13:35:00 +00:00
use Illuminate\Support\Facades\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
{
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'])
);
2024-06-04 13:35:00 +00:00
Cache::forever("app.composite-tokens.$token->apiToken", $token->audioToken);
2022-11-16 17:57:38 +00:00
return $token;
}
public function deleteCompositionToken(string $plainTextApiToken): void
{
/** @var string $audioToken */
2024-06-04 13:35:00 +00:00
$audioToken = Cache::get("app.composite-tokens.$plainTextApiToken");
2022-11-16 17:57:38 +00:00
if ($audioToken) {
self::deleteTokenByPlainTextToken($audioToken);
2024-06-04 13:35:00 +00:00
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
}