normalizePath($request->path()); if (in_array($path, (array) config('nl.api.white_list', []), true)) { return $next($request); } try { $userInfo = JWTService::getInstance()->getToken()->getUserInfo(); } catch (\Throwable $e) { return $this->deny($e->getMessage() ?: '请先登录', ErrorEnum::NOT_AUTH); } if (empty($userInfo['id'])) { return $this->deny('请先登录', ErrorEnum::NOT_AUTH); } $roleId = (int) ($userInfo['role_id'] ?? 0); if (!PermissionService::getInstance()->allows($roleId, $path)) { return $this->deny('没有该操作的权限,请联系管理员', ErrorEnum::NOT_PERMISSION); } // 后续无需再解 token 的地方可以直接取 $request->attributes->set('nl_user', $userInfo); return $next($request); } private function normalizePath(string $path): string { $path = trim($path, '/'); if (str_starts_with($path, 'api/')) { $path = substr($path, 4); } return trim($path, '/'); } /** * HTTP 恒 200、业务码表达失败,与前端 request.ts 拦截器的约定一致 */ private function deny(string $message, ErrorEnum $code): Response { return response()->json([ 'code' => $code->value, 'message' => $message, 'result' => [], 'type' => 'error', ]); } }