Aman Githala commited on
Commit
72e4aba
·
1 Parent(s): ed21595

Update main.py to use API Key verification instead of JWT

Browse files
Files changed (1) hide show
  1. main.py +13 -25
main.py CHANGED
@@ -4,17 +4,16 @@ import json
4
  from typing import List, Optional
5
  from fastapi import FastAPI, HTTPException, Depends, Header, BackgroundTasks
6
  from pydantic import BaseModel
7
- from jose import jwt, JWTError
8
  from redis import Redis
9
  from rq import Queue
10
  import httpx
11
 
12
  # --- Configuration ---
13
- SUPABASE_JWT_SECRET = os.getenv("SUPABASE_JWT_SECRET", "")
14
- SUPABASE_URL = os.getenv("SUPABASE_URL", "")
15
- SUPABASE_SERVICE_ROLE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")
16
 
17
  app = FastAPI(title="Code Execution Gateway")
 
18
  redis_conn = Redis(host='localhost', port=6379)
19
  q = Queue('executions', connection=redis_conn)
20
 
@@ -24,42 +23,32 @@ class CodeExecutionRequest(BaseModel):
24
  source_code: str
25
  language: str
26
  is_submit: bool = False
 
27
 
28
  class ExecutionResponse(BaseModel):
29
  job_id: str
30
  status: str
31
 
32
- # --- Middleware: JWT Verification ---
33
- async def verify_supabase_jwt(authorization: str = Header(None)):
34
- if not authorization or not authorization.startswith("Bearer "):
35
- raise HTTPException(status_code=401, detail="Missing or invalid token")
36
-
37
- token = authorization.split(" ")[1]
38
- try:
39
- payload = jwt.decode(
40
- token,
41
- SUPABASE_JWT_SECRET,
42
- algorithms=["HS256"],
43
- options={"verify_aud": False}
44
- )
45
- return payload # Contains user_id (sub)
46
- except JWTError:
47
- raise HTTPException(status_code=401, detail="Token verification failed")
48
 
49
  # --- Core Logic ---
50
  @app.post("/execute", response_model=ExecutionResponse)
51
  async def execute_code(
52
  request: CodeExecutionRequest,
53
- user: dict = Depends(verify_supabase_jwt)
54
  ):
55
  """
56
- Validates user, pushes job to Redis queue, and returns immediately.
57
  """
58
- job_id = f"job_{int(time.time() * 1000)}_{user.get('sub')[:8]}"
59
 
60
  job_data = {
61
  "job_id": job_id,
62
- "user_id": user.get("sub"),
63
  "problem_id": request.problem_id,
64
  "source_code": request.source_code,
65
  "language": request.language,
@@ -69,7 +58,6 @@ async def execute_code(
69
 
70
  # Push to Redis Queue
71
  q.enqueue("worker.process_job", job_data, job_id=job_id)
72
-
73
  return {"job_id": job_id, "status": "queued"}
74
 
75
  @app.get("/health")
 
4
  from typing import List, Optional
5
  from fastapi import FastAPI, HTTPException, Depends, Header, BackgroundTasks
6
  from pydantic import BaseModel
 
7
  from redis import Redis
8
  from rq import Queue
9
  import httpx
10
 
11
  # --- Configuration ---
12
+ # This key MUST match exactly what Next.js sends
13
+ EXECUTION_API_KEY = os.getenv("EXECUTION_API_KEY", "super_secret_piston_key_2026")
 
14
 
15
  app = FastAPI(title="Code Execution Gateway")
16
+
17
  redis_conn = Redis(host='localhost', port=6379)
18
  q = Queue('executions', connection=redis_conn)
19
 
 
23
  source_code: str
24
  language: str
25
  is_submit: bool = False
26
+ user_id: str
27
 
28
  class ExecutionResponse(BaseModel):
29
  job_id: str
30
  status: str
31
 
32
+ # --- Middleware: API Key Verification ---
33
+ async def verify_api_key(x_api_key: str = Header(None)):
34
+ if not x_api_key or x_api_key != EXECUTION_API_KEY:
35
+ raise HTTPException(status_code=401, detail="Invalid API Key")
36
+ return True
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  # --- Core Logic ---
39
  @app.post("/execute", response_model=ExecutionResponse)
40
  async def execute_code(
41
  request: CodeExecutionRequest,
42
+ authorized: bool = Depends(verify_api_key)
43
  ):
44
  """
45
+ Validates API key, pushes job to Redis queue, and returns immediately.
46
  """
47
+ job_id = f"job_{int(time.time() * 1000)}_{request.user_id[:8]}"
48
 
49
  job_data = {
50
  "job_id": job_id,
51
+ "user_id": request.user_id,
52
  "problem_id": request.problem_id,
53
  "source_code": request.source_code,
54
  "language": request.language,
 
58
 
59
  # Push to Redis Queue
60
  q.enqueue("worker.process_job", job_data, job_id=job_id)
 
61
  return {"job_id": job_id, "status": "queued"}
62
 
63
  @app.get("/health")