koel/app/Services/TokenManager.php

44 lines
1,000 B
PHP
Raw Normal View History

2020-09-06 18:21:39 +00:00
<?php
namespace App\Services;
use App\Models\User;
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 destroyTokens(User $user): void
{
$user->tokens()->delete();
}
2020-09-06 21:11:48 +00:00
public function deleteTokenByPlainTextToken(string $plainTextToken): void
{
$token = PersonalAccessToken::findToken($plainTextToken);
if ($token) {
$token->delete();
}
}
2020-09-06 21:11:48 +00:00
public function getUserFromPlainTextToken(string $plainTextToken): ?User
{
$token = PersonalAccessToken::findToken($plainTextToken);
return $token ? $token->tokenable : null;
}
public function refreshToken(User $user): NewAccessToken
{
$this->destroyTokens($user);
return $this->createToken($user);
}
2020-09-06 18:21:39 +00:00
}