From e7d3f3c5decb63e172cc92f2a43ce38aa4e49edb Mon Sep 17 00:00:00 2001 From: XZH Date: Sun, 30 Aug 2026 17:27:36 -0700 Subject: [PATCH] feat(learner): add self-service learner profiles --- deeptutor/api/routers/auth.py | 38 ++++++++ tests/multi_user/test_learner_profile.py | 9 ++ .../settings/learner-profile/page.tsx | 87 +++++++++++++++++++ web/lib/profile-api.ts | 29 +++++++ 4 files changed, 163 insertions(+) create mode 100644 web/app/(utility)/settings/learner-profile/page.tsx diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py index 5df4e7999..ac6d2e126 100644 --- a/deeptutor/api/routers/auth.py +++ b/deeptutor/api/routers/auth.py @@ -50,6 +50,9 @@ from deeptutor.services.auth import ( set_learner_profile, set_role, ) +from deeptutor.services.auth import ( + get_learner_profile as load_learner_profile, +) from deeptutor.services.codex_auth.contracts import CodexAuthError from deeptutor.services.codex_auth.service import deliver_codex_oauth_callback @@ -765,6 +768,41 @@ async def get_users(_: TokenPayload = Depends(require_admin)) -> list[UserInfo]: return [UserInfo(**u) for u in list_users()] +@router.get("/profile/learner-profile") +async def get_current_learner_profile(current: TokenPayload = Depends(require_auth)) -> dict: + """Return the authenticated learner's own profile.""" + if current.role != "user": + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Learner profile required" + ) + profile = load_learner_profile(current.username) + return {"learner_profile": profile} + + +@router.put("/profile/learner-profile") +async def put_current_learner_profile( + body: LearnerProfileRequest, + current: TokenPayload = Depends(require_auth), +) -> dict: + """Update only the authenticated learner's own profile.""" + if current.role != "user": + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Learner profile required" + ) + from deeptutor.multi_user.learner_profile import normalize_profile + + try: + profile = normalize_profile(body.model_dump(exclude_none=True)) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc) + ) from exc + updated = set_learner_profile(current.username, profile) + if updated is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") + return {"learner_profile": updated} + + @router.get("/users/{username}/learner-profile") async def get_learner_profile(username: str, _: TokenPayload = Depends(require_admin)) -> dict: """Return the structured profile managed for an ordinary learner.""" diff --git a/tests/multi_user/test_learner_profile.py b/tests/multi_user/test_learner_profile.py index 56329bc0a..385e08734 100644 --- a/tests/multi_user/test_learner_profile.py +++ b/tests/multi_user/test_learner_profile.py @@ -1,5 +1,6 @@ from __future__ import annotations +from deeptutor.multi_user.identity import set_learner_profile from deeptutor.multi_user.learner_profile import normalize_profile, prompt_block @@ -43,3 +44,11 @@ def test_prompt_block_is_empty_for_missing_profile_and_lists_trusted_values() -> assert "trusted learner profile" in block assert "Age: 8" in block assert "Grade level: primary_4" in block + + +def test_profile_store_rejects_admin_accounts(tmp_path, monkeypatch) -> None: + from deeptutor.multi_user import identity + + monkeypatch.setattr(identity, "USERS_FILE", tmp_path / "users.json") + identity.save_user("admin", "hash", role="admin") + assert set_learner_profile("admin", {"age": 10}) is None diff --git a/web/app/(utility)/settings/learner-profile/page.tsx b/web/app/(utility)/settings/learner-profile/page.tsx new file mode 100644 index 000000000..cdbda4ab1 --- /dev/null +++ b/web/app/(utility)/settings/learner-profile/page.tsx @@ -0,0 +1,87 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { + getOwnLearnerProfile, + setOwnLearnerProfile, + type LearnerProfile, +} from "@/lib/profile-api"; + +const fields: Array<[keyof LearnerProfile, string]> = [ + ["age", "Age"], + ["grade_level", "Grade level"], + ["curriculum", "Curriculum"], + ["language", "Preferred language"], + ["reading_level", "Reading level"], + ["explanation_style", "Explanation style"], +]; + +export default function LearnerProfileSettingsPage() { + const { t } = useTranslation(); + const [profile, setProfile] = useState({}); + const [status, setStatus] = useState<"idle" | "loading" | "saved" | "error">("loading"); + + useEffect(() => { + void getOwnLearnerProfile() + .then((value) => { + setProfile(value ?? {}); + setStatus("idle"); + }) + .catch(() => setStatus("error")); + }, []); + + const update = (key: keyof LearnerProfile, value: string) => { + setProfile((current) => ({ + ...current, + [key]: key === "age" ? (value ? Number(value) : undefined) : value || undefined, + })); + }; + + const save = async () => { + setStatus("loading"); + try { + setProfile((await setOwnLearnerProfile(profile)) ?? {}); + setStatus("saved"); + } catch { + setStatus("error"); + } + }; + + return ( +
+

{t("Learner profile")}

+

+ {t("Personalize explanations and reading support for your account.")} +

+
+ {fields.map(([key, label]) => ( + + ))} +
+
+ + {status === "saved" && {t("Saved")}} + {status === "error" && {t("Unable to save profile")}} +
+
+ ); +} diff --git a/web/lib/profile-api.ts b/web/lib/profile-api.ts index 22abc6f02..6efd349bc 100644 --- a/web/lib/profile-api.ts +++ b/web/lib/profile-api.ts @@ -1,5 +1,34 @@ import { apiFetch, apiUrl } from "@/lib/api"; +export interface LearnerProfile { + age?: number; + grade_level?: string; + curriculum?: string; + language?: string; + reading_level?: string; + explanation_style?: string; +} + +export async function getOwnLearnerProfile(): Promise { + const res = await apiFetch(apiUrl("/api/v1/auth/profile/learner-profile")); + if (!res.ok) throw new Error("Failed to fetch learner profile"); + const data = (await res.json()) as { learner_profile?: LearnerProfile | null }; + return data.learner_profile ?? null; +} + +export async function setOwnLearnerProfile( + profile: LearnerProfile, +): Promise { + const res = await apiFetch(apiUrl("/api/v1/auth/profile/learner-profile"), { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(profile), + }); + if (!res.ok) throw new Error("Failed to save learner profile"); + const data = (await res.json()) as { learner_profile?: LearnerProfile | null }; + return data.learner_profile ?? null; +} + export interface ProfileInfo { id: string; username: string;