12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- <?php
- namespace app\admin\middleware;
- use app\admin\logic\BaseLogic;
- use think\Exception;
- use think\exception\ValidateException;
- use think\facade\Cache;
- use think\facade\Config;
- use think\facade\Validate;
- use think\Response;
- use app\model\ActionLogModel;
- //中间件
- class apiMiddleware
- {
- //白名单
- private $white_list = ['login','test'];
- //请求入口
- public function handle($request, \Closure $next)
- {
- //请求的唯一标识
- $request->request_id = date('YmdHis') . mt_rand(100000, 999999);
- //接收参数
- $param = $request->post();
- //记录日志
- ActionLogModel::add($request->request_id, $param);
- //判断白名单
- if (!in_array(request()->pathinfo(), $this->white_list)) {
- $val = Validate::rule(['token'=>'require']);
- if(!$val->check($param)) throw new ValidateException($val->getError());
- //获取用户信息
- $user = verifyToken($param['token']);
- BaseLogic::setUserInfo($user);
- $request->uid = $user['uid'];
- $request->uname = $user['uname'];
- $request->roleid = $user['roleid'];
- }
- return $next($request);
- }
- //请求结束的回调(如果返回数据用的是app_show/error_show,即直接echo,则不会触发该方法)
- public function end(Response $response)
- {
- //只做记录,不做输出
- ActionLogModel::where('request_id', request()->request_id)->save([
- 'response' => $response->getContent(),
- 'uid' => request()->uid ?? 0,
- 'uname' => request()->uname ?? '',
- ]);
- }
- }
|