ValidAt.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Lcobucci\JWT\Validation\Constraint;
  3. use DateInterval;
  4. use DateTimeInterface;
  5. use Lcobucci\Clock\Clock;
  6. use Lcobucci\JWT\Token;
  7. use Lcobucci\JWT\Validation\Constraint;
  8. use Lcobucci\JWT\Validation\ConstraintViolation;
  9. final class ValidAt implements Constraint
  10. {
  11. /** @var Clock */
  12. private $clock;
  13. /** @var DateInterval */
  14. private $leeway;
  15. public function __construct(Clock $clock, DateInterval $leeway = null)
  16. {
  17. $this->clock = $clock;
  18. $this->leeway = $this->guardLeeway($leeway);
  19. }
  20. /** @return DateInterval */
  21. private function guardLeeway(DateInterval $leeway = null)
  22. {
  23. if ($leeway === null) {
  24. return new DateInterval('PT0S');
  25. }
  26. if ($leeway->invert === 1) {
  27. throw LeewayCannotBeNegative::create();
  28. }
  29. return $leeway;
  30. }
  31. public function assert(Token $token)
  32. {
  33. $now = $this->clock->now();
  34. $this->assertIssueTime($token, $now->add($this->leeway));
  35. $this->assertMinimumTime($token, $now->add($this->leeway));
  36. $this->assertExpiration($token, $now->sub($this->leeway));
  37. }
  38. /** @throws ConstraintViolation */
  39. private function assertExpiration(Token $token, DateTimeInterface $now)
  40. {
  41. if ($token->isExpired($now)) {
  42. throw new ConstraintViolation('The token is expired');
  43. }
  44. }
  45. /** @throws ConstraintViolation */
  46. private function assertMinimumTime(Token $token, DateTimeInterface $now)
  47. {
  48. if (! $token->isMinimumTimeBefore($now)) {
  49. throw new ConstraintViolation('The token cannot be used yet');
  50. }
  51. }
  52. /** @throws ConstraintViolation */
  53. private function assertIssueTime(Token $token, DateTimeInterface $now)
  54. {
  55. if (! $token->hasBeenIssuedBefore($now)) {
  56. throw new ConstraintViolation('The token was issued in the future');
  57. }
  58. }
  59. }