TokenProviderAble.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of qbhy/simple-jwt.
  5. *
  6. * @link https://github.com/qbhy/simple-jwt
  7. * @document https://github.com/qbhy/simple-jwt/blob/master/README.md
  8. * @contact qbhy0715@qq.com
  9. * @license https://github.com/qbhy/simple-jwt/blob/master/LICENSE
  10. */
  11. namespace Qbhy\SimpleJwt\Laravel;
  12. use Illuminate\Database\Eloquent\Model;
  13. use Qbhy\SimpleJwt\Exceptions\TokenProviderException;
  14. use Qbhy\SimpleJwt\JWT;
  15. use Qbhy\SimpleJwt\JWTManager;
  16. /**
  17. * Trait TokenProviderAble.
  18. *
  19. * @mixin \Qbhy\SimpleJwt\Interfaces\TokenProviderInterface
  20. * @mixin \Illuminate\Database\Eloquent\Model
  21. */
  22. trait TokenProviderAble
  23. {
  24. /**
  25. * @throws TokenProviderException
  26. * @throws \Qbhy\SimpleJwt\Exceptions\InvalidTokenException
  27. * @throws \Qbhy\SimpleJwt\Exceptions\SignatureException
  28. * @throws \Qbhy\SimpleJwt\Exceptions\TokenExpiredException
  29. * @return Model|TokenProviderAble
  30. */
  31. public static function fromToken(string $token)
  32. {
  33. /** @var JWT $jwt */
  34. $jwt = static::jwtManager()->parse($token);
  35. static::checkJwt($jwt);
  36. return static::fromPayload($jwt->getPayload());
  37. }
  38. /**
  39. * @return string
  40. */
  41. public function getToken()
  42. {
  43. $jwtManager = static::jwtManager();
  44. return $jwtManager->make($this->buildPayload(), static::matchHeaders())->token();
  45. }
  46. /**
  47. * @return \Illuminate\Database\Eloquent\Model|static
  48. */
  49. abstract public static function fromPayload(array $payload);
  50. /**
  51. * @throws TokenProviderException
  52. */
  53. protected static function checkJwt(JWT $jwt)
  54. {
  55. $headers = $jwt->getHeaders();
  56. foreach (static::matchHeaders() as $key => $header) {
  57. if (! isset($headers[$key]) || $headers[$key] !== $header) {
  58. throw new TokenProviderException('header invalid');
  59. }
  60. }
  61. $payload = $jwt->getPayload();
  62. $needPayloadsCount = count($needPayloads = static::needPayloads());
  63. $intersectCount = count(array_intersect($needPayloads, array_keys($payload)));
  64. if ($needPayloadsCount !== $intersectCount) {
  65. throw new TokenProviderException('payload invalid');
  66. }
  67. }
  68. /**
  69. * @return JWTManager
  70. */
  71. protected static function jwtManager()
  72. {
  73. return app(JWTManager::class);
  74. }
  75. abstract protected static function matchHeaders();
  76. abstract protected static function needPayloads();
  77. }