46 lines
1.5 KiB
PHP
46 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Middleware\Api;
|
|
|
|
use App\Constants\ApiCode;
|
|
use App\Lib\ApiReturn;
|
|
use App\Lib\Crypto\CryptoFactory;
|
|
use Hyperf\Context\Context;
|
|
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Psr\Http\Server\MiddlewareInterface;
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
|
|
|
class JwtAuthMiddleware implements MiddlewareInterface
|
|
{
|
|
public function __construct(
|
|
protected HttpResponse $response,
|
|
protected ApiReturn $apiReturn,
|
|
protected CryptoFactory $cryptoFactory,
|
|
){}
|
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
|
{
|
|
// 获取头部token
|
|
$authorization = $request->getHeaderLine('Authorization');
|
|
|
|
if (empty($authorization)){
|
|
return $this->response->json(
|
|
$this->apiReturn->error(ApiCode::getMessage(ApiCode::LOGIN_ERROR), ApiCode::LOGIN_ERROR)
|
|
);
|
|
}
|
|
|
|
$authorization = str_replace("Bearer ", "", $authorization);
|
|
$userJwt = $this->cryptoFactory->cryptoClass('jwt', $authorization)->decrypt();
|
|
if (empty($userJwt)) {
|
|
return $this->response->json(
|
|
$this->apiReturn->error(ApiCode::getMessage(ApiCode::LOGIN_TOKEN_ERROR), ApiCode::LOGIN_TOKEN_ERROR)
|
|
);
|
|
}
|
|
|
|
Context::set('user_id',$userJwt['data']->id);
|
|
|
|
return $handler->handle($request);
|
|
}
|
|
} |