Spaces:
Runtime error
Runtime error
Add client listing feature to Admin Dashboard
Browse filesFiles changed (2)
- admin_router.py+172-54
- database.py+6
19 unmodified lines2021222324252627282930313210 unmodified lines43444546474849505152535455565758596034 unmodified lines95969798991001011021032 unmodified lines1061071081091101111121131141151161171186 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620738 unmodified lines24624724819 unmodified lines@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;10 unmodified linespadding: 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;34 unmodified linestransform: translateY(-2px);box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);}button:active {transform: translateY(0);}.result {margin-top: 30px;padding: 20px;2 unmodified linesborder-radius: 6px;display: none;}.result.success {display: block;}.result.error {display: block;background: #fff0f0;border-left-color: #e74c3c;}.api-key {background: #333;6 unmodified linesword-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" requiredplaceholder="Enter admin password"></div><div class="form-group"><label for="client_name">Client Name:</label><input type="text" id="client_name" name="client_name" requiredplaceholder="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>38 unmodified lines"api_key": api_key,"message": "API Key created successfully. This key will not be shown again."}19 unmodified lines2021222324252627282930313210 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848534 unmodified lines1201211221231241252 unmodified lines1281291301311321331341351361371386 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230338 unmodified lines34234334434534634734834935035135235335435535635735835936036136236336436536619 unmodified lines@router.get("/create-api-key", response_class=HTMLResponse)async def create_api_key_form():"""Admin dashboard for managing API keys."""html_content = """<!DOCTYPE html><html><head><title>NutriBot Admin Dashboard</title><style>body {font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;10 unmodified linespadding: 40px;border-radius: 12px;box-shadow: 0 10px 40px rgba(0,0,0,0.2);max-width: 600px;width: 100%;}h1 {color: #333;margin-bottom: 10px;font-size: 24px;text-align: center;}.subtitle {color: #666;margin-bottom: 30px;font-size: 14px;text-align: center;}.tabs {display: flex;margin-bottom: 20px;border-bottom: 2px solid #eee;}.tab {padding: 10px 20px;cursor: pointer;font-weight: 600;color: #666;border-bottom: 2px solid transparent;margin-bottom: -2px;}.tab.active {color: #667eea;border-bottom-color: #667eea;}.tab-content {display: none;}.tab-content.active {display: block;}.form-group {margin-bottom: 20px;34 unmodified linestransform: translateY(-2px);box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);}.result {margin-top: 30px;padding: 20px;2 unmodified linesborder-radius: 6px;display: none;}.result.success { display: block; }.result.error {display: block;background: #fff0f0;border-left-color: #e74c3c;}.api-key {background: #333;6 unmodified linesword-break: break-all;cursor: pointer;}table {width: 100%;border-collapse: collapse;margin-top: 10px;}th, td {padding: 12px;text-align: left;border-bottom: 1px solid #eee;}th {background: #f8f9fa;font-weight: 600;color: #555;}.badge {background: #e0e0e0;padding: 4px 8px;border-radius: 12px;font-size: 12px;}</style></head><body><div class="container"><h1>🛡️ Admin Dashboard</h1><p class="subtitle">Manage B2B Clients & API Keys</p><div class="tabs"><div class="tab active" onclick="switchTab('create')">Create Key</div><div class="tab" onclick="switchTab('list')">View Clients</div></div><!-- Create Key Tab --><div id="create" class="tab-content active"><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="createResult" class="result"></div></div><!-- List Clients Tab --><div id="list" class="tab-content"><form id="listClientsForm"><div class="form-group"><label for="list_password">Admin Password:</label><input type="password" id="list_password" name="password" required placeholder="Enter admin password"></div><button type="submit">Load Clients</button></form><div id="listResult" style="margin-top: 20px;"></div></div></div><script>function switchTab(tabName) {document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));event.target.classList.add('active');document.getElementById(tabName).classList.add('active');// Sync password if typedconst p1 = document.getElementById('password').value;const p2 = document.getElementById('list_password').value;if(p1 && !p2) document.getElementById('list_password').value = p1;if(!p1 && p2) document.getElementById('password').value = p2;}// Create Key Handlerdocument.getElementById('apiKeyForm').addEventListener('submit', async (e) => {e.preventDefault();const formData = new FormData(e.target);const resultDiv = document.getElementById('createResult');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;">✅ Created!</h3><p><strong>Client:</strong> ${data.client_name} (ID: ${data.client_id})</p><div class="api-key" onclick="navigator.clipboard.writeText(this.textContent); alert('Copied!')">${data.api_key}</div><p style="color: #e74c3c; font-size: 12px;">⚠️ Copy now! Won't be shown again.</p>`;e.target.reset();} else {throw new Error(data.detail || 'Error');}} catch (error) {resultDiv.className = 'result error';resultDiv.innerHTML = `<p>❌ ${error.message}</p>`;}});// List Clients Handlerdocument.getElementById('listClientsForm').addEventListener('submit', async (e) => {e.preventDefault();const formData = new FormData(e.target);const resultDiv = document.getElementById('listResult');resultDiv.innerHTML = '<p style="text-align:center">Loading...</p>';try {const response = await fetch('/admin/list-clients', {method: 'POST',body: formData});const data = await response.json();if (response.ok) {if (data.clients.length === 0) {resultDiv.innerHTML = '<p style="text-align:center; color:#666">No clients found.</p>';return;}let html = `<p><strong>Total Clients:</strong> ${data.count}</p><table><thead><tr><th>ID</th><th>Name</th></tr></thead><tbody>`;data.clients.forEach(client => {html += `<tr><td><span class="badge">${client.id}</span></td><td>${client.name}</td></tr>`;});html += '</tbody></table>';resultDiv.innerHTML = html;} else {throw new Error(data.detail || 'Error');}} catch (error) {resultDiv.innerHTML = `<p style="color: #e74c3c; text-align: center;">❌ ${error.message}</p>`;}});</script></body></html>38 unmodified lines"api_key": api_key,"message": "API Key created successfully. This key will not be shown again."}@router.post("/list-clients")async def list_clients(password: str = Form(...),database: Session = Depends(get_db)):"""List all registered clients.Protected by admin password."""if password != ADMIN_PASSWORD:raise HTTPException(status_code=401, detail="Invalid admin password")clients = db.get_all_api_clients(database)return {"count": len(clients),"clients": [{"id": c.id, "name": c.client_name}for c in clients]}
101 unmodified lines102103104105106107101 unmodified linesreturn clientreturn None# --- NEW: Document Management Functions ---def add_document_metadata(db_session, client_id: int, filename: str, file_hash: str,file_size: int, chunk_count: int = 0, status: str = "completed"):101 unmodified lines102103104105106107108109110111112113101 unmodified linesreturn clientreturn Nonedef get_all_api_clients(db_session):"""Returns a list of all API clients."""return db_session.query(ApiClient).all()# --- NEW: Document Management Functions ---def add_document_metadata(db_session, client_id: int, filename: str, file_hash: str,file_size: int, chunk_count: int = 0, status: str = "completed"):
admin_router.py+172-54
database.py+6