UserAuthServices.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 = 'auth:'.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. throw new Exception($e->getMessage(), 401);
  48. }
  49. $user = $this->model->where('id', $uid)->where('status', 1)->find(); // 获取用户信息
  50. if (empty($user) || $user->id != $tokenData['uid']) {
  51. $cacheServices::clearToken($md5Token);
  52. // token过期
  53. throw new Exception('登录状态有误,请重新登录', 401);
  54. }
  55. if ($user->login_count != $jwt['user']['login_count']) {
  56. throw new Exception('登录已过期', 402); // 账号在另一设备登录,使用短信登录
  57. }
  58. return $user;
  59. }
  60. }