123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace crmeb\utils;
- use crmeb\exceptions\AdminException;
- use crmeb\services\CacheService;
- use Firebase\JWT\JWT;
- use think\facade\Env;
- class JwtAuth
- {
-
- protected $token;
-
- protected $app_key = 'crmeb_app_key';
-
- public function getToken(int $id, string $type, array $params = []): array
- {
- $host = app()->request->host();
- $time = time();
- $exp_time = strtotime('+ 7day');
- if (app()->request->isApp()) {
- $exp_time = strtotime('+ 30day');
- }
- if ($type == 'out') {
- $exp_time = strtotime('+ 1day');
- }
- $params += [
- 'iss' => $host,
- 'aud' => $host,
- 'iat' => $time,
- 'nbf' => $time,
- 'exp' => $exp_time,
- ];
- $params['jti'] = compact('id', 'type');
- $token = JWT::encode($params, Env::get('app.app_key', $this->app_key) ?: $this->app_key);
- return compact('token', 'params');
- }
-
- public function parseToken(string $jwt): array
- {
- $this->token = $jwt;
- [$headb64, $bodyb64, $cryptob64] = explode('.', $this->token);
- $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
- return [$payload->jti->id, $payload->jti->type, $payload->auth ?? ''];
- }
-
- public function verifyToken()
- {
- JWT::$leeway = 60;
- JWT::decode($this->token, Env::get('app.app_key', $this->app_key) ?: $this->app_key, array('HS256'));
- $this->token = null;
- }
-
- public function createToken(int $id, string $type, array $params = [])
- {
- $tokenInfo = $this->getToken($id, $type, $params);
- $exp = $tokenInfo['params']['exp'] - $tokenInfo['params']['iat'] + 60;
- $res = CacheService::setTokenBucket(md5($tokenInfo['token']), ['uid' => $id, 'type' => $type, 'token' => $tokenInfo['token'], 'exp' => $exp], (int)$exp, $type);
- if (!$res) {
- throw new AdminException(ApiErrorCode::ERR_SAVE_TOKEN);
- }
- return $tokenInfo;
- }
- }
|