apiMiddleware.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace app\admin\middleware;
  3. use app\admin\logic\BaseLogic;
  4. use think\Exception;
  5. use think\exception\ValidateException;
  6. use think\facade\Cache;
  7. use think\facade\Config;
  8. use think\facade\Validate;
  9. use think\Response;
  10. use app\model\ActionLogModel;
  11. //中间件
  12. class apiMiddleware
  13. {
  14. //白名单
  15. private $white_list = ['login','test'];
  16. //请求入口
  17. public function handle($request, \Closure $next)
  18. {
  19. //请求的唯一标识
  20. $request->request_id = date('YmdHis') . mt_rand(100000, 999999);
  21. //接收参数
  22. $param = $request->post();
  23. //记录日志
  24. ActionLogModel::add($request->request_id, $param);
  25. //判断白名单
  26. if (!in_array(request()->pathinfo(), $this->white_list)) {
  27. $val = Validate::rule(['token'=>'require']);
  28. if(!$val->check($param)) throw new ValidateException($val->getError());
  29. //获取用户信息
  30. $user = verifyToken($param['token']);
  31. BaseLogic::setUserInfo($user);
  32. $request->uid = $user['uid'];
  33. $request->uname = $user['uname'];
  34. $request->roleid = $user['roleid'];
  35. }
  36. return $next($request);
  37. }
  38. //请求结束的回调(如果返回数据用的是app_show/error_show,即直接echo,则不会触发该方法)
  39. public function end(Response $response)
  40. {
  41. //只做记录,不做输出
  42. ActionLogModel::where('request_id', request()->request_id)->save([
  43. 'response' => $response->getContent(),
  44. 'uid' => request()->uid ?? 0,
  45. 'uname' => request()->uname ?? '',
  46. ]);
  47. }
  48. }