BAdminRepository.php 2.5 KB

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