UserAuthServices.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 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 \think\db\exception\DataNotFoundException
  38. * @throws \think\db\exception\DbException
  39. * @throws \think\db\exception\ModelNotFoundException
  40. */
  41. public function parseToken($token): array
  42. {
  43. $md5Token = is_null($token) ? '' : md5($token);
  44. if ($token === 'undefined') {
  45. throw new AuthException(110002);
  46. }
  47. if (!$token || !$tokenData = CacheService::get($md5Token))
  48. throw new AuthException(110002);
  49. if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) {
  50. throw new AuthException(110002);
  51. }
  52. /** @var JwtAuth $jwtAuth */
  53. $jwtAuth = app()->make(JwtAuth::class);
  54. //设置解析token
  55. [$id, $type] = $jwtAuth->parseToken($token);
  56. try {
  57. $jwtAuth->verifyToken();
  58. } catch (\Throwable $e) {
  59. if (!request()->isCli()) CacheService::delete($md5Token);
  60. throw new AuthException(110003);
  61. }
  62. $user = $this->dao->get(['uid' => $id, 'is_del' => 0, 'status' => 1]);
  63. if (!$user || $user->uid != $tokenData['uid']) {
  64. if (!request()->isCli()) CacheService::delete($md5Token);
  65. throw new AuthException(110004);
  66. }
  67. $tokenData['type'] = $type;
  68. return compact('user', 'tokenData');
  69. }
  70. }