Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(learner): add self-service learner profiles

XZHe7d3f3c5decb
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()]
[email protected]("/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}
+
+
[email protected]("/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<LearnerProfile>({});
+ 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 (
+ <main className="mx-auto max-w-2xl px-6 py-8">
+ <h1 className="text-xl font-semibold">{t("Learner profile")}</h1>
+ <p className="mt-1 text-sm text-[var(--muted-foreground)]">
+ {t("Personalize explanations and reading support for your account.")}
+ </p>
+ <div className="mt-6 grid gap-4 sm:grid-cols-2">
+ {fields.map(([key, label]) => (
+ <label key={key} className="grid gap-1 text-sm">
+ <span>{t(label)}</span>
+ <input
+ type={key === "age" ? "number" : "text"}
+ min={key === "age" ? 3 : undefined}
+ max={key === "age" ? 120 : undefined}
+ value={profile[key] ?? ""}
+ onChange={(event) => update(key, event.target.value)}
+ className="rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-2"
+ />
+ </label>
+ ))}
+ </div>
+ <div className="mt-6 flex items-center gap-3">
+ <button
+ type="button"
+ onClick={() => void save()}
+ disabled={status === "loading"}
+ className="rounded-md bg-[var(--primary)] px-4 py-2 text-sm text-[var(--primary-foreground)] disabled:opacity-60"
+ >
+ {t("Save profile")}
+ </button>
+ {status === "saved" && <span className="text-sm">{t("Saved")}</span>}
+ {status === "error" && <span className="text-sm text-red-600">{t("Unable to save profile")}</span>}
+ </div>
+ </main>
+ );
+}
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<LearnerProfile | null> {
+ 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<LearnerProfile | null> {
+ 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;