"""Authentication dependency function is defined here.""" from dataclasses import dataclass import jwt from fastapi import Request from . import logger_dep @dataclass class AuthenticationData: api_key: str | None jwt_payload: dict | None jwt_original: str | None def obtain(request: Request) -> AuthenticationData: if hasattr(request.state, "auth_dep"): return request.state.auth_dep auth = AuthenticationData(None, None, None) if (value := request.headers.get("X-API-Key")) is not None: auth.api_key = value if (value := request.headers.get("Authorization")) is not None and value.startswith("Bearer "): value = value[7:] auth.jwt_original = value try: auth.jwt_payload = jwt.decode(value, algorithms=["HS256"], options={"verify_signature": False}) except Exception: # pylint: disable=broad-except logger = logger_dep.obtain(request) logger.warning("failed to parse Authorization header as jwt", value=value) logger.debug("failed to parse Authorization header as jwt", exc_info=True) request.state.auth_dep = auth return auth