import logging from fastapi import Request, Response from starlette.responses import JSONResponse from app.core.constants import ( REQUEST_ID_HEADER, SECURITY_HEADERS, UNAUTHORIZED_HEADERS ) from app.core.context import request_id_ctx import os logger = logging.getLogger(__name__) async def auth_middleware(request: Request, call_next) -> Response: if request.url.path in ["/", "/openapi.json"]: return await call_next(request) request_id = request_id_ctx.get('not-set') auth_header = request.headers.get("Authorization") if not auth_header or not auth_header.startswith("Bearer "): return JSONResponse( status_code=401, content={"detail": "Unauthorized", "request_id": request_id}, headers= { REQUEST_ID_HEADER: request_id, **SECURITY_HEADERS, **UNAUTHORIZED_HEADERS } ) token = auth_header.split(" ")[1] if token != os.getenv("SERVER_AUTH"): return JSONResponse( status_code=401, content={"detail": "Unauthorized", "request_id": request_id}, headers= { REQUEST_ID_HEADER: request_id, **SECURITY_HEADERS, **UNAUTHORIZED_HEADERS } ) return await call_next(request)