Skip to content

Commit

Permalink
add cors.
Browse files Browse the repository at this point in the history
  • Loading branch information
tharlestsa committed Oct 2, 2024
1 parent 20de37d commit 017ba6f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
16 changes: 16 additions & 0 deletions app/utils/cors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

from os import getenv

# Obtém o caminho do diretório dos arquivos estáticos via variável de ambiente
origin_regex = r"^https:\/\/(?:\w+\.)?lapig\.iesa\.ufg\.br$|^https:\/\/lapig-ufg\.github\.io$"

# Função para obter as origens separadas por vírgula da variável de ambiente
def get_origins_from_env():
origins = getenv('ALLOW_ORIGINS', '')
if not origins:
return [] # Retorna lista vazia se a variável de ambiente não estiver definida ou estiver vazia
return [origin.strip() for origin in origins.split(',') if origin]


# Obtém as origens permitidas da variável de ambiente
allow_origins = get_origins_from_env()
14 changes: 13 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import RedirectResponse
from unidecode import unidecode
from fastapi.middleware.cors import CORSMiddleware

from app.config import logger, settings, start_logger
from app.router import created_routes
from app.utils.cors import allow_origins, origin_regex

import os

@asynccontextmanager
async def lifespan(app: FastAPI):
Expand All @@ -32,6 +33,17 @@ def gee_credentials(private_key_file):

app = FastAPI(lifespan=lifespan)

# Configurações CORS com expressões regulares para subdomínios dinâmicos
app.add_middleware(
CORSMiddleware,
allow_origins=allow_origins, # Lista de origens estáticas (deixe vazio se estiver usando regex)
allow_methods=["*"], # Métodos permitidos
allow_headers=["*"], # Cabeçalhos permitidos
allow_credentials=True, # Permite o envio de cookies/credenciais
allow_origin_regex=origin_regex,
expose_headers=["X-Response-Time"], # Cabeçalhos expostos
max_age=3600, # Tempo máximo para cache da resposta preflight
)

@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
Expand Down

0 comments on commit 017ba6f

Please sign in to comment.