Update src/api/admin.py
Browse files20 unmodified lines21222324252627282930313233343536373839404142434445464758 unmodified lines1061071081091101115 unmodified lines117118119120121122294 unmodified lines41741841942042142220 unmodified linesfrom src.services.runtime_store import JsonRuntimeStorerouter = APIRouter()admin_sessions: Dict[str, float] = {}_START_TIME = time.time()_CONFIG_DEFAULTS: Dict[str, Any] = {"max_results": 5,"maintenance_mode": False,"welcome_message": "Hi! I'm LibBee, the Khalifa University Library AI Assistant.","custom_instructions": "","announcement": "","maintenance_message": "LibBee is currently under maintenance. Please try again shortly.",}# ββ Session helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _cleanup_sessions() -> None:now = time.time()expired = [t for t, exp in admin_sessions.items() if exp <= now]for t in expired:admin_sessions.pop(t, None)def _require_session(request: Request) -> None:58 unmodified linesraise HTTPException(status_code=401, detail="Invalid password")token = secrets.token_hex(32)admin_sessions[token] = time.time() + 86400resp = Response(content='{"status":"ok"}', media_type="application/json")resp.set_cookie(key="admin_session", value=token, httponly=True,max_age=86400, samesite="lax")5 unmodified linestoken = request.cookies.get("admin_session")if token:admin_sessions.pop(token, None)resp = Response(content='{"status":"ok"}', media_type="application/json")resp.delete_cookie("admin_session")return resp294 unmodified lines# ββ API endpoints ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@router.get("/config")async def get_config(request: Request):_require_session(request)20 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727358 unmodified lines1321331341351361371385 unmodified lines144145146147148149150294 unmodified lines44544644744844945045145245345445545645745845946046146220 unmodified linesfrom src.services.runtime_store import JsonRuntimeStorerouter = APIRouter()admin_sessions: Dict[str, float] = {} # in-memory cache# ββ Persistent session store ββββββββββββββββββββββββββββββββββββββββββββββββββdef _sessions_store() -> JsonRuntimeStore:"""Sessions stored at /data/admin_sessions.json β survives container restarts."""settings = get_settings()path = settings.runtime_path.parent / "admin_sessions.json"# Use /data if CONFIG_STORE_PATH is set to /data/..., else use runtime_pathif "data" in str(settings.config_path):path = settings.config_path.parent / "admin_sessions.json"return JsonRuntimeStore(path, default={})def _load_sessions() -> Dict[str, float]:"""Load sessions from disk and merge into in-memory cache."""global admin_sessionstry:data = _sessions_store().load()now = time.time()# Only keep non-expired sessionsvalid = {t: exp for t, exp in data.items() if isinstance(exp, (int, float)) and exp > now}admin_sessions.update(valid)return admin_sessionsexcept Exception:return admin_sessionsdef _save_sessions() -> None:"""Persist current valid sessions to disk."""try:now = time.time()valid = {t: exp for t, exp in admin_sessions.items() if exp > now}_sessions_store().save(valid)except Exception:pass# ββ Session helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _cleanup_sessions() -> None:now = time.time()expired = [t for t, exp in list(admin_sessions.items()) if exp <= now]for t in expired:admin_sessions.pop(t, None)_load_sessions() # merge any sessions saved by other workersdef _require_session(request: Request) -> None:58 unmodified linesraise HTTPException(status_code=401, detail="Invalid password")token = secrets.token_hex(32)admin_sessions[token] = time.time() + 86400_save_sessions()resp = Response(content='{"status":"ok"}', media_type="application/json")resp.set_cookie(key="admin_session", value=token, httponly=True,max_age=86400, samesite="lax")5 unmodified linestoken = request.cookies.get("admin_session")if token:admin_sessions.pop(token, None)_save_sessions()resp = Response(content='{"status":"ok"}', media_type="application/json")resp.delete_cookie("admin_session")return resp294 unmodified lines# ββ API endpoints ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@router.get("/public-config")async def public_config():"""Public endpoint β no auth required. Returns safe fields for the frontend."""cfg = _load_config()return {"welcome_message": cfg.get("welcome_message", ""),"announcement": cfg.get("announcement", ""),"maintenance_mode": cfg.get("maintenance_mode", False),"maintenance_message": cfg.get("maintenance_message", ""),}@router.get("/config")async def get_config(request: Request):_require_session(request)
src/api/admin.py+51-11