tapi/app/http/middleware/AuthMiddleware.php
2025-08-28 16:58:10 +08:00

76 lines
2.2 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\http\middleware;
use app\entity\SysUserClient;
use app\model\SysUser;
use app\Request;
use app\service\admin\LoginService;
use Closure;
use think\exception\ValidateException;
use think\Middleware;
use think\Response;
/**
* 权限校验中间件
*/
class AuthMiddleware extends Middleware
{
/*
* 请求接口白名单列表
*/
protected array $whiteList = [];
public function handle(Request $request, Closure $next)
{
/*
* 权限校验
*/
$authorization = (string)$request->header('authorization', '');
$authorization = str_replace('Bearer ', '', $authorization);
$loginSrv = new LoginService();
if (!in_array($request->pathinfo(), $this->whiteList, true)) {
try{
$auth = $loginSrv->checkUserAccessToken($authorization);
}catch (ValidateException $e){
return json(['code' => 401, 'message' => $e->getMessage()]);
}
} else {
$auth = $loginSrv->getVisitor($request);
return json(['code' => 401, 'message' => '禁止访问']);
}
$client = Request::getClient();
$clientModel = SysUserClient::where([
'client_id' => $client->id,
'client_name'=> $client->name,
'user_id' => $auth->userId
])->find();
if(empty($clientModel)) {
return json(['code' => 401, 'message' => '设备下线']);
}
if(1 != $clientModel->status) {
return json(['code' => 401, 'message' => '设备禁用']);
}
/*
* 注入获取用户信息的function
*/
$auth::macro('getUser', function () use ($auth) {
return SysUser::cache("sysUserInfo:{$auth->userId}", 180, 'sysUserInfoLists')->findOrFail($auth->userId);
});
return $next($request->setAuth($auth));
}
// /**
// * 结束调度
// * @中间件支持定义请求结束前的回调机制你只需要在中间件类中添加end方法。
// * @param Response $response
// */
// public function end(Response $response)
// {
// // 回调行为
// }
}