UserAuthServices.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\services\user;
  13. use app\services\BaseServices;
  14. use app\dao\user\UserAuthDao;
  15. use crmeb\exceptions\AuthException;
  16. use crmeb\services\CacheService;
  17. use crmeb\utils\JwtAuth;
  18. /**
  19. *
  20. * Class UserAuthServices
  21. * @package app\services\user
  22. */
  23. class UserAuthServices extends BaseServices
  24. {
  25. /**
  26. * UserAuthServices constructor.
  27. * @param UserAuthDao $dao
  28. */
  29. public function __construct(UserAuthDao $dao)
  30. {
  31. $this->dao = $dao;
  32. }
  33. /**
  34. * 获取授权信息
  35. * @param $token
  36. * @return array
  37. * @throws \Psr\SimpleCache\InvalidArgumentException\
  38. */
  39. public function parseToken($token): array
  40. {
  41. $md5Token = is_null($token) ? '' : md5($token);
  42. if ($token === 'undefined') {
  43. throw new AuthException('请登录', 410000);
  44. }
  45. if (!$token || !$tokenData = CacheService::getTokenBucket($md5Token))
  46. throw new AuthException('请登录', 410000);
  47. if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) {
  48. throw new AuthException('请登录', 410000);
  49. }
  50. /** @var JwtAuth $jwtAuth */
  51. $jwtAuth = app()->make(JwtAuth::class);
  52. //设置解析token
  53. [$id, $type] = $jwtAuth->parseToken($token);
  54. try {
  55. $jwtAuth->verifyToken();
  56. } catch (\Throwable $e) {
  57. if (!request()->isCli()) CacheService::clearToken($md5Token);
  58. throw new AuthException('登录已过期,请重新登录', 410001);
  59. }
  60. $user = $this->dao->get(['uid' => $id, 'is_del' => 0]);
  61. if (!$user || $user->uid != $tokenData['uid']) {
  62. if (!request()->isCli()) CacheService::clearToken($md5Token);
  63. throw new AuthException('登录状态有误,请重新登录', 410002);
  64. }
  65. $tokenData['type'] = $type;
  66. return compact('user', 'tokenData');
  67. }
  68. }