CheckAuth.php 2.4 KB

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