123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- declare(strict_types=1);
- namespace App\Utils\Encrypt;
- use App\Master\Enum\RedisKeyEnum;
- use App\Utils\RedisUtil;
- use Hyperf\Config\Annotation\Value;
- use Hyperf\Coroutine\Coroutine;
- class Token
- {
-
-
- protected array $config;
- private static $instances = [];
-
- public static function getInstance()
- {
- $instanceName = Coroutine::id() . uniqid();
- if (!isset(self::$instances[$instanceName])) {
- self::$instances[$instanceName] = new self();
- Coroutine::defer(function () use ($instanceName) {
- unset(self::$instances[$instanceName]);
- });
- }
- return self::$instances[$instanceName];
- }
-
- public function create(array $data): string
- {
- $data = array_merge($data, [
- 'iat' => time(),
- 'exp' => time() + $this->config['expire'],
- ]);
- $dataJson = json_encode($data, JSON_UNESCAPED_UNICODE);
- $token = Aes::encode($dataJson, $this->config['key']);
-
- if ($this->config['sso'] === true) {
- $token_key = (string)key($data);
- $token_id = (string)reset($data);
- RedisUtil::getInstance(RedisKeyEnum::TOKEN_ONCE, $token_key, $token_id)->setex($token, $this->config['expire']);
- }
- return $token;
- }
-
- public function check(string $token)
- {
-
- if (!$data = Aes::decode($token, $this->config['key'])) {
- return false;
- }
- $data = json_decode($data, true);
-
- if ($this->config['sso'] === true) {
- $token_key = (string)key($data);
- $token_id = (string)reset($data);
- if (!$userToken = RedisUtil::getInstance(RedisKeyEnum::TOKEN_ONCE, $token_key, $token_id)->get()) {
- return false;
- }
- if ($userToken != $token) {
- return false;
- }
- }
- return $data;
- }
-
- public function remove(array $data)
- {
-
- if ($this->config['sso'] === true) {
- $token_key = (string)key($data);
- $token_id = (string)reset($data);
-
- if (!RedisUtil::getInstance(RedisKeyEnum::TOKEN_ONCE, $token_key, $token_id)->del()) {
- return false;
- }
- }
- return true;
- }
- }
|