adminMiddleware.php 1.9 KB

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