AdminRepository.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace crmeb\repositories;
  3. use app\models\system\SystemAdmin;
  4. use crmeb\exceptions\AuthException;
  5. use crmeb\services\CacheService;
  6. use Firebase\JWT\ExpiredException;
  7. use think\db\exception\ModelNotFoundException;
  8. use think\db\exception\DataNotFoundException;
  9. use think\exception\DbException;
  10. use think\facade\Cache;
  11. use Firebase\JWT\JWT;
  12. /**
  13. * Class UserRepository
  14. * @package crmeb\repositories
  15. */
  16. class AdminRepository
  17. {
  18. /**
  19. * 获取Admin授权信息
  20. * @param $token
  21. * @param int $expires
  22. * @param string $prefix
  23. * @return array
  24. * @throws \Psr\SimpleCache\InvalidArgumentException
  25. */
  26. public static function adminParseToken($token): array
  27. {
  28. if (!$token || !CacheService::hasToken($token) || !($cacheToken = CacheService::getTokenBucket($token)))
  29. throw new AuthException('Please login', 410000);
  30. if (isset($cacheToken['max']) && $cacheToken['max'] >= 3) {
  31. CacheService::clearToken($token);
  32. throw new AuthException('Landing overdue', 410001);
  33. }
  34. try {
  35. [$adminInfo, $type] = SystemAdmin::parseToken($token);
  36. CacheService::setTokenBucket($cacheToken['token'], $cacheToken, $cacheToken['exp']);
  37. } catch (ExpiredException $e) {
  38. list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
  39. $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
  40. $type = $payload->jti->type;
  41. $adminInfo = SystemAdmin::where('id', $payload->jti->id)->find();
  42. if (!$adminInfo) {
  43. CacheService::clearToken($token);
  44. throw new AuthException('Landing overdue', 410001);
  45. }
  46. if (isset($cacheToken['max'])) {
  47. $cacheToken['max'] = bcadd($cacheToken['max'], 1, 0);
  48. } else {
  49. $cacheToken['max'] = 1;
  50. }
  51. CacheService::setTokenBucket($cacheToken['token'], $cacheToken, $cacheToken['exp']);
  52. } catch (\Throwable $e) {
  53. CacheService::clearToken($token);
  54. throw new AuthException('Landing overdue', 410001);
  55. }
  56. if (!isset($adminInfo) || !$adminInfo || !$adminInfo->id || $type != "admin") {
  57. CacheService::clearToken($token);
  58. throw new AuthException('The login status is incorrect. Please login again.', 410002);
  59. }
  60. $adminInfo->type = $type;
  61. return $adminInfo->toArray();
  62. }
  63. }