travel/service/app/middleware/adminAuth.php

73 lines
2.3 KiB
PHP
Raw Normal View History

2024-06-24 11:52:30 +08:00
<?php
namespace app\middleware;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
2024-07-01 14:43:47 +08:00
use support\Log;
2024-06-24 11:52:30 +08:00
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use support\Redis;
class adminAuth implements MiddlewareInterface
{
public function process(Request $request, callable $next): Response
{
$path = $request->path();
if($path) {
//白名单
$url = [
2024-06-27 19:53:53 +08:00
'/admin/login',
2024-07-09 16:15:32 +08:00
'admin/index/avatar',
'admin/upload/index',
2024-06-24 11:52:30 +08:00
];
if(in_array($path, $url)) {
return $next($request);
}
}
$token = $request->header('X-Token');
if(empty($token)) {
$token = $request->cookie('vue_admin_template_token');
}
if(empty($token)) {
$token = $request->cookie('AdminToken');
}
if(empty($token)) {
return response(json_encode(['code' => 403, 'msg'=> 'token expire']));
}
//判断是否退出登录
$md5 = md5($token);
$logout = Redis::get('Admin:logout:'.$md5);
if(!empty($logout)) {
return response(json_encode(['code' => 400, 'msg'=> 'token expire']));
}
try {
$key = new Key(config('app.jwt_key_admin'), 'HS256'); // 密钥
$decoded = JWT::decode(str_replace('Bearer ','',$token), $key);
if(!empty($decoded) && $decoded->data && $decoded->data->id) {
$id = $decoded->data->id;
$disabled = Redis::get('Admin:disabled:'.$id);
//用户是否被禁用了
if($disabled) {
return response(json_encode(['code' => 405, 'msg'=> 'token disabled']));
}
$request->admin = $decoded->data;
$request->token = $token;
}else {
return response(json_encode(['code' => 401, 'msg'=> 'token expired']));
}
}catch (ExpiredException $e){
return response(json_encode(['code' => 401, 'msg'=> 'token expired']));
}catch (\Exception $e){
return response(json_encode(['code' => 402, 'msg'=> 'token expire']));
}
$response = $next($request);
return $response;
}
}