smbaner6 commited on
Commit
152237b
·
verified ·
1 Parent(s): a48116e

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +37 -16
server.py CHANGED
@@ -1,38 +1,59 @@
1
- from fastapi import FastAPI, Request
 
2
  import os, requests
3
 
4
  app = FastAPI()
5
 
6
- OLLAMA_URL = os.getenv("OLLAMA_URL")
 
7
  CF_ID = os.getenv("CF_ACCESS_CLIENT_ID")
8
  CF_SECRET = os.getenv("CF_ACCESS_CLIENT_SECRET")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  @app.get("/")
11
  def home():
12
  return {"status": "Decidr proxy running"}
13
 
14
- @app.post("/api/generate")
15
- async def generate(req: Request):
16
- body = await req.json()
17
- r = requests.post(
18
- f"{OLLAMA_URL}/api/generate",
19
- json=body,
20
  headers={
21
  "CF-Access-Client-Id": CF_ID,
22
- "CF-Access-Client-Secret": CF_SECRET
23
  },
24
- timeout=60
25
  )
 
26
  return r.json()
27
 
28
- @app.get("/api/tags")
29
- def tags():
30
- r = requests.get(
31
- f"{OLLAMA_URL}/api/tags",
 
 
32
  headers={
33
  "CF-Access-Client-Id": CF_ID,
34
- "CF-Access-Client-Secret": CF_SECRET
35
  },
36
- timeout=30
37
  )
 
38
  return r.json()
 
1
+ from fastapi import FastAPI, Request, HTTPException, Depends
2
+ from fastapi.middleware.cors import CORSMiddleware
3
  import os, requests
4
 
5
  app = FastAPI()
6
 
7
+ # --- Config from env ---
8
+ OLLAMA_URL = os.getenv("OLLAMA_URL") # https://studio-ollama.decidrapp.com
9
  CF_ID = os.getenv("CF_ACCESS_CLIENT_ID")
10
  CF_SECRET = os.getenv("CF_ACCESS_CLIENT_SECRET")
11
+ API_KEY = os.getenv("API_KEY") # <-- NEW: server-side API key
12
+
13
+ # --- CORS (optional; safe defaults) ---
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_methods=["GET", "POST", "OPTIONS"],
18
+ allow_headers=["*"],
19
+ )
20
+
21
+ def require_api_key(request: Request):
22
+ """Simple header-based auth for this proxy."""
23
+ if not API_KEY:
24
+ # If you forgot to set it, fail CLOSED
25
+ raise HTTPException(status_code=500, detail="Server missing API_KEY")
26
+ if request.headers.get("x-api-key") != API_KEY:
27
+ raise HTTPException(status_code=401, detail="Unauthorized")
28
 
29
  @app.get("/")
30
  def home():
31
  return {"status": "Decidr proxy running"}
32
 
33
+ @app.get("/api/tags")
34
+ def tags(_: None = Depends(require_api_key)):
35
+ r = requests.get(
36
+ f"{OLLAMA_URL}/api/tags",
 
 
37
  headers={
38
  "CF-Access-Client-Id": CF_ID,
39
+ "CF-Access-Client-Secret": CF_SECRET,
40
  },
41
+ timeout=30
42
  )
43
+ r.raise_for_status()
44
  return r.json()
45
 
46
+ @app.post("/api/generate")
47
+ async def generate(req: Request, _: None = Depends(require_api_key)):
48
+ body = await req.json()
49
+ r = requests.post(
50
+ f"{OLLAMA_URL}/api/generate",
51
+ json=body,
52
  headers={
53
  "CF-Access-Client-Id": CF_ID,
54
+ "CF-Access-Client-Secret": CF_SECRET,
55
  },
56
+ timeout=60
57
  )
58
+ r.raise_for_status()
59
  return r.json()