12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- <?php
- // +----------------------------------------------------------------------
- // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
- // +----------------------------------------------------------------------
- // | Author: CRMEB Team <admin@crmeb.com>
- // +----------------------------------------------------------------------
- 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);
- }
- }
|