|
4 | 4 | import datetime |
5 | 5 | import calendar |
6 | 6 | from json import JSONEncoder |
7 | | -from typing import TypedDict, Type, Any |
| 7 | +from typing import TypedDict, Type, Any, Callable |
8 | 8 | from ..util import to_bytes |
9 | 9 | from ..errors import ( |
10 | 10 | MissingClaimError, |
@@ -83,13 +83,26 @@ def validate(self, claims: dict[str, Any]) -> None: |
83 | 83 |
|
84 | 84 |
|
85 | 85 | class JWTClaimsRegistry(ClaimsRegistry): |
86 | | - def __init__(self, now: int | None = None, leeway: int = 0, **kwargs: ClaimsOption): |
| 86 | + """A claims registry for validating JWT claims. |
| 87 | +
|
| 88 | + :param now: timestamp of "now" time |
| 89 | + :param leeway: leeway time in seconds |
| 90 | + :param **kwargs: claims options |
| 91 | + """ |
| 92 | + |
| 93 | + def __init__(self, now: int | Callable[[], int] | None = None, leeway: int = 0, **kwargs: ClaimsOption) -> None: |
87 | 94 | if now is None: |
88 | | - now = int(time.time()) |
89 | | - self.now = now |
| 95 | + now = _generate_now |
| 96 | + self._now = now |
90 | 97 | self.leeway = leeway |
91 | 98 | super().__init__(**kwargs) |
92 | 99 |
|
| 100 | + @property |
| 101 | + def now(self) -> int: |
| 102 | + if callable(self._now): |
| 103 | + return self._now() |
| 104 | + return self._now |
| 105 | + |
93 | 106 | def validate_exp(self, value: int) -> None: |
94 | 107 | """The "exp" (expiration time) claim identifies the expiration time on |
95 | 108 | or after which the JWT MUST NOT be accepted for processing. The |
@@ -135,3 +148,7 @@ def validate_iat(self, value: int) -> None: |
135 | 148 |
|
136 | 149 | def _validate_numeric_time(s: int) -> bool: |
137 | 150 | return isinstance(s, (int, float)) |
| 151 | + |
| 152 | + |
| 153 | +def _generate_now() -> int: |
| 154 | + return int(time.time()) |
0 commit comments