File size: 8,069 Bytes
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49f22ac
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49f22ac
c5cf697
 
 
 
49f22ac
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49f22ac
 
 
 
 
 
 
 
 
 
 
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49f22ac
 
 
 
 
 
 
c5cf697
 
 
 
 
49f22ac
c5cf697
49f22ac
 
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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,
    }