@devries-cameron20 / OCIU-npo Mirror · read-only
Fork 0

Mirrored from https://github.com/Camo67/OCIU-npo.git

Synced Nov 21, 06:00 UTC

1 import os
2 from fastapi import FastAPI, Request, HTTPException, Depends
3 from fastapi.middleware.cors import CORSMiddleware
4 import httpx
5 import time
6 from typing import Dict
7
8 app = FastAPI(title="CamoFlow Edge Proxy")
9
10 app.add_middleware(
11 CORSMiddleware,
12 allow_origins=["*"],
13 allow_methods=["*"],
14 allow_headers=["*"],
15 )
16
17 CORE_SERVER_URL = os.getenv("CORE_SERVER_URL", "http://localhost:8000")
18 EDGE_CACHE: Dict[str, dict] = {}
19 CACHE_TTL = 300 # 5 minutes default
20
21 async def verify_token(request: Request):
22 auth_header = request.headers.get("Authorization")
23 if not auth_header:
24 raise HTTPException(status_code=401, detail="Missing auth token")
25 # In a real setup, verify JWT with Supabase/Firebase here
26 return True
27
28 @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
29 async def proxy(path: str, request: Request, authenticated: bool = Depends(verify_token)):
30 method = request.method
31 url = f"{CORE_SERVER_URL}/{path}"
32
33 # Check cache for GET requests
34 if method == "GET":
35 if path in EDGE_CACHE:
36 entry = EDGE_CACHE[path]
37 if time.time() - entry["timestamp"] < CACHE_TTL:
38 return entry["data"]
39
40 async with httpx.AsyncClient(timeout=30.0) as client:
41 try:
42 body = await request.body()
43 resp = await client.request(
44 method,
45 url,
46 content=body,
47 headers=dict(request.headers),
48 params=dict(request.query_params)
49 )
50
51 data = resp.json()
52
53 if method == "GET" and resp.status_code == 200:
54 EDGE_CACHE[path] = {"data": data, "timestamp": time.time()}
55
56 return data
57 except Exception as e:
58 raise HTTPException(status_code=500, detail=str(e))
59
60 if __name__ == "__main__":
61 import uvicorn
62 uvicorn.run(app, host="0.0.0.0", port=8001)