JwtAuthModelTrait.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace crmeb\traits;
  3. use Firebase\JWT\BeforeValidException;
  4. use Firebase\JWT\ExpiredException;
  5. use Firebase\JWT\JWT;
  6. use Firebase\JWT\SignatureInvalidException;
  7. use think\facade\Config;
  8. use UnexpectedValueException;
  9. trait JwtAuthModelTrait
  10. {
  11. /**
  12. * @param string $type
  13. * @param array $params
  14. * @return array
  15. */
  16. public function getToken(string $type, array $params = []): array
  17. {
  18. $id = $this->{$this->getPk()};
  19. $host = app()->request->host();
  20. $time = time();
  21. $params += [
  22. 'iss' => $host,
  23. 'aud' => $host,
  24. 'iat' => $time,
  25. 'nbf' => $time,
  26. 'exp' => strtotime('+ 3hour'),
  27. ];
  28. $params['jti'] = compact('id', 'type');
  29. $token = JWT::encode($params, Config::get('app.app_key', 'default'));
  30. return compact('token', 'params');
  31. }
  32. /**
  33. * @param string $jwt
  34. * @return array
  35. *
  36. * @throws UnexpectedValueException Provided JWT was invalid
  37. * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
  38. * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
  39. * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
  40. * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
  41. *
  42. */
  43. public static function parseToken(string $jwt): array
  44. {
  45. JWT::$leeway = 60;
  46. $data = JWT::decode($jwt, Config::get('app.app_key', 'default'), array('HS256'));
  47. $model = new self();
  48. return [$model->where($model->getPk(), $data->jti->id)->find(), $data->jti->type];
  49. }
  50. }