| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- <?php
- namespace app\common\library\token\driver;
- use app\common\library\token\Driver;
- use think\Config;
- /**
- * Token操作类
- */
- class Redis extends Driver
- {
- protected array $options = [
- 'host' => '127.0.0.1',
- 'port' => 6379,
- 'password' => '',
- 'select' => 0,
- 'timeout' => 0,
- 'persistent' => false,
- ];
- /**
- * 构造函数
- * @throws \BadFunctionCallException
- * @access public
- */
- public function __construct()
- {
- if (!extension_loaded('redis')) {
- throw new \BadFunctionCallException('not support: redis');
- }
- $this->options = array_merge($this->options, \think\Config::get('redis')); // 读取redis的配置信息
- $this->handler = new \Redis;
- if ($this->options['persistent']) {
- $this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
- } else {
- $this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']);
- }
- if ('' != $this->options['password']) {
- $this->handler->auth($this->options['password']);
- }
- if (0 != $this->options['select']) {
- $this->handler->select($this->options['select']);
- }
- }
- /**
- * 存储Token
- * @param int $userID 用户ID
- * @param string $token 凭证
- * @return bool
- */
- public function set(int $userID, string $token): bool
- {
- return $this->handler->hSet($this->userTokenKey, $userID, $token);
- }
- /**
- * 获取Token内的信息
- * @param string $token
- * @return array
- */
- public function get(int $userID): array
- {
- // 判断redis中是否存在
- $value = $this->handler->hGet($this->userTokenKey, $userID);
- if (is_null($value) || false === $value) {
- return [];
- }
- // 解码
- $tokenArr = json_decode($value,true);
- if (is_null($tokenArr) || false === $tokenArr) {
- return [];
- }
- return $tokenArr;
- }
- /**
- * 获取加密后的Token
- * @param int $userID 用户ID
- * @return string
- */
- public function getEncryptedToken(int $userID): string
- {
- // 对json数据进行base64编码
- return base64_encode(json_encode(self::get($userID), JSON_UNESCAPED_UNICODE));
- }
- /**
- * 判断Token是否可用
- * @param string $token Token
- * @param int $userID 会员ID
- * @return boolean
- */
- public function check(int $userID, string $token): bool
- {
- $data = self::get($userID);
- return $data && $data['user_id'] == $userID && $data['token'] == $token && $data['create_time'] + Config::get('token.duration') > time();
- }
- /**
- * 删除用户的Token
- * @param int $userID 会员ID
- * @return boolean
- */
- public function delete(int $userID): bool
- {
- $data = $this->get($userID);
- if ($data) {
- $this->handler->hDel($this->userTokenKey, $userID);
- }
- return true;
- }
- }
|