CheckAuth.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. use think\facade\Request;
  8. //验证权限
  9. class CheckAuth
  10. {
  11. public function handle($request, \Closure $next)
  12. {
  13. try {
  14. //判断,如果当前控制的noNeedLogin 属性包含当前接口的名称,则不需要验证权限
  15. // $controller = $request->controller();
  16. // $action = $request->action();
  17. // $noNeedLogin = $controller->noNeedLogin;
  18. // if(in_array($action, $noNeedLogin)){
  19. // return $next($request);
  20. // }
  21. $jwtData = JWTAuth::auth();
  22. } catch (Exception $exception) {
  23. //token有误
  24. if (get_class($exception) == TokenInvalidException::class) {
  25. return shutdown(lang('user.loginError'), -1);
  26. }
  27. $errorMsgArr = [
  28. 'Must have token' => lang('user.mustToken'),
  29. 'The token is in blacklist.' => lang('user.blacklist'),
  30. 'The token is expired.' => lang('user.expired'),
  31. 'The token is in blacklist grace period list.' => lang('user.expired')
  32. ];
  33. return shutdown($errorMsgArr[$exception->getMessage()] ?? $exception->getMessage(), -1);
  34. }
  35. $adminInfo = [];
  36. if (!empty($jwtData['admin'])) {
  37. $adminInfo = $jwtData['admin']->getValue();
  38. }
  39. $userInfo = $jwtData['info']->getValue();
  40. //解密token中的用户信息
  41. $userInfo = str_encipher($userInfo,false, config('app.aes_token_key'));
  42. if (!$userInfo) {
  43. return shutdown(lang('user.loginError'), -1);
  44. }
  45. //解析json
  46. $userInfo = (array)json_decode($userInfo, true);
  47. if(cache('forbidUser_'.$userInfo['id'])){
  48. JWTAuth::invalidate(JWTAuth::token()->get());
  49. Cache::delete('forbidUser_'.$userInfo['id']);
  50. return shutdown(lang('user.forbid'), -1);
  51. }
  52. //已经登陆,将用户信息存入请求头
  53. $request->adminInfo = $adminInfo;
  54. $request->userInfo = $userInfo;
  55. $request->uid = $userInfo['id'];
  56. $request->userToken = JWTAuth::token()->get();
  57. return $next($request);
  58. }
  59. }