import logging from functools import lru_cache import jwt from ...enums import JwtAlgorithm from ...utils.custom_types import FrozenDict logger = logging.getLogger(__name__) @lru_cache(maxsize=128) def validate_jwt_token( token: str, secret: str, algorithm: JwtAlgorithm | str = JwtAlgorithm.HS256 ) -> FrozenDict | None: """Validate a JWT token using the provided secret. Uses an LRU cache to optimize performance for repeated calls. Args: token (str): The JWT token to validate. secret (str): The secret key used to decode the token. algorithm (str): The algorithm used to sign the token, default is "HS256", which is the one used by Monday.com. Returns: A read-only dictionary of the token's payload if valid, or None if the token is invalid. """ try: payload = jwt.decode(token, secret, algorithms=[algorithm]) # Return read-only dict, to prevent cached result mutation by callers return FrozenDict(payload) except jwt.PyJWTError as ex: logger.warning("JWT validation failed. Reason: %s", ex.args[0]) return None