Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -28,7 +28,7 @@ CLOUD_KEY = os.getenv("CLOUD_KEY")
|
|
| 28 |
|
| 29 |
supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY)
|
| 30 |
|
| 31 |
-
# Security: Support both X-API-Key and Bearer Token
|
| 32 |
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
| 33 |
bearer_scheme = HTTPBearer(auto_error=False)
|
| 34 |
|
|
@@ -36,19 +36,35 @@ async def verify_token(
|
|
| 36 |
api_key: str = Depends(api_key_header),
|
| 37 |
bearer: HTTPAuthorizationCredentials = Depends(bearer_scheme)
|
| 38 |
):
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
if not token:
|
| 43 |
-
|
|
|
|
| 44 |
|
| 45 |
try:
|
|
|
|
| 46 |
result = supabase.table("api_tokens").select("user_id").eq("api", token).execute()
|
| 47 |
-
|
|
|
|
|
|
|
| 48 |
raise HTTPException(status_code=403, detail="Invalid API Token.")
|
|
|
|
| 49 |
return result.data[0]
|
|
|
|
|
|
|
| 50 |
except Exception as e:
|
| 51 |
-
print(f"Database error: {e}")
|
| 52 |
raise HTTPException(status_code=500, detail="Internal Server Error during authentication.")
|
| 53 |
|
| 54 |
app.add_middleware(
|
|
@@ -117,14 +133,14 @@ async def chat(request: ChatRequest, token_data: dict = Depends(verify_token)):
|
|
| 117 |
finally:
|
| 118 |
driver.quit()
|
| 119 |
|
| 120 |
-
# --- Cursor Compatibility Endpoint ---
|
| 121 |
@app.post("/v1/chat/completions")
|
| 122 |
async def cursor_handler(request: Request, token_data: dict = Depends(verify_token)):
|
| 123 |
try:
|
| 124 |
body = await request.json()
|
| 125 |
messages = body.get("messages", [])
|
| 126 |
|
| 127 |
-
#
|
| 128 |
last_user_message = ""
|
| 129 |
for m in reversed(messages):
|
| 130 |
if m.get("role") == "user":
|
|
@@ -134,13 +150,13 @@ async def cursor_handler(request: Request, token_data: dict = Depends(verify_tok
|
|
| 134 |
if not last_user_message:
|
| 135 |
return {"error": "No user message found"}
|
| 136 |
|
| 137 |
-
#
|
| 138 |
chat_req = ChatRequest(message=last_user_message)
|
| 139 |
response = await chat(chat_req, token_data)
|
| 140 |
|
| 141 |
-
content = response.get("content") or response.get("raw") or "No response."
|
| 142 |
|
| 143 |
-
#
|
| 144 |
return {
|
| 145 |
"id": f"chatcmpl-{int(time.time())}",
|
| 146 |
"object": "chat.completion",
|
|
@@ -154,7 +170,7 @@ async def cursor_handler(request: Request, token_data: dict = Depends(verify_tok
|
|
| 154 |
},
|
| 155 |
"finish_reason": "stop"
|
| 156 |
}],
|
| 157 |
-
"usage": response.get("usage", {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
|
| 158 |
}
|
| 159 |
except Exception as e:
|
| 160 |
print(f"Bridge Error: {str(e)}")
|
|
|
|
| 28 |
|
| 29 |
supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY)
|
| 30 |
|
| 31 |
+
# Security: Support both X-API-Key and Bearer Token
|
| 32 |
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
| 33 |
bearer_scheme = HTTPBearer(auto_error=False)
|
| 34 |
|
|
|
|
| 36 |
api_key: str = Depends(api_key_header),
|
| 37 |
bearer: HTTPAuthorizationCredentials = Depends(bearer_scheme)
|
| 38 |
):
|
| 39 |
+
"""
|
| 40 |
+
Unified authentication: checks X-API-Key or Authorization: Bearer
|
| 41 |
+
"""
|
| 42 |
+
token = None
|
| 43 |
|
| 44 |
+
# 1. Check for X-API-Key (Standard Web/Postman)
|
| 45 |
+
if api_key:
|
| 46 |
+
token = api_key
|
| 47 |
+
# 2. Check for Bearer Token (Cursor / Continue / OpenAI standard)
|
| 48 |
+
elif bearer:
|
| 49 |
+
token = bearer.credentials
|
| 50 |
+
|
| 51 |
if not token:
|
| 52 |
+
print("Auth Error: No token provided in headers")
|
| 53 |
+
raise HTTPException(status_code=401, detail="API Key missing. Use X-API-Key or Bearer token.")
|
| 54 |
|
| 55 |
try:
|
| 56 |
+
# Query Supabase for the token
|
| 57 |
result = supabase.table("api_tokens").select("user_id").eq("api", token).execute()
|
| 58 |
+
|
| 59 |
+
if not result.data or len(result.data) == 0:
|
| 60 |
+
print(f"Auth Error: Token {token[:5]}*** not found in database")
|
| 61 |
raise HTTPException(status_code=403, detail="Invalid API Token.")
|
| 62 |
+
|
| 63 |
return result.data[0]
|
| 64 |
+
except HTTPException:
|
| 65 |
+
raise
|
| 66 |
except Exception as e:
|
| 67 |
+
print(f"Database error during auth: {e}")
|
| 68 |
raise HTTPException(status_code=500, detail="Internal Server Error during authentication.")
|
| 69 |
|
| 70 |
app.add_middleware(
|
|
|
|
| 133 |
finally:
|
| 134 |
driver.quit()
|
| 135 |
|
| 136 |
+
# --- Cursor / Continue Compatibility Endpoint ---
|
| 137 |
@app.post("/v1/chat/completions")
|
| 138 |
async def cursor_handler(request: Request, token_data: dict = Depends(verify_token)):
|
| 139 |
try:
|
| 140 |
body = await request.json()
|
| 141 |
messages = body.get("messages", [])
|
| 142 |
|
| 143 |
+
# Extract the last message from the conversation history
|
| 144 |
last_user_message = ""
|
| 145 |
for m in reversed(messages):
|
| 146 |
if m.get("role") == "user":
|
|
|
|
| 150 |
if not last_user_message:
|
| 151 |
return {"error": "No user message found"}
|
| 152 |
|
| 153 |
+
# Call the existing scraper logic
|
| 154 |
chat_req = ChatRequest(message=last_user_message)
|
| 155 |
response = await chat(chat_req, token_data)
|
| 156 |
|
| 157 |
+
content = response.get("content") or response.get("raw") or "No response from scraper."
|
| 158 |
|
| 159 |
+
# Return standard OpenAI JSON structure
|
| 160 |
return {
|
| 161 |
"id": f"chatcmpl-{int(time.time())}",
|
| 162 |
"object": "chat.completion",
|
|
|
|
| 170 |
},
|
| 171 |
"finish_reason": "stop"
|
| 172 |
}],
|
| 173 |
+
"usage": response.get("usage") if isinstance(response.get("usage"), dict) else {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
|
| 174 |
}
|
| 175 |
except Exception as e:
|
| 176 |
print(f"Bridge Error: {str(e)}")
|