nikeshn commited on
Commit
3a437f7
Β·
verified Β·
1 Parent(s): 4d33aa5

Update src/api/admin.py

Browse files
Files changed (1) hide show
  1. src/api/admin.py +51 -11
src/api/admin.py CHANGED
@@ -21,27 +21,53 @@ from src.config import get_settings
21
  from src.services.runtime_store import JsonRuntimeStore
22
 
23
  router = APIRouter()
24
- admin_sessions: Dict[str, float] = {}
25
 
26
- _START_TIME = time.time()
27
 
28
- _CONFIG_DEFAULTS: Dict[str, Any] = {
29
- "max_results": 5,
30
- "maintenance_mode": False,
31
- "welcome_message": "Hi! I'm LibBee, the Khalifa University Library AI Assistant.",
32
- "custom_instructions": "",
33
- "announcement": "",
34
- "maintenance_message": "LibBee is currently under maintenance. Please try again shortly.",
35
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
 
38
  # ── Session helpers ────────────────────────────────────────────────────────────
39
 
40
  def _cleanup_sessions() -> None:
41
  now = time.time()
42
- expired = [t for t, exp in admin_sessions.items() if exp <= now]
43
  for t in expired:
44
  admin_sessions.pop(t, None)
 
45
 
46
 
47
  def _require_session(request: Request) -> None:
@@ -106,6 +132,7 @@ async def admin_auth(req: LoginRequest):
106
  raise HTTPException(status_code=401, detail="Invalid password")
107
  token = secrets.token_hex(32)
108
  admin_sessions[token] = time.time() + 86400
 
109
  resp = Response(content='{"status":"ok"}', media_type="application/json")
110
  resp.set_cookie(key="admin_session", value=token, httponly=True,
111
  max_age=86400, samesite="lax")
@@ -117,6 +144,7 @@ async def admin_logout_post(request: Request):
117
  token = request.cookies.get("admin_session")
118
  if token:
119
  admin_sessions.pop(token, None)
 
120
  resp = Response(content='{"status":"ok"}', media_type="application/json")
121
  resp.delete_cookie("admin_session")
122
  return resp
@@ -417,6 +445,18 @@ setInterval(loadRecentQueries, 60000);
417
 
418
  # ── API endpoints ──────────────────────────────────────────────────────────────
419
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  @router.get("/config")
421
  async def get_config(request: Request):
422
  _require_session(request)
 
21
  from src.services.runtime_store import JsonRuntimeStore
22
 
23
  router = APIRouter()
24
+ admin_sessions: Dict[str, float] = {} # in-memory cache
25
 
 
26
 
27
+ # ── Persistent session store ──────────────────────────────────────────────────
28
+
29
+ def _sessions_store() -> JsonRuntimeStore:
30
+ """Sessions stored at /data/admin_sessions.json β€” survives container restarts."""
31
+ settings = get_settings()
32
+ path = settings.runtime_path.parent / "admin_sessions.json"
33
+ # Use /data if CONFIG_STORE_PATH is set to /data/..., else use runtime_path
34
+ if "data" in str(settings.config_path):
35
+ path = settings.config_path.parent / "admin_sessions.json"
36
+ return JsonRuntimeStore(path, default={})
37
+
38
+
39
+ def _load_sessions() -> Dict[str, float]:
40
+ """Load sessions from disk and merge into in-memory cache."""
41
+ global admin_sessions
42
+ try:
43
+ data = _sessions_store().load()
44
+ now = time.time()
45
+ # Only keep non-expired sessions
46
+ valid = {t: exp for t, exp in data.items() if isinstance(exp, (int, float)) and exp > now}
47
+ admin_sessions.update(valid)
48
+ return admin_sessions
49
+ except Exception:
50
+ return admin_sessions
51
+
52
+
53
+ def _save_sessions() -> None:
54
+ """Persist current valid sessions to disk."""
55
+ try:
56
+ now = time.time()
57
+ valid = {t: exp for t, exp in admin_sessions.items() if exp > now}
58
+ _sessions_store().save(valid)
59
+ except Exception:
60
+ pass
61
 
62
 
63
  # ── Session helpers ────────────────────────────────────────────────────────────
64
 
65
  def _cleanup_sessions() -> None:
66
  now = time.time()
67
+ expired = [t for t, exp in list(admin_sessions.items()) if exp <= now]
68
  for t in expired:
69
  admin_sessions.pop(t, None)
70
+ _load_sessions() # merge any sessions saved by other workers
71
 
72
 
73
  def _require_session(request: Request) -> None:
 
132
  raise HTTPException(status_code=401, detail="Invalid password")
133
  token = secrets.token_hex(32)
134
  admin_sessions[token] = time.time() + 86400
135
+ _save_sessions()
136
  resp = Response(content='{"status":"ok"}', media_type="application/json")
137
  resp.set_cookie(key="admin_session", value=token, httponly=True,
138
  max_age=86400, samesite="lax")
 
144
  token = request.cookies.get("admin_session")
145
  if token:
146
  admin_sessions.pop(token, None)
147
+ _save_sessions()
148
  resp = Response(content='{"status":"ok"}', media_type="application/json")
149
  resp.delete_cookie("admin_session")
150
  return resp
 
445
 
446
  # ── API endpoints ──────────────────────────────────────────────────────────────
447
 
448
+ @router.get("/public-config")
449
+ async def public_config():
450
+ """Public endpoint β€” no auth required. Returns safe fields for the frontend."""
451
+ cfg = _load_config()
452
+ return {
453
+ "welcome_message": cfg.get("welcome_message", ""),
454
+ "announcement": cfg.get("announcement", ""),
455
+ "maintenance_mode": cfg.get("maintenance_mode", False),
456
+ "maintenance_message": cfg.get("maintenance_message", ""),
457
+ }
458
+
459
+
460
  @router.get("/config")
461
  async def get_config(request: Request):
462
  _require_session(request)