UserAuthServices.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * 用户验证
  4. */
  5. declare (strict_types=1);
  6. namespace app\api\services;
  7. use app\common\model\UserModel;
  8. use services\CacheServices;
  9. use think\Exception;
  10. use think\facade\Db;
  11. use utils\JwtAuth;
  12. class UserAuthServices extends BaseServices
  13. {
  14. public function __construct (UserModel $model)
  15. {
  16. $this->model = new UserModel();
  17. }
  18. /**
  19. * 获取授权信息
  20. * @param $token
  21. * @return array
  22. * @throws \Psr\SimpleCache\InvalidArgumentException
  23. */
  24. public function parseToken ($token)
  25. {
  26. if ($token === 'undefined' || !$token) {
  27. throw new Exception('请登录', 401);
  28. }
  29. /** @var JwtAuth $jwtAuth */
  30. $jwtAuth = app()->make(JwtAuth::class);
  31. // 解析token
  32. [$uid, $type] = $jwtAuth->parseToken($token);
  33. /** @var CacheServices $cacheServices */
  34. $cacheServices = app()->make(CacheServices::class);
  35. $md5Token = md5('yjbuy:' . $uid);
  36. if (!$cacheServices::hasToken($md5Token) || !($tokenData = $cacheServices::getTokenBucket($md5Token)))
  37. throw new Exception('登录已过期,请重新登录', 401);
  38. if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) {
  39. throw new Exception('请登录', 401);
  40. }
  41. /**
  42. * 验证token
  43. */
  44. try {
  45. $jwt = $jwtAuth->verifyToken($token);
  46. } catch (\Throwable $e) {
  47. // $cacheServices::clearToken($md5Token);
  48. throw new Exception($e->getMessage(), 401);
  49. }
  50. $user = $this->model->where('id', $uid)->where('status', 1)->find(); // 获取用户信息
  51. // $user->service_ratio = getService($user->pledge_level);
  52. if (empty($user) || $user->id != $tokenData['uid']) {
  53. $cacheServices::clearToken($md5Token);
  54. // token过期
  55. throw new Exception('登录状态有误,请重新登录', 401);
  56. }
  57. if ($user->login_count != $jwt['user']['login_count']) {
  58. // $cacheServices::clearToken($md5Token);
  59. // throw new Exception('当前账号在另一设备上登陆,若非本人操作,您的登陆密码可能泄露,请及时修改密码', 402); // 账号在另一设备登录,使用短信登录
  60. throw new Exception('登录已过期', 402); // 账号在另一设备登录,使用短信登录
  61. }
  62. return $user;
  63. }
  64. }