CheckAuth.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace app\common\middleware;
  3. use Exception;
  4. use thans\jwt\exception\TokenInvalidException;
  5. use thans\jwt\facade\JWTAuth;
  6. use think\facade\Cache;
  7. //验证权限
  8. class CheckAuth
  9. {
  10. public function handle($request, \Closure $next)
  11. {
  12. try {
  13. $jwtData = JWTAuth::auth();
  14. } catch (Exception $exception) {
  15. //token有误
  16. if (get_class($exception) == TokenInvalidException::class) {
  17. return shutdown(lang('user.loginError'), -1);
  18. }
  19. $errorMsgArr = [
  20. 'Must have token' => lang('user.mustToken'),
  21. 'The token is in blacklist.' => lang('user.blacklist'),
  22. 'The token is expired.' => lang('user.expired'),
  23. 'The token is in blacklist grace period list.' => lang('user.expired')
  24. ];
  25. return shutdown($errorMsgArr[$exception->getMessage()] ?? $exception->getMessage(), -1);
  26. }
  27. $userInfo = $jwtData['info']->getValue();
  28. //解密token中的用户信息
  29. $userInfo = str_encipher($userInfo,false, config('app.aes_token_key'));
  30. if (!$userInfo) {
  31. return shutdown(lang('user.loginError'), -1);
  32. }
  33. //解析json
  34. $userInfo = (array)json_decode($userInfo, true);
  35. if(cache('forbidUser_'.$userInfo['id'])){
  36. JWTAuth::invalidate(JWTAuth::token()->get());
  37. Cache::delete('forbidUser_'.$userInfo['id']);
  38. return shutdown(lang('user.forbid'), -1);
  39. }
  40. //已经登陆,将用户信息存入请求头
  41. $request->userInfo = $userInfo;
  42. $request->uid = $userInfo['id'];
  43. $request->userToken = JWTAuth::token()->get();
  44. return $next($request);
  45. }
  46. }