Files
hyperf_rbac_framework_serve…/app/Service/BaseTokenService.php
2025-09-12 23:54:03 +08:00

64 lines
1.6 KiB
PHP

<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service;
use App\Exception\ErrException;
use App\Interface\CheckTokenInterface;
use App\Lib\Jwt\JwtFactory;
use Hyperf\Di\Annotation\Inject;
use Lcobucci\JWT\Token\RegisteredClaims;
use Lcobucci\JWT\UnencryptedToken;
use App\Interface\JwtInterface;
use function Hyperf\Support\value;
final class BaseTokenService implements CheckTokenInterface
{
private string $jwt = 'admin';
/**
* @var JwtFactory
*/
#[Inject]
protected JwtFactory $jwtFactory;
/**
* @return JwtInterface
*/
public function getJwt(): JwtInterface
{
return $this->jwtFactory->get($this->jwt);
}
/**
* @param UnencryptedToken $token
* @return void
*/
public function checkJwt(UnencryptedToken $token): void
{
$this->getJwt()->hasBlackList($token) && throw new ErrException('token已过期');
}
/**
* @param UnencryptedToken $token
* @return \Closure
*/
public function refreshToken(UnencryptedToken $token): \Closure
{
return value(static function (JwtInterface $jwt) use ($token) {
$jwt->addBlackList($token);
return [
'access_token' => $jwt->builderAccessToken($token->claims()->get(RegisteredClaims::ID))->toString(),
'refresh_token' => $jwt->builderRefreshToken($token->claims()->get(RegisteredClaims::ID))->toString(),
'expire_at' => (int) $jwt->getConfig('ttl', 0),
];
}, $this->getJwt());
}
}