container = $container; $this->response = $response; $this->request = $request; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { //日志统一写入 LogUtil::getInstance(self::PROJECT . "/");//设置日志存入通道 Coroutine::defer(function () { LogUtil::close();// 协程结束后统一写入 }); $this->action = ActionUtil::getInstance()->actions($request,self::PROJECT); $params = $this->request->all(); // 记录用户请求参数 LogUtil::info('请求参数', $this->action['controller'], $this->action['action'], $params); //接口限流,写到中间件中 if (!RedisUtil::getInstance(RedisKeyEnum::API_REQUEST_TRAFFIC)->requestLimit("{$this->action['controller']}/{$this->action['action']}", 1, 10)) { LogUtil::info('请求次数过多', $this->action['controller'], $this->action['action']); return $this->response206(); } $token = $this->request->header('token'); if (empty($token)) $token = $params['token'] ?? ''; if (!empty($token) && !in_array("{$this->action['controller']}/{$this->action['action']}", self::tokenWhiteList())) { LogUtil::info('token 验证开始', $this->action['controller'], $this->action['action'], (string)$token); // 校验token if (!$user_id = $this->checkToken($token)){ return $this->response401(); } // 查询并记录用户信息 $user = (new UserModel())->authUserInfo($user_id); if (!$user) { LogUtil::warning('账号不存在', $this->action['controller'], $this->action['action'], ['user_id', $user_id]); return $this->response401(); } LogUtil::info('用户编号', $this->action['controller'], $this->action['action'], $user_id); AuthUser::getInstance()->set(json_decode(json_encode($user), true)); } return $handler->handle($request); } /** * 校验token * * @param string $token * @return false|int */ public function checkToken(string $token): false|int { $checkToken = TokenFast::get($token); if (!$checkToken) { LogUtil::warning('token 验证失败', $this->action['controller'], $this->action['action'], $checkToken); return false; } //验证参数信息 if (empty($checkToken['user_id'])) { LogUtil::warning('token 参数不全', $this->action['controller'], $this->action['action'], $checkToken); return false; } return (int)$checkToken['user_id']; } /** * 令牌失效 * * @param string $message * @param $result * @return ResponseInterface */ private function response401(string $message = '令牌失效,请稍后重试!', $result = null): ResponseInterface { // 记录令牌校验 LogUtil::info($message, $this->action['controller'], $this->action['action'], $result); return AppResult::response_fast(401,$message, $result); } /** * 请求频繁 * * @param string $message * @param $result * @return ResponseInterface */ private function response206(string $message = '当前访问人数过多,请稍后再试!', $result = null): ResponseInterface { // 记录令牌校验 LogUtil::info($message, $this->action['controller'], $this->action['action'], $result); return AppResult::response_fast(206,$message, $result); } /** * token校验黑名单 * @return string[] */ public function tokenWhiteList(): array { return [ 'v1/UserController/login', ]; } }