DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(auth): gate learner-only paths on "non-admin" instead of "exactly user"
polaris-smart5357e0c29d32
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.pyindex ea923a19c..8877a39ad 100644--- a/deeptutor/api/routers/auth.py+++ b/deeptutor/api/routers/auth.py@@ -1421,7 +1421,7 @@ async def get_users(_: TokenPayload = Depends(require_admin)) -> list[UserInfo]:def _require_local_learner(current: TokenPayload) -> tuple[str, dict]:"""Resolve a self-service profile request to its local learner account."""- if current.role != "user":+ if current.role == "admin":raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Learner profile required")@@ -1476,7 +1476,7 @@ async def get_learner_profile(username: str, _: TokenPayload = Depends(require_auser = get_user(username)if (user is None- or str(user.get("role") or "user") != "user"+ or str(user.get("role") or "user") == "admin"or str(user.get("preset") or "standard") != "learner"):raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")@@ -1495,7 +1495,7 @@ async def put_learner_profile(user = get_user(username)if (user is None- or str(user.get("role") or "user") != "user"+ or str(user.get("role") or "user") == "admin"or str(user.get("preset") or "standard") != "learner"):raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")diff --git a/deeptutor/multi_user/device_credentials.py b/deeptutor/multi_user/device_credentials.pyindex f006614d2..b0a5baffb 100644--- a/deeptutor/multi_user/device_credentials.py+++ b/deeptutor/multi_user/device_credentials.py@@ -156,7 +156,7 @@ def _active_account(user_id: str) -> tuple[str, dict[str, Any]] | None:if account is None:return Noneusername, record = account- if str(record.get("role") or "user") != "user" or bool(record.get("disabled")):+ if str(record.get("role") or "user") == "admin" or bool(record.get("disabled")):return Noneif str(record.get("preset") or "standard") != "learner":return Nonediff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.pyindex 9cc99bc7c..cefd69021 100644--- a/deeptutor/multi_user/identity.py+++ b/deeptutor/multi_user/identity.py@@ -308,7 +308,7 @@ def set_learner_profile(username: str, profile: dict[str, Any] | None) -> dict[srecord = users.get(username)if (record is None- or str(record.get("role") or "user") != "user"+ or str(record.get("role") or "user") == "admin"or str(record.get("preset") or "standard") != "learner"):return Nonediff --git a/tests/multi_user/test_device_credentials.py b/tests/multi_user/test_device_credentials.pyindex 7f22f1586..4beed48d6 100644--- a/tests/multi_user/test_device_credentials.py+++ b/tests/multi_user/test_device_credentials.py@@ -510,3 +510,47 @@ def _add_seconds(value: datetime, seconds: int) -> datetime:if value.tzinfo is None:value = value.replace(tzinfo=timezone.utc)return value + timedelta(seconds=seconds)+++def test_device_login_admits_non_admin_learner_accounts_and_still_rejects_admins(+ mu_isolated_root, monkeypatch+):+ from deeptutor.multi_user.identity import save_user+ from deeptutor.services.auth import hash_password++ client, users = _client(mu_isolated_root, monkeypatch)+ teacher = save_user(+ "tess", hash_password("teacher-password"), role="teacher", preset="learner"+ )+ issued = client.post(+ "/api/auth/devices",+ headers=_auth(users["admin_token"]),+ json={+ "user_id": teacher["id"],+ "device_name": "Teacher tablet",+ "expires_in_days": 30,+ "daily_limit_minutes": 30,+ },+ )+ assert issued.status_code == 201, issued.text++ login = client.post(+ "/api/auth/device-login",+ json={"pairing_code": issued.json()["pairing_code"], "pin": issued.json()["pin"]},+ )+ assert login.status_code == 200, login.text+ assert login.json()["username"] == "tess"+ assert login.json()["role"] == "teacher"++ admin_issue = client.post(+ "/api/auth/devices",+ headers=_auth(users["admin_token"]),+ json={+ "user_id": users["admin"]["id"],+ "device_name": "Admin tablet",+ "expires_in_days": 30,+ "daily_limit_minutes": 30,+ },+ )+ assert admin_issue.status_code == 400+ assert "active learner account" in admin_issue.json()["detail"]diff --git a/tests/multi_user/test_learner_profile.py b/tests/multi_user/test_learner_profile.pyindex 1008b0653..5f3c56a3c 100644--- a/tests/multi_user/test_learner_profile.py+++ b/tests/multi_user/test_learner_profile.py@@ -103,3 +103,116 @@ def test_admin_profile_api_is_learner_only_and_can_clear_profile(from deeptutor.services.auth import get_learner_profileassert get_learner_profile("learner") is None+++def test_non_admin_learner_accounts_can_manage_own_learner_profile(+ mu_isolated_root, monkeypatch+) -> None:+ from deeptutor.api.routers import auth as auth_router+ from deeptutor.multi_user.identity import save_user+ from deeptutor.services.auth import TokenPayload, hash_password++ # A non-empty store keeps save_user from bootstrapping the first account+ # to admin, so "tess" actually lands as a teacher.+ save_user("root", hash_password("root-password"), role="admin")+ teacher = save_user(+ "tess", hash_password("teacher-password"), role="teacher", preset="learner"+ )+ tokens = {+ "teacher-token": TokenPayload(+ username="tess", role="teacher", user_id=teacher["id"]+ )+ }+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", True)+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))++ app = FastAPI()+ app.include_router(auth_router.router, prefix="/api/auth")+ client = TestClient(app)+ headers = {"Authorization": "Bearer teacher-token"}++ updated = client.put(+ "/api/auth/profile/learner-profile",+ headers=headers,+ json={"age": 9, "language": "zh-CN"},+ )+ assert updated.status_code == 200, updated.text+ assert updated.json()["learner_profile"]["age"] == 9++ fetched = client.get("/api/auth/profile/learner-profile", headers=headers)+ assert fetched.status_code == 200+ assert fetched.json()["learner_profile"]["age"] == 9+++def test_admin_managed_learner_profile_admits_non_admin_targets(+ mu_isolated_root, monkeypatch+) -> None:+ from deeptutor.api.routers import auth as auth_router+ from deeptutor.multi_user.identity import get_learner_profile, save_user+ from deeptutor.services.auth import TokenPayload, hash_password++ admin = save_user("root", hash_password("root-password"), role="admin")+ save_user(+ "tess", hash_password("teacher-password"), role="teacher", preset="learner"+ )+ tokens = {+ "admin-token": TokenPayload(username="root", role="admin", user_id=admin["id"])+ }+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", True)+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))++ app = FastAPI()+ app.include_router(auth_router.router, prefix="/api/auth")+ client = TestClient(app)+ headers = {"Authorization": "Bearer admin-token"}++ updated = client.put(+ "/api/auth/users/tess/learner-profile",+ headers=headers,+ json={"age": 10, "language": "zh-CN"},+ )+ assert updated.status_code == 200, updated.text+ assert updated.json()["learner_profile"]["age"] == 10++ fetched = client.get("/api/auth/users/tess/learner-profile", headers=headers)+ assert fetched.status_code == 200+ assert fetched.json()["learner_profile"]["age"] == 10+ assert get_learner_profile("tess")["age"] == 10+++def test_admin_accounts_still_excluded_from_learner_profile_paths(+ mu_isolated_root, monkeypatch+) -> None:+ from deeptutor.api.routers import auth as auth_router+ from deeptutor.multi_user.identity import save_user, set_learner_profile+ from deeptutor.services.auth import TokenPayload, hash_password++ admin = save_user(+ "root", hash_password("root-password"), role="admin", preset="learner"+ )+ tokens = {+ "admin-token": TokenPayload(username="root", role="admin", user_id=admin["id"])+ }+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", True)+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))++ app = FastAPI()+ app.include_router(auth_router.router, prefix="/api/auth")+ client = TestClient(app)+ headers = {"Authorization": "Bearer admin-token"}++ assert (+ client.get("/api/auth/profile/learner-profile", headers=headers).status_code+ == 403+ )+ assert (+ client.put(+ "/api/auth/profile/learner-profile", headers=headers, json={"age": 8}+ ).status_code+ == 403+ )+ assert (+ client.get("/api/auth/users/root/learner-profile", headers=headers).status_code+ == 404+ )+ assert set_learner_profile("root", {"age": 8}) is None