Spaces:
Running
Running
from fastapi import FastAPI, Request, Response, HTTPException | |
import httpx | |
import os | |
app = FastAPI() | |
BACKEND_URL = os.environ.get("BACKEND_URL") | |
AUTH_HEADER = os.environ.get("AUTH_HEADER") | |
async def is_session_valid(session_token: str) -> bool: | |
async with httpx.AsyncClient() as client: | |
resp = await client.get( | |
f"{BACKEND_URL}/user/session", | |
params={"token": session_token}, | |
headers={"Authorization": AUTH_HEADER} | |
) | |
if resp.status_code != 200: | |
return False | |
result = resp.json() | |
return result.get("valid", False) | |
async def proxy(full_path: str, request: Request): | |
url = f"{BACKEND_URL}/{full_path}" | |
# Extrai o token de sessão do usuário do header Authorization | |
user_auth = request.headers.get("authorization") | |
session_token = None | |
if user_auth and user_auth.lower().startswith("bearer "): | |
session_token = user_auth.split(" ", 1)[1] | |
# Valida sessão, exceto para rotas públicas | |
if full_path not in ["user/login", "user/register", "user/session"]: | |
if not session_token or not await is_session_valid(session_token): | |
return Response(content="Não autorizado", status_code=401) | |
# Copia headers originais e sobrescreve Authorization com AUTH_HEADER | |
headers = dict(request.headers) | |
headers["Authorization"] = AUTH_HEADER | |
# Remove headers que podem causar conflito | |
for h in ["host", "content-length", "accept-encoding", "connection"]: | |
headers.pop(h, None) | |
body = await request.body() | |
async with httpx.AsyncClient() as client: | |
resp = await client.request( | |
method=request.method, | |
url=url, | |
headers=headers, | |
content=body if request.method != "GET" else None, | |
params=dict(request.query_params) | |
) | |
return Response( | |
content=resp.content, | |
status_code=resp.status_code, | |
headers={k: v for k, v in resp.headers.items() if k.lower() not in ["content-encoding", "transfer-encoding", "connection"]} | |
) | |
# Para rodar: | |
# uvicorn proxy:app --reload --port 8000 |