"""Middleware for authentication and security headers.""" from fastapi import Request, Response from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.cors import CORSMiddleware from fastapi import FastAPI import os def add_security_headers(app: FastAPI): """Add security headers to all responses.""" class SecurityHeadersMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): response: Response = await call_next(request) # Security headers response.headers["X-Content-Type-Options"] = "nosniff" response.headers["X-XSS-Protection"] = "1; mode=block" response.headers["Content-Security-Policy"] = "frame-ancestors *" # CORS headers response.headers["Access-Control-Allow-Origin"] = os.getenv( "APP_CORS_ORIGINS", "http://localhost:3000" ) response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS" response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type" return response app.add_middleware(SecurityHeadersMiddleware) def add_cors_middleware(app: FastAPI): """Add CORS middleware.""" cors_origins = os.getenv("APP_CORS_ORIGINS", "http://localhost:3000").split(",") app.add_middleware( CORSMiddleware, allow_origins=cors_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )