| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- <?php
- declare (strict_types=1);
- namespace app\middleware;
- use app\service\MenuService;
- use Firebase\JWT\JWT;
- use Firebase\JWT\Key;
- use think\facade\Config;
- use think\Response;
- class AuthMiddleware
- {
- /**
- * 处理请求
- */
- public function handle($request, \Closure $next)
- {
- // 获取当前控制器和操作
- $controller = $request->controller();
- $action = $request->action();
-
- // 检查是否在登录白名单中(不需要登录验证)
- if ($this->isLoginWhitelisted($controller, $action)) {
- return $next($request);
- }
-
- // 验证登录状态
- $userInfo = $this->checkLogin($request);
- if (!$userInfo) {
- return json_error([], '请先登录', 401);
- }
-
- // 将用户信息注入请求
- $request->userInfo = $userInfo;
- $request->userId = (int)$userInfo['user_id'];
-
- // 检查是否在权限白名单中(需要登录但不需要权限验证)
- if ($this->isPermissionWhitelisted($controller, $action)) {
- return $next($request);
- }
-
- // 验证权限
- if (!$this->checkPermission((int)$userInfo['user_id'], $controller, $action)) {
- return json_error([], '无权限访问', 403);
- }
-
- return $next($request);
- }
-
- /**
- * 检查登录状态
- */
- protected function checkLogin($request): ?array
- {
- $token = $request->cookie('auth_token');
- if (!$token) {
- return null;
- }
-
- $decoded = parseToken($token);
- if (!$decoded) {
- return null;
- }
-
- return $decoded;
- }
-
- /**
- * 检查权限
- */
- protected function checkPermission(int $userId, string $controller, string $action): bool
- {
- // 使用MenuService检查权限
- return MenuService::checkPermission($userId, $controller, $action);
- }
-
- /**
- * 检查是否在登录白名单中
- */
- protected function isLoginWhitelisted(string $controller, string $action): bool
- {
- $whitelist = Config::get('menu.login_whitelist', []);
-
- // 检查控制器级别白名单
- $controllers = $whitelist['controllers'] ?? [];
- if (in_array($controller, $controllers)) {
- return true;
- }
-
- // 检查具体方法白名单
- $actions = $whitelist['actions'] ?? [];
- $current = $controller . '/' . $action;
- if (in_array($current, $actions)) {
- return true;
- }
-
- return false;
- }
-
- /**
- * 检查是否在权限白名单中
- */
- protected function isPermissionWhitelisted(string $controller, string $action): bool
- {
- $whitelist = Config::get('menu.permission_whitelist', []);
-
- // 检查控制器级别白名单
- $controllers = $whitelist['controllers'] ?? [];
- if (in_array($controller, $controllers)) {
- return true;
- }
-
- // 检查具体方法白名单
- $actions = $whitelist['actions'] ?? [];
- $current = $controller . '/' . $action;
- if (in_array($current, $actions)) {
- return true;
- }
-
- return false;
- }
- }
|