| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- /**
- * 认证服务.
- *
- * @author nj
- * @date 2021-01-22 11:36:11
- */
- namespace Modules\AgentApi\Services;
- use App\Constants\AgentConstant;
- use App\Constants\CommonConstant;
- use App\Constants\ManageConstant;
- use App\Repositories\Utils\JwtRepository;
- use Psr\SimpleCache\CacheInterface;
- use Cache;
- use Str;
- class AgentAuthService
- {
- /**
- * Jwt受众.
- *
- * @var string
- */
- private $jwtAud = 'agent-users';
- /**
- * 获取存储用户设备Token的缓存Key.
- * @param string $agentUid
- * @return string
- */
- public function getAgentCacheKey($agentUid)
- {
- $cacheKey = 'agent_auth_'. $agentUid;
- return $cacheKey;
- }
- /**
- * 创建单点Jwt.
- * @param string $agentUid 代理UID
- * @param int $roleId 角色ID
- * @return array
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public function createSingleJwt($agentUid)
- {
- $agent = new \stdClass();
- $agent->uid = $agentUid;
- /**
- * @var JwtRepository $jwtRepository
- */
- $jwtRepository = make(JwtRepository::class);
- $tokenInfo = $jwtRepository->createAgentJwt($agent);
- $token = $tokenInfo['token'];
- $cacheKey = $this->getAgentCacheKey($agentUid);
- /**
- * @var Cache $cache
- */
- $cache = make('cache');
- $cacheToken = $cache->has($cacheKey) ? $cache->get($cacheKey) : '';
- if (!empty($cacheToken)) {
- $cache->delete($cacheKey);
- }
- $cache->set($cacheKey, $token, config('jwt.ttl') * 60);
- return $tokenInfo;
- }
- /**
- * 获取头部Token.
- * @return mixed
- */
- public function getHeaderToken()
- {
- $token = request()->header(AgentConstant::AG_TOKEN_NAME, null);
- if (empty($token)) {
- // 支持GET/PUT获取token
- $token = request()->input(AgentConstant::AG_TOKEN_NAME, null);
- }
- return $token;
- }
- /**
- * 获取Token中的AgentInfo
- * @return array 返回agent_uid
- */
- public function getAgentInfo()
- {
- $managerInfo = [];
- $token = $this->getHeaderToken();
- if (!empty($token)) {
- /**
- * @var JwtRepository $jwtRepository
- */
- $jwtRepository = make(JwtRepository::class);
- $validateResult = $jwtRepository->validateToken($token, $this->jwtAud);
- if ($validateResult['is_valid']) {
- $claim = $validateResult['token_obj']->claims();
- $managerInfo = [
- 'agent_uid' => !empty($claim->get('agent_uid')) ? $claim->get('agent_uid') : '',
- ];
- }
- }
- return $managerInfo;
- }
- }
|