UserMiddleware.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | [ WE CAN DO IT MORE SIMPLE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2018-2020 rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: TABLE ME
  8. // +----------------------------------------------------------------------
  9. // | Date: 2020-08-30 14:59
  10. // +----------------------------------------------------------------------
  11. namespace app\api\middleware;
  12. use app\model\api\Member;
  13. use app\model\api\Site;
  14. use app\Request;
  15. use Firebase\JWT\JWT;
  16. use library\exceptions\AuthException;
  17. use library\interfaces\MiddlewareInterface;
  18. use think\facade\Env;
  19. class UserMiddleware implements MiddlewareInterface
  20. {
  21. public function handle(Request $request, \Closure $next)
  22. {
  23. $token =$request->header('TOKEN');
  24. $request->user = $this->checkUser($token);
  25. return $next($request);
  26. }
  27. /**
  28. * 检查数据是否正常
  29. * @param $token
  30. */
  31. private function checkUser($token) {
  32. try{
  33. list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
  34. $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
  35. $uid = $payload->uid;
  36. $member = (new Member)->where('uid',$uid)->find();
  37. if(empty($member)) {
  38. throw new AuthException('请重新登录', -99);
  39. }
  40. return $member->toArray();
  41. }catch (\Throwable $e) {
  42. throw new AuthException('请重新登录', -99);
  43. }
  44. }
  45. }