47 lines
1.7 KiB
PHP
47 lines
1.7 KiB
PHP
<?php
|
|
declare (strict_types = 1);
|
|
|
|
namespace app\middleware;
|
|
|
|
use app\config\BusinessCacheKey;
|
|
use app\config\BusinessCode;
|
|
use app\exception\BusinessException;
|
|
use app\service\util\RedisService;
|
|
use app\util\SessionUtil;
|
|
use Firebase\JWT\ExpiredException;
|
|
use Firebase\JWT\SignatureInvalidException;
|
|
|
|
class Request
|
|
{
|
|
public function handle(\think\Request $request, \Closure $next): \think\Response
|
|
{
|
|
$token = SessionUtil::getToken();
|
|
if (empty($token)) {
|
|
throw new BusinessException('需要登录', BusinessCode::LOGIN_INVALID);
|
|
}
|
|
$client = RedisService::getRedisInstance();
|
|
if (empty($client->sismember(BusinessCacheKey::SITE_TOKEN_LIST['key'], $token))) {
|
|
throw new BusinessException('需要登录', BusinessCode::LOGIN_INVALID);
|
|
}
|
|
try {
|
|
$data = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(env('jwt_token_key'), 'HS256'));
|
|
SessionUtil::setUser($data->data);
|
|
} catch (ExpiredException $e) {
|
|
throw new BusinessException('请重新授权登陆', BusinessCode::LOGIN_INVALID);
|
|
} catch (SignatureInvalidException|\Throwable $e) {
|
|
throw new BusinessException('签名验证失败', BusinessCode::LOGIN_INVALID);
|
|
}
|
|
return $next($request);
|
|
}
|
|
|
|
public function end(\think\Response $response): \think\Response
|
|
{
|
|
$response->header([
|
|
'Access-Control-Allow-Origin' => '*',
|
|
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
|
|
'Access-Control-Allow-Headers' => 'X-Requested-With, Content-Type, Accept, Origin, token,Status Code'
|
|
]);
|
|
return $response;
|
|
}
|
|
}
|