JwtAuthModelTrait.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. namespace crmeb\traits;
  12. use Firebase\JWT\JWT;
  13. use think\facade\Env;
  14. /**
  15. * Trait JwtAuthModelTrait
  16. * @package crmeb\traits
  17. */
  18. trait JwtAuthModelTrait
  19. {
  20. /**
  21. * @param string $type
  22. * @param array $params
  23. * @return array
  24. */
  25. public function getToken(string $type, array $params = []): array
  26. {
  27. $id = $this->{$this->getPk()};
  28. $host = app()->request->host();
  29. $time = time();
  30. $params += [
  31. 'iss' => $host,
  32. 'aud' => $host,
  33. 'iat' => $time,
  34. 'nbf' => $time,
  35. 'exp' => strtotime('+30 days'),
  36. ];
  37. $params['jti'] = compact('id', 'type');
  38. $token = JWT::encode($params, Env::get('app.app_key', 'default'));
  39. return compact('token', 'params');
  40. }
  41. /**
  42. * @param string $jwt
  43. * @return array
  44. *
  45. * @throws \think\db\exception\DataNotFoundException
  46. * @throws \think\db\exception\DbException
  47. * @throws \think\db\exception\ModelNotFoundException
  48. */
  49. public static function parseToken(string $jwt): array
  50. {
  51. JWT::$leeway = 60;
  52. $data = JWT::decode($jwt, Env::get('app.app_key', 'default'), array('HS256'));
  53. $model = new self();
  54. return [$model->where($model->getPk(), $data->jti->id)->find(), $data->jti->type];
  55. }
  56. }