'user_token', 'expire' => 2592000 ]; /** * 构造函数 * @param array $options 参数 * @access public * @throws \Exception */ public function __construct(array $options = []) { if (!empty($options)) { $this->options = array_merge($this->options, $options); } $time = time(); $token_time = RedisUtil::getInstance(RedisKeyEnum::TOKEN_TIME)->get(); if (!$token_time || $token_time < $time - 86400) { RedisUtil::getInstance(RedisKeyEnum::TOKEN_TIME)->setex($time, $this->options['expire']); Db::table($this->options['table'])->whereBetween('expiretime', [0, $time])->delete(); } } /** * 存储Token * @param string $token Token * @param int $user_id 会员ID * @param int|null $expire 过期时长,0表示无限,单位秒 * @return bool */ public function set(string $token, int $user_id, int $expire = null): bool { $expire_time = !is_null($expire) && $expire !== 0 ? time() + $expire : 0; $token = $this->getEncryptedToken($token); Db::table($this->options['table'])->where('user_id', $user_id)->delete(); Db::table($this->options['table'])->insert(['token' => $token, 'user_id' => $user_id, 'createtime' => time(), 'expiretime' => $expire_time]); return true; } /** * 获取Token内的信息 * @param string $token * @return array */ public function get(string $token): array { //方便测试 if (strpos($token, 'testuid_') !== false && config('app_debug',false)) { $uid = substr($token, 8); return [ 'user_id' => intval($uid), ]; } //方便测试 $data = Db::table($this->options['table'])->where('token', $this->getEncryptedToken($token))->first(); if ($data) { $data = json_decode(json_encode($data),true); if (!$data['expiretime'] || $data['expiretime'] > time()) { //返回未加密的token给客户端使用 $data['token'] = $token; //返回剩余有效时间 $data['expires_in'] = $this->getExpiredIn((int)$data['expiretime']); return $data; } else { $this->delete($token); } } return []; } /** * 判断Token是否可用 * @param string $token Token * @param int $user_id 会员ID * @return boolean */ public function check(string $token, int $user_id): bool { $data = $this->get($token); return $data && $data['user_id'] == $user_id; } /** * 删除Token * @param string $token * @return boolean */ public function delete(string $token): bool { Db::table($this->options['table'])->where('token', $this->getEncryptedToken($token))->delete(); return true; } /** * 删除指定用户的所有Token * @param int $user_id * @return boolean */ public function clear(int $user_id): bool { Db::table($this->options['table'])->where('user_id', $user_id)->delete(); return true; } }