"""Utility Functions for Handlers.""" from functools import wraps from typing import Any, Callable from flask import g from assets.constants import authorization from assets.exceptions import JwtInvalid, JwtMissing def validate_jwt( allowed_identities: list[str], ) -> Callable[[Any], Callable[[tuple[Any, ...], dict[str, Any]], Any]]: def wrap(function: Any) -> Callable[[tuple[Any, ...], dict[str, Any]], Any]: @wraps(function) def wrapped_f(*args: Any, **kwargs: Any) -> Any: jwt_identity_id = g.request_context.jwt_identity_id if not jwt_identity_id: raise JwtMissing() if jwt_identity_id not in allowed_identities: raise JwtInvalid() return function(*args, **kwargs) return wrapped_f return wrap def is_jwt_identity_authorized(jwt_identity_id: str | None) -> bool: """Check if the given JWT identity UUID is authorized. Args: jwt_identity_id (str | None): The identity UUID, or ``None`` if no identity is available. ``None`` is treated as unauthorized. """ return bool( jwt_identity_id and jwt_identity_id in authorization.AUTHORIZED_IDENTITIES )