Spaces:
Running
Running
File size: 2,268 Bytes
0ec2ef1 4c57e3f 4c1ea99 4c57e3f 0ec2ef1 b010ab7 0ec2ef1 4c57e3f f7f1079 c8ecf05 0ec2ef1 c8ecf05 4c57e3f c8ecf05 4c57e3f c8ecf05 4c57e3f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
from fastapi import FastAPI, Request, Response
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)
@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
async def proxy(full_path: str, request: Request):
url = f"{BACKEND_URL}/{full_path}"
# Recebe o token de sessão no header 'token_session'
session_token = request.headers.get("token_session")
# Rotas públicas não exigem validação
public_routes = ["user/login", "user/register", "user/session", "session/create", "session/end", "users/by_email"]
if full_path not in public_routes:
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)
# Remove o token_session do header antes de encaminhar ao backend
headers.pop("token_session", 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 |