UserTokenMiddleware.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * @package merchant
  4. *
  5. * @author xaboy
  6. * @day 2020-03-24
  7. *
  8. *
  9. */
  10. namespace app\middleware;
  11. use app\controller\Auth;
  12. use app\Request;
  13. use think\Response;
  14. use app\exceptions\AuthException;
  15. class UserTokenMiddleware
  16. {
  17. public function handle(Request $request,\Closure $next)
  18. {
  19. $XToken = $request->header('X-Token');
  20. if(!$XToken) throw new AuthException('token不存在');
  21. $token = trim($request->header('X-Token'));
  22. if (!$token) throw new AuthException('无效的token');
  23. $data = Auth::checkToken($token,$request->param());
  24. if(!$data) throw new AuthException('无效的token!');
  25. if(isset($data['code']) && $data['code'] == 101) throw new AuthException('用户不存在');
  26. if(isset($data['code']) && $data['code'] == 500) throw new AuthException('系统错误');
  27. $request->macro('token', function () use (&$token) {
  28. return $token;
  29. });
  30. $request->macro('userInfo', function () use (&$data) {
  31. return $data['userInfo'];
  32. });
  33. $request->macro('uid', function () use (&$data) {
  34. return $data['userInfo']['uid'];
  35. });
  36. return $next($request);
  37. }
  38. public function after(Response $response)
  39. {
  40. // TODO: Implement after() method.
  41. }
  42. }