UserAuthServices.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\ApiErrorCode;
  18. use crmeb\utils\JwtAuth;
  19. /**
  20. *
  21. * Class UserAuthServices
  22. * @package app\services\user
  23. */
  24. class UserAuthServices extends BaseServices
  25. {
  26. /**
  27. * UserAuthServices constructor.
  28. * @param UserAuthDao $dao
  29. */
  30. public function __construct(UserAuthDao $dao)
  31. {
  32. $this->dao = $dao;
  33. }
  34. /**
  35. * 获取授权信息
  36. * @param $token
  37. * @return array
  38. * @throws \Psr\SimpleCache\InvalidArgumentException\
  39. */
  40. public function parseToken($token): array
  41. {
  42. $md5Token = is_null($token) ? '' : md5($token);
  43. if ($token === 'undefined') {
  44. throw new AuthException('请登录', 410000);
  45. }
  46. if (!$token || !$tokenData = CacheService::getTokenBucket($md5Token))
  47. throw new AuthException('请登录', 410000);
  48. if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) {
  49. throw new AuthException('请登录', 410000);
  50. }
  51. /** @var JwtAuth $jwtAuth */
  52. $jwtAuth = app()->make(JwtAuth::class);
  53. //设置解析token
  54. [$id, $type] = $jwtAuth->parseToken($token);
  55. try {
  56. $jwtAuth->verifyToken();
  57. } catch (\Throwable $e) {
  58. if (!request()->isCli()) CacheService::clearToken($md5Token);
  59. throw new AuthException('登录已过期,请重新登录', 410001);
  60. }
  61. $user = $this->dao->get($id);
  62. if (!$user || $user->uid != $tokenData['uid']) {
  63. if (!request()->isCli()) CacheService::clearToken($md5Token);
  64. throw new AuthException('登录状态有误,请重新登录', 410002);
  65. }
  66. $tokenData['type'] = $type;
  67. return compact('user', 'tokenData');
  68. }
  69. }