Spaces:
Running
Running
Update backend/app.py
Browse files123456784 unmodified lines1314151617181920212223242526272829303132333435363738394041424 unmodified lines4748495051525354555657585960616263646566676869from fastapi import FastAPI, HTTPException, Dependsfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentialsimport osfrom dotenv import load_dotenv4 unmodified linesapp = FastAPI(title="Gemini Multimodal API")# Setup securitysecurity = HTTPBearer(auto_error=False)# Get API key from environment variableAPI_KEY = os.environ.get("API_KEY", None)def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):"""Verify API key from Authorization header"""if not API_KEY:return True # No key set, allow allif not credentials:raise HTTPException(status_code=401, detail="API key required")if credentials.credentials != API_KEY:raise HTTPException(status_code=403, detail="Invalid API key")return Trueasync def verify_websocket_api_key(websocket, api_key: str = None):"""Verify API key for WebSocket connections (from query param)"""if not API_KEY:return Trueif not api_key or api_key != API_KEY:await websocket.close(code=1008, reason="Invalid or missing API key")return Falsereturn True# Add CORS middlewareapp.add_middleware(4 unmodified linesallow_headers=["*"],)# Public routes (no API key required)app.mount("/static", StaticFiles(directory="../frontend"), name="static")@app.get("/")def serve_index():return FileResponse("../frontend/index.html")# Protected WebSocket route@app.websocket("/ws/{client_id}")async def protected_websocket_endpoint(websocket, client_id: str, api_key: str = None):"""WebSocket endpoint with API key validation"""if not await verify_websocket_api_key(websocket, api_key):returnfrom routes.websocket import websocket_endpointawait websocket_endpoint(websocket, client_id)# Include other routersapp.include_router(websocket_router)if __name__ == "__main__":12345674 unmodified lines12131415161718194 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990from fastapi import FastAPI, HTTPException, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, HTMLResponsefrom fastapi.staticfiles import StaticFilesimport osfrom dotenv import load_dotenv4 unmodified linesapp = FastAPI(title="Gemini Multimodal API")# --- 1. Get your secret API key ---APP_API_KEY = os.environ.get("API_KEY", None)# Add CORS middlewareapp.add_middleware(4 unmodified linesallow_headers=["*"],)# --- 2. A simple, password-protected landing page ---@app.get("/", response_class=HTMLResponse)async def landing_page(request: Request):# If no API key is set in the environment, allow everyone.if not APP_API_KEY:return FileResponse("../frontend/index.html")# Get the key from the URL's query parametersapi_key = request.query_params.get("api_key")# Check if the provided key is validif api_key and api_key == APP_API_KEY:# Key is valid! Serve the real application.return FileResponse("../frontend/index.html")else:# Key is missing or invalid. Show a simple login page.return """<!DOCTYPE html><html><head><title>Access Required</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>body { font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f0f0f0; }.card { background: white; padding: 2rem; border-radius: 1rem; box-shadow: 0 4px 6px rgba(0,0,0,0.1); text-align: center; }input, button { padding: 0.5rem; margin: 0.5rem; font-size: 1rem; }.error { color: red; }</style></head><body><div class="card"><h2>🔐 Access to Voice Assistant</h2><p>This application is protected. Please enter the access key.</p><input type="password" id="apiKeyInput" placeholder="Enter API Key" autofocus><button onclick="login()">Submit</button><div id="errorMsg" class="error"></div></div><script>function login() {const key = document.getElementById('apiKeyInput').value;if (key) {// Redirect to the same page with the key in the URLwindow.location.href = window.location.pathname + '?api_key=' + encodeURIComponent(key);} else {document.getElementById('errorMsg').innerText = 'Please enter a key.';}}// Allow pressing "Enter" key to submitdocument.getElementById('apiKeyInput').addEventListener('keypress', function(e) {if (e.key === 'Enter') login();});</script></body></html>"""# --- 3. Mount static files (these are now "inside" the protected zone) ---# Users must have a valid key to load CSS, JS, etc., because these routes are checked by the middleware.app.mount("/static", StaticFiles(directory="../frontend"), name="static")# --- 4. Your existing WebSocket route (already protected by your previous logic) ---app.include_router(websocket_router)if __name__ == "__main__":
backend/app.py+62-41