Files
hyperf_service/app/Middleware/Admin/JwtAuthMiddleware.php
2024-10-27 19:34:20 +08:00

56 lines
1.9 KiB
PHP

<?php
namespace App\Middleware\Admin;
use App\Cache\Redis\Admin\UserCache;
use App\Constants\AdminCode;
use App\Lib\AdminReturn;
use App\Lib\Crypto\CryptoFactory;
use Hyperf\Context\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
class JwtAuthMiddleware implements MiddlewareInterface
{
public function __construct(
protected HttpResponse $response,
protected AdminReturn $apiReturn,
protected CryptoFactory $cryptoFactory,
protected UserCache $userCache,
){}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// 获取头部token
$authorization = $request->getHeaderLine('Authorization');
if (empty($authorization)) {
return $this->response->json(
$this->apiReturn->error(AdminCode::getMessage(AdminCode::LOGIN_ERROR), AdminCode::LOGIN_ERROR)
);
}
$authorization = str_replace("Bearer ", "", $authorization);
$userJwt = $this->cryptoFactory->cryptoClass('admin-jwt', $authorization)->decrypt();
if (empty($userJwt)) {
return $this->response->json(
$this->apiReturn->error(AdminCode::getMessage(AdminCode::LOGIN_TOKEN_ERROR), AdminCode::LOGIN_TOKEN_ERROR)
);
}
//单点登录
if ($this->userCache->getAdminToken($userJwt['data']->id) != $authorization) {
return $this->response->json(
$this->apiReturn->error(AdminCode::getMessage(AdminCode::LOGIN_TOKEN_ERROR), AdminCode::LOGIN_TOKEN_ERROR)
);
}
Context::set('admin_id',$userJwt['data']->id);
Context::set('role_id',$userJwt['data']->role);
return $handler->handle($request);
}
}