import os
import secrets
from fastapi import APIRouter, HTTPException, Depends, Form
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session
import 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():
"""
Admin dashboard for managing API keys.
"""
html_content = """
NutriBot Admin Dashboard
🛡️ Admin Dashboard
Manage B2B Clients & API Keys
"""
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."
}
@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
]
}