Files
template-fastapi/{{project_slug}}/dependencies/auth_dep.py
Aleksei Sokol 34c1347402
All checks were successful
Run linters on applied template / Python 3.13 lint and build (push) Successful in 54s
Version 0.2.0
Changes:
- add metrics dispencer
- add basic authentication dependency
- enable GZIP middleware
- add !env() example to deploy section
- update dependencies state attribute name
2025-11-30 16:59:25 +03:00

35 lines
1.1 KiB
Python

"""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