JwtAuthModelTrait.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. namespace crmeb\traits;
  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('+ 3hour'),
  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. }