jwk_set_cache.py 959 B

12345678910111213141516171819202122232425262728293031
  1. import time
  2. from typing import Optional
  3. from .api_jwk import PyJWKSet, PyJWTSetWithTimestamp
  4. class JWKSetCache:
  5. def __init__(self, lifespan: int) -> None:
  6. self.jwk_set_with_timestamp: Optional[PyJWTSetWithTimestamp] = None
  7. self.lifespan = lifespan
  8. def put(self, jwk_set: PyJWKSet) -> None:
  9. if jwk_set is not None:
  10. self.jwk_set_with_timestamp = PyJWTSetWithTimestamp(jwk_set)
  11. else:
  12. # clear cache
  13. self.jwk_set_with_timestamp = None
  14. def get(self) -> Optional[PyJWKSet]:
  15. if self.jwk_set_with_timestamp is None or self.is_expired():
  16. return None
  17. return self.jwk_set_with_timestamp.get_jwk_set()
  18. def is_expired(self) -> bool:
  19. return (
  20. self.jwk_set_with_timestamp is not None
  21. and self.lifespan > -1
  22. and time.monotonic()
  23. > self.jwk_set_with_timestamp.get_timestamp() + self.lifespan
  24. )