backend / routes /admin.py
muhammadhasnain100's picture
add code
49f22ac
Raw History Blame Contribute Delete
8.07 kB
import os
import uuid
from math import ceil
from fastapi import APIRouter, File, Header, HTTPException, Query, Request, UploadFile
from passlib.context import CryptContext
from pydantic import BaseModel, EmailStr, Field
from database import chats_collection
from dependencies import CurrentAdminIdDep
from security import (
create_admin_access_token,
create_admin_refresh_token,
decode_admin_refresh_token,
)
router = APIRouter(prefix="/admin", tags=["admin"])
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
MAX_KB_CSV_BYTES = 25 * 1024 * 1024
class AdminRegister(BaseModel):
email: EmailStr
password: str = Field(min_length=6)
full_name: str | None = None
class AdminLogin(BaseModel):
email: EmailStr
password: str
class AdminPublic(BaseModel):
admin_id: str
email: str
full_name: str | None = None
class AdminRefreshRequest(BaseModel):
refresh_token: str
class UserRow(BaseModel):
user_id: str
email: str
full_name: str | None = None
chat_count: int = 0
class PaginatedUsers(BaseModel):
items: list[UserRow]
total: int
page: int
page_size: int
pages: int
def _hash_password(password: str) -> str:
return pwd_context.hash(password)
def _verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
def _admin_public(doc: dict) -> AdminPublic:
return AdminPublic(
admin_id=doc["_id"],
email=doc["email"],
full_name=doc.get("full_name"),
)
def _user_row(doc: dict, *, chat_count: int = 0) -> UserRow:
return UserRow(
user_id=doc["_id"],
email=doc["email"],
full_name=doc.get("full_name"),
chat_count=chat_count,
)
def _bootstrap_ok(request: Request, bootstrap_secret_header: str | None) -> bool:
admins_coll = request.app.state.admins_collection
if admins_coll.count_documents({}) == 0:
return True
env_secret = os.getenv("ADMIN_BOOTSTRAP_SECRET", "").strip()
if not env_secret:
return False
hdr = (bootstrap_secret_header or "").strip()
return hdr == env_secret
@router.post("/register", response_model=AdminPublic)
def register_admin(
body: AdminRegister,
request: Request,
x_admin_bootstrap_secret: str | None = Header(default=None, alias="X-Admin-Bootstrap-Secret"),
):
if not _bootstrap_ok(request, x_admin_bootstrap_secret):
raise HTTPException(
status_code=403,
detail="Admin registration is closed. Set ADMIN_BOOTSTRAP_SECRET and send "
"X-Admin-Bootstrap-Secret header, or register while no admins exist.",
)
admins_coll = request.app.state.admins_collection
email_lower = body.email.lower().strip()
if admins_coll.find_one({"email": email_lower}):
raise HTTPException(status_code=409, detail="Email already registered")
admin_id = str(uuid.uuid4())
doc = {
"_id": admin_id,
"email": email_lower,
"password_hash": _hash_password(body.password),
"full_name": body.full_name.strip() if body.full_name else None,
}
admins_coll.insert_one(doc)
return _admin_public(doc)
@router.post("/login")
def admin_login(body: AdminLogin, request: Request):
admins_coll = request.app.state.admins_collection
email_lower = body.email.lower().strip()
admin = admins_coll.find_one({"email": email_lower})
if not admin or not _verify_password(body.password, admin["password_hash"]):
raise HTTPException(status_code=401, detail="Invalid email or password")
aid = admin["_id"]
return {
"access_token": create_admin_access_token(aid),
"refresh_token": create_admin_refresh_token(aid),
"token_type": "bearer",
"admin": _admin_public(admin),
}
@router.post("/refresh")
def admin_refresh(body: AdminRefreshRequest, request: Request):
admins_coll = request.app.state.admins_collection
aid = decode_admin_refresh_token(body.refresh_token.strip())
admin = admins_coll.find_one({"_id": aid})
if not admin:
raise HTTPException(status_code=401, detail="Admin no longer exists")
return {
"access_token": create_admin_access_token(aid),
"refresh_token": create_admin_refresh_token(aid),
"token_type": "bearer",
}
@router.get("/users", response_model=PaginatedUsers)
def list_users(
_: CurrentAdminIdDep,
request: Request,
page: int = Query(default=1, ge=1),
page_size: int = Query(default=20, ge=1, le=100),
):
users_coll = request.app.state.users_collection
total = users_coll.count_documents({})
skip = (page - 1) * page_size
cursor = (
users_coll.find({}, {"password_hash": 0})
.sort("email", 1)
.skip(skip)
.limit(page_size)
)
docs = list(cursor)
user_ids = [d["_id"] for d in docs]
counts: dict[str, int] = {}
if user_ids:
pipeline = [
{"$match": {"user_id": {"$in": user_ids}}},
{"$group": {"_id": "$user_id", "n": {"$sum": 1}}},
]
for row in chats_collection.aggregate(pipeline):
counts[row["_id"]] = row["n"]
items = [_user_row(doc, chat_count=counts.get(doc["_id"], 0)) for doc in docs]
pages = ceil(total / page_size) if total else 0
return PaginatedUsers(
items=items,
total=total,
page=page,
page_size=page_size,
pages=pages,
)
@router.delete("/users/{user_id}")
def delete_user(
user_id: str,
_: CurrentAdminIdDep,
request: Request,
):
users_coll = request.app.state.users_collection
result = users_coll.delete_one({"_id": user_id})
if result.deleted_count == 0:
raise HTTPException(status_code=404, detail="User not found")
chats_collection.delete_many({"user_id": user_id})
return {"message": "User and related chats deleted."}
@router.get("/knowledge-base/status")
def knowledge_base_status(_: CurrentAdminIdDep, request: Request):
bot = request.app.state.chatbot
base_present = [p for p in bot.paths if os.path.isfile(p)]
vector_count: int | None = None
try:
if bot.faiss_index is not None and getattr(bot.faiss_index, "index", None) is not None:
vector_count = int(bot.faiss_index.index.ntotal)
except Exception:
vector_count = None
upload_names = bot.list_kb_upload_filenames()
return {
"index_path": bot.index_path,
"kb_upload_dir": bot.kb_upload_dir,
"index_on_disk": os.path.exists(bot.index_path),
"retriever_ready": bot.faiss_retriever is not None,
"vector_count": vector_count,
"base_csv_files": base_present,
"uploaded_csv_files": upload_names,
"uploaded_csv_count": len(upload_names),
}
@router.post("/knowledge-base/upload")
async def upload_knowledge_base_csv_merge(
_: CurrentAdminIdDep,
request: Request,
file: UploadFile = File(...),
):
"""Accept one CSV; embed rows and merge into FAISS (`update_faiss_index`)."""
if not file.filename or not str(file.filename).strip():
raise HTTPException(status_code=400, detail="No filename.")
if not str(file.filename).lower().endswith('.csv'):
raise HTTPException(status_code=400, detail="Only .csv files are accepted.")
data = await file.read()
if len(data) > MAX_KB_CSV_BYTES:
raise HTTPException(status_code=413, detail="File too large (max 25 MB).")
chatbot = request.app.state.chatbot
try:
stats = chatbot.merge_kb_csv_bytes(file.filename, data)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except RuntimeError as e:
raise HTTPException(status_code=503, detail=str(e))
except Exception:
raise HTTPException(
status_code=500,
detail="Could not merge CSV into the index (check embedding model matches existing index).",
)
return {
"message": "Knowledge base updated (merged into FAISS).",
**stats,
}