AdminAuthTokenMiddleware.php 2.8 KB

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