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
|
|
|
|
2020-09-07 20:43:23 +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;
|
|
|
|
}
|
2021-01-31 17:21:57 +00:00
|
|
|
|
|
|
|
public function refreshToken(User $user): NewAccessToken
|
|
|
|
{
|
|
|
|
$this->destroyTokens($user);
|
|
|
|
|
|
|
|
return $this->createToken($user);
|
|
|
|
}
|
2020-09-06 18:21:39 +00:00
|
|
|
}
|