Abdullah0327's picture
fixes
98cf243
Raw History Blame Contribute Delete
10.4 kB
"""
Supabase integration: token verification + chat-history persistence.
All database access here uses the *service-role* key, which bypasses Row Level
Security. Because of that, every query is explicitly scoped to the
authenticated user's id β€” never trust a client-supplied user id.
"""
import json
import os
import time
from pathlib import Path
from datetime import datetime, timezone
from dotenv import load_dotenv
from supabase import create_client, Client
load_dotenv(Path(__file__).parent.parent / ".env")
SUPABASE_URL = os.environ.get("SUPABASE_URL", "").rstrip("/")
SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")
SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
# Comma-separated list of emails allowed to upload/manage documents.
ADMIN_EMAILS = {
e.strip().lower()
for e in os.environ.get("ADMIN_EMAILS", "").split(",")
if e.strip()
}
_admin: Client | None = None
def is_configured() -> bool:
return bool(SUPABASE_URL and SERVICE_ROLE_KEY and SUPABASE_ANON_KEY)
def admin() -> Client:
"""Lazily create and reuse a single service-role client."""
global _admin
if _admin is None:
if not is_configured():
raise RuntimeError(
"Supabase is not configured. Set SUPABASE_URL, SUPABASE_ANON_KEY "
"and SUPABASE_SERVICE_ROLE_KEY in your .env file."
)
_admin = create_client(SUPABASE_URL, SERVICE_ROLE_KEY)
return _admin
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
# ── Auth ────────────────────────────────────────────────────────────────────
# Verifying a token is a network round-trip to Supabase; caching it briefly
# shaves that latency off every request. Trade-off: a revoked token stays
# usable for up to TOKEN_CACHE_TTL seconds.
TOKEN_CACHE_TTL = 300
_token_cache: dict[str, tuple[float, object]] = {}
def verify_token(token: str):
"""Validate a Supabase access token and return the user, or None."""
now = time.monotonic()
hit = _token_cache.get(token)
if hit and hit[0] > now:
return hit[1]
try:
res = admin().auth.get_user(token)
user = res.user if res else None
except Exception:
return None
if user is not None:
if len(_token_cache) > 500:
for k in [k for k, v in _token_cache.items() if v[0] <= now]:
del _token_cache[k]
_token_cache[token] = (now + TOKEN_CACHE_TTL, user)
return user
def is_admin(user) -> bool:
"""A user is an admin if their email is listed in ADMIN_EMAILS (.env)."""
email = (getattr(user, "email", "") or "").lower()
return bool(email) and email in ADMIN_EMAILS
# ── Sessions ──────────────────────────────────────────────────────────────────
def create_session(user_id: str, title: str) -> dict:
res = (
admin()
.table("chat_sessions")
.insert({"user_id": user_id, "title": title[:80] or "New chat"})
.execute()
)
return res.data[0]
def list_sessions(user_id: str) -> list[dict]:
res = (
admin()
.table("chat_sessions")
.select("id, title, created_at, updated_at")
.eq("user_id", user_id)
.order("updated_at", desc=True)
.execute()
)
return res.data or []
def get_session(session_id: str, user_id: str) -> dict | None:
res = (
admin()
.table("chat_sessions")
.select("*")
.eq("id", session_id)
.eq("user_id", user_id)
.limit(1)
.execute()
)
return res.data[0] if res.data else None
def touch_session(session_id: str) -> None:
admin().table("chat_sessions").update({"updated_at": _now()}).eq("id", session_id).execute()
def rename_session(session_id: str, user_id: str, title: str) -> None:
admin().table("chat_sessions").update({"title": title[:80]}).eq("id", session_id).eq("user_id", user_id).execute()
def delete_session(session_id: str, user_id: str) -> None:
# messages cascade-delete via the foreign key
admin().table("chat_sessions").delete().eq("id", session_id).eq("user_id", user_id).execute()
def delete_all_sessions(user_id: str) -> None:
admin().table("chat_sessions").delete().eq("user_id", user_id).execute()
# ── Messages ──────────────────────────────────────────────────────────────────
def add_message(session_id: str, role: str, content: str, sources: list | None = None) -> dict:
res = (
admin()
.table("messages")
.insert({
"session_id": session_id,
"role": role,
"content": content,
"sources": sources or [],
})
.execute()
)
return res.data[0]
def list_messages(session_id: str) -> list[dict]:
res = (
admin()
.table("messages")
.select("id, role, content, sources, feedback, created_at")
.eq("session_id", session_id)
.order("created_at")
.execute()
)
return res.data or []
def set_feedback(message_id: str, user_id: str, value: str | None) -> bool:
"""Record πŸ‘/πŸ‘Ž on a message. Verifies the message belongs to the user."""
res = (
admin()
.table("messages")
.select("session_id")
.eq("id", message_id)
.limit(1)
.execute()
)
if not res.data:
return False
if get_session(res.data[0]["session_id"], user_id) is None:
return False
admin().table("messages").update({"feedback": value}).eq("id", message_id).execute()
return True
# ── Analytics (admin) ─────────────────────────────────────────────────────────
NO_ANSWER_PREFIX = "I don't have information"
# "Clear unanswered" stores a cutoff timestamp on disk (no schema change needed):
# refusals older than the cutoff stay in chat history but leave the dashboard.
_STATE_PATH = Path(__file__).parent.parent / "data" / "analytics_state.json"
def _unanswered_cleared_at() -> str:
try:
return json.loads(_STATE_PATH.read_text(encoding="utf-8")).get("unanswered_cleared_at", "")
except Exception:
return ""
def clear_unanswered() -> None:
_STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
_STATE_PATH.write_text(
json.dumps({"unanswered_cleared_at": _now()}), encoding="utf-8"
)
def _admin_user_ids() -> set[str]:
"""Auth user ids of the accounts listed in ADMIN_EMAILS."""
ids: set[str] = set()
if not ADMIN_EMAILS:
return ids
try:
page = 1
while True:
res = admin().auth.admin.list_users(page=page, per_page=200)
users = res if isinstance(res, list) else getattr(res, "users", None) or []
if not users:
break
for u in users:
if (getattr(u, "email", "") or "").lower() in ADMIN_EMAILS:
ids.add(str(u.id))
if len(users) < 200:
break
page += 1
except Exception:
pass # if the lookup fails, stats simply include everyone
return ids
def analytics() -> dict:
"""Aggregate usage statistics for regular users (admin activity excluded)."""
admin_ids = _admin_user_ids()
sess_rows = (
admin()
.table("chat_sessions")
.select("id, user_id")
.limit(10000)
.execute()
).data or []
user_session_ids = {
s["id"] for s in sess_rows if str(s.get("user_id")) not in admin_ids
}
msgs = (
admin()
.table("messages")
.select("role, content, sources, feedback, session_id, created_at")
.order("created_at")
.limit(5000)
.execute()
).data or []
msgs = [m for m in msgs if m.get("session_id") in user_session_ids]
total_questions = sum(1 for m in msgs if m.get("role") == "user")
answers = [m for m in msgs if m.get("role") == "assistant"]
fb_up = sum(1 for m in answers if m.get("feedback") == "up")
fb_down = sum(1 for m in answers if m.get("feedback") == "down")
# Which documents get cited, and which questions the bot could not answer
cited: dict[str, int] = {}
last_user_question: dict[str, str] = {}
unanswered: list[str] = []
cleared_at = _unanswered_cleared_at()
for m in msgs:
if m.get("role") == "user":
last_user_question[m.get("session_id")] = m.get("content", "")
continue
if (m.get("content") or "").startswith(NO_ANSWER_PREFIX):
if cleared_at and (m.get("created_at") or "") <= cleared_at:
continue # dismissed by the admin
q = last_user_question.get(m.get("session_id"))
if q:
unanswered.append(q)
for s in (m.get("sources") or []):
f = s.get("file")
if f:
cited[f] = cited.get(f, 0) + 1
top_documents = sorted(cited.items(), key=lambda x: -x[1])[:10]
# Questions per day for the last 14 days (UTC)
from datetime import timedelta, date
per_day: dict[str, int] = {}
for m in msgs:
if m.get("role") == "user":
day = (m.get("created_at") or "")[:10]
if day:
per_day[day] = per_day.get(day, 0) + 1
today = datetime.now(timezone.utc).date()
daily = [
{"date": (today - timedelta(days=i)).isoformat(),
"count": per_day.get((today - timedelta(days=i)).isoformat(), 0)}
for i in range(13, -1, -1)
]
return {
"total_conversations": len(user_session_ids),
"total_questions": total_questions,
"total_answers": len(answers),
"feedback": {"up": fb_up, "down": fb_down},
"unanswered_count": len(unanswered),
"recent_unanswered": unanswered[-10:][::-1],
"top_documents": [{"file": f, "citations": c} for f, c in top_documents],
"daily_questions": daily,
}