Spaces:
Runtime error
Runtime error
api
Browse filesFiles changed (4)
- ._admin_router.pyAdded
- ._app.pyAdded
- admin_router.pyAdded+248
- app.py+8
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248import osimport secretsfrom fastapi import APIRouter, HTTPException, Depends, Formfrom fastapi.responses import HTMLResponsefrom sqlalchemy.orm import Sessionimport database as db
router = APIRouter()
# --- Admin Password from Environment ---ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "change_me_in_secrets")
def get_db(): database = db.SessionLocal() try: yield database finally: database.close()
@router.get("/create-api-key", response_class=HTMLResponse)async def create_api_key_form(): """ Simple HTML form for creating API keys. """ html_content = """ <!DOCTYPE html> <html> <head> <title>NutriBot Admin - Create API Key</title> <style> body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; padding: 20px; } .container { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); max-width: 500px; width: 100%; } h1 { color: #333; margin-bottom: 10px; font-size: 24px; } .subtitle { color: #666; margin-bottom: 30px; font-size: 14px; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 8px; color: #555; font-weight: 600; font-size: 14px; } input { width: 100%; padding: 12px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 14px; box-sizing: border-box; transition: border-color 0.3s; } input:focus { outline: none; border-color: #667eea; } button { width: 100%; padding: 14px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 6px; font-size: 16px; font-weight: 600; cursor: pointer; transition: transform 0.2s, box-shadow 0.2s; } button:hover { transform: translateY(-2px); box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4); } button:active { transform: translateY(0); } .result { margin-top: 30px; padding: 20px; background: #f0f7ff; border-left: 4px solid #667eea; border-radius: 6px; display: none; } .result.success { display: block; } .result.error { display: block; background: #fff0f0; border-left-color: #e74c3c; } .api-key { background: #333; color: #0f0; padding: 15px; border-radius: 6px; font-family: 'Courier New', monospace; font-size: 13px; margin: 15px 0; word-break: break-all; cursor: pointer; } .warning { color: #e74c3c; font-size: 12px; margin-top: 10px; font-weight: 600; } </style> </head> <body> <div class="container"> <h1>🔑 Create API Key</h1> <p class="subtitle">Generate a new API key for a B2B client</p> <form id="apiKeyForm"> <div class="form-group"> <label for="password">Admin Password:</label> <input type="password" id="password" name="password" required placeholder="Enter admin password"> </div> <div class="form-group"> <label for="client_name">Client Name:</label> <input type="text" id="client_name" name="client_name" required placeholder="e.g., HealthTechCo"> </div> <button type="submit">Generate API Key</button> </form> <div id="result" class="result"></div> </div>
<script> document.getElementById('apiKeyForm').addEventListener('submit', async (e) => { e.preventDefault(); const formData = new FormData(e.target); const resultDiv = document.getElementById('result'); try { const response = await fetch('/admin/create-api-key', { method: 'POST', body: formData }); const data = await response.json(); if (response.ok) { resultDiv.className = 'result success'; resultDiv.innerHTML = ` <h3 style="margin-top: 0; color: #27ae60;">✅ Success!</h3> <p><strong>Client Name:</strong> ${data.client_name}</p> <p><strong>Client ID:</strong> ${data.client_id}</p> <p style="margin-top: 15px; margin-bottom: 5px;"><strong>API Key:</strong></p> <div class="api-key" onclick="copyToClipboard(this.textContent)" title="Click to copy"> ${data.api_key} </div> <p class="warning">⚠️ This key will only be shown once. Copy it now!</p> `; e.target.reset(); } else { throw new Error(data.detail || 'An error occurred'); } } catch (error) { resultDiv.className = 'result error'; resultDiv.innerHTML = ` <h3 style="margin-top: 0; color: #e74c3c;">❌ Error</h3> <p>${error.message}</p> `; } }); function copyToClipboard(text) { navigator.clipboard.writeText(text).then(() => { alert('API Key copied to clipboard!'); }); } </script> </body> </html> """ return html_content
@router.post("/create-api-key")async def create_api_key( password: str = Form(...), client_name: str = Form(...), database: Session = Depends(get_db)): """ Create a new API key for a B2B client. Protected by admin password. """ # Verify admin password if password != ADMIN_PASSWORD: raise HTTPException(status_code=401, detail="Invalid admin password") # Validate client name if not client_name or not client_name.strip(): raise HTTPException(status_code=400, detail="Client name cannot be empty") client_name = client_name.strip() # Check if client already exists existing_client = db.get_api_client_by_name(database, client_name) if existing_client: raise HTTPException(status_code=400, detail=f"Client '{client_name}' already exists") # Generate secure API key api_key = f"nbk_live_{secrets.token_hex(32)}" # Add client to database new_client = db.add_api_client(database, client_name, api_key) return { "status": "success", "client_name": new_client.client_name, "client_id": new_client.id, "api_key": api_key, "message": "API Key created successfully. This key will not be shown again." }7 unmodified lines891011121340 unmodified lines5455565758597 unmodified linesfrom sqlalchemy.orm import Sessionimport database as dbfrom website_chat_router import chat_routerfrom process_user_docs import process_user_document# --- Load Environment Variables ---40 unmodified linesreturn client# --- API Routers ---# The chat router is now also protected by the API keyapp.include_router(chat_router,7 unmodified lines89101112131440 unmodified lines555657585960616263646566677 unmodified linesfrom sqlalchemy.orm import Sessionimport database as dbfrom website_chat_router import chat_routerfrom admin_router import router as admin_routerfrom process_user_docs import process_user_document# --- Load Environment Variables ---40 unmodified linesreturn client# --- API Routers ---# Admin router (no authentication required - uses password in the form)app.include_router(admin_router,prefix="/admin",tags=["Admin"])# The chat router is now also protected by the API keyapp.include_router(chat_router,
._admin_router.pyAdded
._app.pyAdded
admin_router.pyAdded+248
app.py+8