AdminAuthTokenMiddleware.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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\admin\middleware;
  12. use app\model\admin\Admin;
  13. use app\Request;
  14. use Firebase\JWT\ExpiredException;
  15. use Firebase\JWT\JWT;
  16. use library\exceptions\AuthException;
  17. use library\interfaces\MiddlewareInterface;
  18. use think\facade\Cache;
  19. use think\facade\Config;
  20. class AdminAuthTokenMiddleware implements MiddlewareInterface
  21. {
  22. public function handle(Request $request, \Closure $next)
  23. {
  24. $authInfo = null;
  25. $token = trim($request->header(Config::get('cookie.admin_token_name','')), );
  26. $adminInfo = $this->adminParseToken($token);
  27. $request->adminInfo = $adminInfo;
  28. return $next($request);
  29. }
  30. /**
  31. * 获取Admin授权信息
  32. * @param $token
  33. * @param int $expires
  34. * @param string $prefix
  35. * @return array
  36. * @throws \Psr\SimpleCache\InvalidArgumentException
  37. */
  38. public static function adminParseToken($token): array
  39. {
  40. $redis = Cache::store('redis');
  41. try {
  42. if (!$token || !$redis->has($token) || !($cacheToken = $redis->get($token)))
  43. throw new AuthException('请重新登录', -909);
  44. [$adminInfo, $type] = Admin::parseToken($token);
  45. Cache::store('redis')->set($cacheToken['token'], $cacheToken, $cacheToken['exp']);
  46. } catch (ExpiredException $e) {
  47. list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
  48. $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
  49. $type = $payload->jti->type;
  50. $adminInfo = Admin::where('id', $payload->jti->id)->find();
  51. if (!$adminInfo) {
  52. $redis->delete($token);
  53. throw new AuthException('登录超时,请重新登录!', -909);
  54. }
  55. $redis->set($cacheToken['token'], $cacheToken, $cacheToken['exp']);
  56. } catch (\Throwable $e) {
  57. $redis->delete($token);
  58. throw new AuthException('登录超时,请重新登录!', -909);
  59. } catch (\Throwable $e) {
  60. throw new AuthException('登录超时,请重新登录!', -909);
  61. }
  62. if (!isset($adminInfo) || !$adminInfo || !$adminInfo->id) {
  63. $redis->delete($token);
  64. throw new AuthException('登录超时,请重新登录!', -909);
  65. }
  66. $adminInfo->type = $type;
  67. return $adminInfo->toArray();
  68. }
  69. }