| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- <?php
- /**
- * 用户验证
- */
- declare (strict_types=1);
- namespace app\api\services;
- use app\common\model\UserModel;
- use services\CacheServices;
- use think\Exception;
- use think\facade\Db;
- use utils\JwtAuth;
- class UserAuthServices extends BaseServices
- {
- public function __construct (UserModel $model)
- {
- $this->model = new UserModel();
- }
- /**
- * 获取授权信息
- * @param $token
- * @return array
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public function parseToken ($token)
- {
- if ($token === 'undefined' || !$token) {
- throw new Exception('请登录', 401);
- }
- /** @var JwtAuth $jwtAuth */
- $jwtAuth = app()->make(JwtAuth::class);
- // 解析token
- [$uid, $type] = $jwtAuth->parseToken($token);
- /** @var CacheServices $cacheServices */
- $cacheServices = app()->make(CacheServices::class);
- $md5Token = 'auth:'.md5('yjbuy:' . $uid);
- if (!$cacheServices::hasToken($md5Token) || !($tokenData = $cacheServices::getTokenBucket($md5Token)))
- throw new Exception('登录已过期,请重新登录', 401);
- if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) {
- throw new Exception('请登录', 401);
- }
- /**
- * 验证token
- */
- try {
- $jwt = $jwtAuth->verifyToken($token);
- } catch (\Throwable $e) {
- throw new Exception($e->getMessage(), 401);
- }
- $user = $this->model->where('id', $uid)->where('status', 1)->find(); // 获取用户信息
- if (empty($user) || $user->id != $tokenData['uid']) {
- $cacheServices::clearToken($md5Token);
- // token过期
- throw new Exception('登录状态有误,请重新登录', 401);
- }
- if ($user->login_count != $jwt['user']['login_count']) {
- throw new Exception('登录已过期', 402); // 账号在另一设备登录,使用短信登录
- }
- return $user;
- }
- }
|