AdminAuthTokenMiddleware.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | [ WE CAN DO IT MORE SIMPLE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2018-2020 rights reserved.
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // | Date: 2020-08-30 14:59
  10. // +----------------------------------------------------------------------
  11. namespace app\system\middleware;
  12. use app\model\system\Admin as AdminModel;
  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.system_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. if (!$token || !$redis->has($token) || !($cacheToken = $redis->get($token)))
  42. throw new AuthException('登录过期了,请重新登录', -9);
  43. try {
  44. [$adminInfo, $type] = AdminModel::parseToken($cacheToken['token']);
  45. Cache::store('redis')->set($token, $cacheToken, $cacheToken['exp']);
  46. } catch (ExpiredException $e) {
  47. list($headb64, $bodyb64, $cryptob64) = explode('.', $cacheToken['token']);
  48. $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
  49. $type = $payload->jti->type;
  50. $adminInfo = AdminModel::where('id', $payload->jti->id)->find();
  51. if (!$adminInfo) {
  52. $redis->delete($token);
  53. throw new AuthException('登录过期了,请重新登录', -9);
  54. }
  55. $redis->set($cacheToken['token'], $cacheToken, $cacheToken['exp']);
  56. } catch (\Throwable $e) {
  57. $redis->delete($token);
  58. throw new AuthException('登录过期了,请重新登录', -9);
  59. } catch (\Throwable $e) {
  60. throw new AuthException('登录过期了,请重新登录', -9);
  61. }
  62. if (!isset($adminInfo) || !$adminInfo || !$adminInfo->id) {
  63. $redis->delete($token);
  64. throw new AuthException('登录过期了,请重新登录', -9);
  65. }
  66. return $adminInfo->toArray();
  67. }
  68. }