AgentAuthService.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. /**
  3. * 认证服务.
  4. *
  5. * @author nj
  6. * @date 2021-01-22 11:36:11
  7. */
  8. namespace Modules\AgentApi\Services;
  9. use App\Constants\AgentConstant;
  10. use App\Constants\CommonConstant;
  11. use App\Constants\ManageConstant;
  12. use App\Repositories\Utils\JwtRepository;
  13. use Psr\SimpleCache\CacheInterface;
  14. use Cache;
  15. use Str;
  16. class AgentAuthService
  17. {
  18. /**
  19. * Jwt受众.
  20. *
  21. * @var string
  22. */
  23. private $jwtAud = 'agent-users';
  24. /**
  25. * 获取存储用户设备Token的缓存Key.
  26. * @param string $agentUid
  27. * @return string
  28. */
  29. public function getAgentCacheKey($agentUid)
  30. {
  31. $cacheKey = 'agent_auth_'. $agentUid;
  32. return $cacheKey;
  33. }
  34. /**
  35. * 创建单点Jwt.
  36. * @param string $agentUid 代理UID
  37. * @param int $roleId 角色ID
  38. * @return array
  39. * @throws \Psr\SimpleCache\InvalidArgumentException
  40. */
  41. public function createSingleJwt($agentUid)
  42. {
  43. $agent = new \stdClass();
  44. $agent->uid = $agentUid;
  45. /**
  46. * @var JwtRepository $jwtRepository
  47. */
  48. $jwtRepository = make(JwtRepository::class);
  49. $tokenInfo = $jwtRepository->createAgentJwt($agent);
  50. $token = $tokenInfo['token'];
  51. $cacheKey = $this->getAgentCacheKey($agentUid);
  52. /**
  53. * @var Cache $cache
  54. */
  55. $cache = make('cache');
  56. $cacheToken = $cache->has($cacheKey) ? $cache->get($cacheKey) : '';
  57. if (!empty($cacheToken)) {
  58. $cache->delete($cacheKey);
  59. }
  60. $cache->set($cacheKey, $token, config('jwt.ttl') * 60);
  61. return $tokenInfo;
  62. }
  63. /**
  64. * 获取头部Token.
  65. * @return mixed
  66. */
  67. public function getHeaderToken()
  68. {
  69. $token = request()->header(AgentConstant::AG_TOKEN_NAME, null);
  70. if (empty($token)) {
  71. // 支持GET/PUT获取token
  72. $token = request()->input(AgentConstant::AG_TOKEN_NAME, null);
  73. }
  74. return $token;
  75. }
  76. /**
  77. * 获取Token中的AgentInfo
  78. * @return array 返回agent_uid
  79. */
  80. public function getAgentInfo()
  81. {
  82. $managerInfo = [];
  83. $token = $this->getHeaderToken();
  84. if (!empty($token)) {
  85. /**
  86. * @var JwtRepository $jwtRepository
  87. */
  88. $jwtRepository = make(JwtRepository::class);
  89. $validateResult = $jwtRepository->validateToken($token, $this->jwtAud);
  90. if ($validateResult['is_valid']) {
  91. $claim = $validateResult['token_obj']->claims();
  92. $managerInfo = [
  93. 'agent_uid' => !empty($claim->get('agent_uid')) ? $claim->get('agent_uid') : '',
  94. ];
  95. }
  96. }
  97. return $managerInfo;
  98. }
  99. }