31 lines
881 B
Python
31 lines
881 B
Python
# -*- coding: utf-8 -*-
|
|
"""Shared CORS configuration for all microservice apps."""
|
|
|
|
import os
|
|
from typing import Sequence
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
def get_cors_origins() -> Sequence[str]:
|
|
"""Get allowed CORS origins from environment variable.
|
|
|
|
Defaults to ["*"] for backward compatibility.
|
|
Set CORS_ALLOWED_ORIGINS env var (comma-separated) in production.
|
|
"""
|
|
origins = os.getenv("CORS_ALLOWED_ORIGINS", "").strip()
|
|
if not origins:
|
|
return ["*"]
|
|
return [o.strip() for o in origins.split(",") if o.strip()]
|
|
|
|
|
|
def add_cors_middleware(app: "FastAPI") -> None:
|
|
"""Add CORS middleware to app with environment-configured origins."""
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=get_cors_origins(),
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|