// +---------------------------------------------------------------------- declare (strict_types=1); namespace app\services\user; use Psr\SimpleCache\InvalidArgumentException; use qiniu\basic\BaseServices; use app\model\user\User; use qiniu\exceptions\AuthException; use qiniu\services\CacheService; use qiniu\utils\JwtAuth; /** * * Class UserAuthServices * @package app\services\user * @mixin User */ class UserAuthServices extends BaseServices { /** * UserAuthServices constructor. * @param User $dao */ public function __construct(User $model) { $this->model = $model; } /** * 获取授权信息 * @param $token * @return array * @throws InvalidArgumentException */ public function parseToken($token): array { $md5Token = is_null($token) ? '' : md5($token); if ($token === 'undefined') { throw new AuthException('请登录', 410000); } if (!$token || !$tokenData = CacheService::getTokenBucket($md5Token)) throw new AuthException('请登录', 410000); if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) { throw new AuthException('请登录', 410000); } /** @var JwtAuth $jwtAuth */ $jwtAuth = app()->make(JwtAuth::class); //设置解析token [$id, $type, $auth] = $jwtAuth->parseToken($token); try { $jwtAuth->verifyToken(); } catch (\Throwable $e) { if (!request()->isCli()) CacheService::clearToken($md5Token); throw new AuthException('登录已过期,请重新登录', 410001); } $user = $this->getUserCacheInfo($id); if (!$user) throw new AuthException('登录失效,请重新登陆', 410001); if (!$user['status']) throw new AuthException('您已被禁止登录,请联系管理员', 410002); if ($user->uid != $tokenData['uid']) { if (!request()->isCli()) CacheService::clearToken($md5Token); throw new AuthException('登录状态有误,请重新登录', 410002); } //有密码在检测 if ($auth !== md5($user['pwd'])) { throw new AuthException('登录已过期,请重新登录', 410001); } $tokenData['type'] = $type; return compact('user', 'tokenData'); } public function getUserCacheInfo($uid, int $expire = 60) { return $this->model->cacheTag()->remember('user_info_' . $uid, function () use ($uid) { return $this->model->get($uid); }, $expire); } }