JwtAuthModelTrait.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace library\traits;
  3. // +----------------------------------------------------------------------
  4. // | [ WE CAN DO IT MORE SIMPLE ]
  5. // +----------------------------------------------------------------------
  6. // | Copyright (c) 2018-2020 rights reserved.
  7. // +----------------------------------------------------------------------
  8. // | Author: TABLE ME
  9. // +----------------------------------------------------------------------
  10. // | Date: 2020-08-29 16:03
  11. // +----------------------------------------------------------------------
  12. use Firebase\JWT\BeforeValidException;
  13. use Firebase\JWT\ExpiredException;
  14. use Firebase\JWT\JWT;
  15. use Firebase\JWT\SignatureInvalidException;
  16. use think\facade\Env;
  17. use UnexpectedValueException;
  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('+ 12hour'),
  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 UnexpectedValueException Provided JWT was invalid
  46. * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
  47. * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
  48. * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
  49. * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
  50. *
  51. */
  52. public static function parseToken(string $jwt): array
  53. {
  54. JWT::$leeway = 60;
  55. $data = JWT::decode($jwt, Env::get('app.app_key', 'default'), array('HS256'));
  56. $model = new self();
  57. return [$model->where($model->getPk(), $data->jti->id)->find(), $data->jti->type];
  58. }
  59. }