From 3784380ecbd7d00a4ebaedace72a715c56dafbfb Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Mon, 30 Nov 2026 16:29:59 +0100 Subject: [PATCH 1/9] feat(users): support exclude_roles in user directory search (#1313) --- .../access/user_directory.py | 4 ++ modules/auth/auth/oidc_common/directory.py | 4 +- .../directory/test_users_directory_filters.py | 58 ++++++++++++++++++- modules/users/users/core/directory.py | 12 +++- 4 files changed, 75 insertions(+), 3 deletions(-) diff --git a/framework/core/simple_module_core/access/user_directory.py b/framework/core/simple_module_core/access/user_directory.py index 927f9332b..7e0e5f361 100644 --- a/framework/core/simple_module_core/access/user_directory.py +++ b/framework/core/simple_module_core/access/user_directory.py @@ -94,6 +94,7 @@ async def search( limit: int, include_ids: Collection[str] | None = None, exclude_ids: Collection[str] = (), + exclude_roles: Collection[str] | None = None, active_only: bool = False, exact_email: bool = False, match_email: bool = True, @@ -101,6 +102,8 @@ async def search( """Users matching *term*, with every filter applied before *limit*. ``include_ids=None`` is unrestricted; an empty collection matches nobody. + ``exclude_roles`` drops users holding any of those role names before + ``limit`` is applied (ignored by providers that do not store roles). ``active_only`` excludes disabled accounts too. ``exact_email`` matches only the complete email (case insensitive), never a name or substring. ``match_email=False`` restricts substring matching to full names, without @@ -157,6 +160,7 @@ async def search( limit: int, include_ids: Collection[str] | None = None, exclude_ids: Collection[str] = (), + exclude_roles: Collection[str] | None = None, active_only: bool = False, exact_email: bool = False, match_email: bool = True, diff --git a/modules/auth/auth/oidc_common/directory.py b/modules/auth/auth/oidc_common/directory.py index 2b3637161..dd2f68636 100644 --- a/modules/auth/auth/oidc_common/directory.py +++ b/modules/auth/auth/oidc_common/directory.py @@ -78,6 +78,7 @@ async def search( limit: int, include_ids: Collection[str] | None = None, exclude_ids: Collection[str] = (), + exclude_roles: Collection[str] | None = None, active_only: bool = False, exact_email: bool = False, match_email: bool = True, @@ -85,7 +86,8 @@ async def search( stmt = select(*self._columns).order_by(self.model.email) if exclude_ids: stmt = stmt.where(self.model.id.not_in(list(parse_user_ids(exclude_ids)))) - # Cache entries represent signed-in users; this provider has no activity flag. + # Cache entries represent signed-in users; this provider has no activity flag + # and keeps roles in the IdP, so ``active_only`` and ``exclude_roles`` are ignored. if exact_email: stmt = stmt.where(func.lower(self.model.email) == (term or "").strip().lower()) elif term and term.strip(): diff --git a/modules/users/tests/core/directory/test_users_directory_filters.py b/modules/users/tests/core/directory/test_users_directory_filters.py index cd477a4df..715bf9433 100644 --- a/modules/users/tests/core/directory/test_users_directory_filters.py +++ b/modules/users/tests/core/directory/test_users_directory_filters.py @@ -8,13 +8,15 @@ import pytest from sqlalchemy import create_engine from users.core.directory import UsersDirectory -from users.models import User +from users.models import Role, User, UserRole @pytest.fixture def directory_db(): engine = create_engine("sqlite://") User.__table__.create(engine) + Role.__table__.create(engine) + UserRole.__table__.create(engine) with engine.connect() as connection: yield SimpleNamespace(execute=AsyncMock(side_effect=connection.execute)), connection engine.dispose() @@ -26,6 +28,18 @@ def insert_user(connection, email, **kwargs): return str(uid) +def insert_role(connection, name: str) -> uuid.UUID: + rid = uuid.uuid4() + connection.execute(Role.__table__.insert().values(id=rid, name=name)) + return rid + + +def assign_role(connection, user_id: str, role_id: uuid.UUID) -> None: + connection.execute( + UserRole.__table__.insert().values(user_id=uuid.UUID(user_id), role_id=role_id) + ) + + async def test_eligible_member_after_200_foreign_matches(directory_db): db, connection = directory_db for n in range(200): @@ -118,3 +132,45 @@ async def test_large_member_filter_chunks_queries_and_keeps_global_limit(directo len(stmt.compile(compile_kwargs={"render_postcompile": True}).params) <= 505 for stmt in statements ) + + +async def test_exclude_roles_filters_before_limit(directory_db): + db, connection = directory_db + guest_role = insert_role(connection, "geowiki_guest") + member_role = insert_role(connection, "member") + bot_role = insert_role(connection, "bot") + + for n in range(5): + guest_id = insert_user( + connection, f"a-demo-guest{n}@example.com", full_name=f"Demo Guest {n}" + ) + assign_role(connection, guest_id, guest_role) + + # A user holding BOTH an excluded role and an allowed role is still excluded. + dual_id = insert_user(connection, "b-demo-dual@example.com", full_name="Demo Dual") + assign_role(connection, dual_id, guest_role) + assign_role(connection, dual_id, member_role) + + bot_id = insert_user(connection, "c-demo-bot@example.com", full_name="Demo Bot") + assign_role(connection, bot_id, bot_role) + + real_member = insert_user(connection, "y-demo-real@example.com", full_name="Demo Member") + assign_role(connection, real_member, member_role) + real_roleless = insert_user(connection, "z-demo-plain@example.com", full_name="Demo Plain") + + directory = UsersDirectory() + + found = await directory.search(db, "demo", limit=2, exclude_roles=["geowiki_guest", "bot"]) + assert [u.id for u in found] == [real_member, real_roleless] + + # Single role exclusion leaves the bot and real users eligible (ordered by email). + found_with_bot = await directory.search(db, "demo", limit=2, exclude_roles=("geowiki_guest",)) + assert [u.id for u in found_with_bot] == [bot_id, real_member] + + # None or empty exclude_roles does not filter out guests. + unfiltered = await directory.search(db, "demo", limit=2, exclude_roles=None) + assert len(unfiltered) == 2 + assert unfiltered[0].email == "a-demo-guest0@example.com" + assert [u.id for u in await directory.search(db, "demo", limit=2, exclude_roles=())] == [ + u.id for u in unfiltered + ] diff --git a/modules/users/users/core/directory.py b/modules/users/users/core/directory.py index 78a42ed81..7bfe2c9d8 100644 --- a/modules/users/users/core/directory.py +++ b/modules/users/users/core/directory.py @@ -27,7 +27,7 @@ search_rows, to_directory_user, ) -from sqlalchemy import String, cast, func, select +from sqlalchemy import String, cast, exists, func, select from users.models import Role, User, UserRole @@ -108,6 +108,7 @@ async def search( limit: int, include_ids: Collection[str] | None = None, exclude_ids: Collection[str] = (), + exclude_roles: Collection[str] | None = None, active_only: bool = False, exact_email: bool = False, match_email: bool = True, @@ -115,6 +116,15 @@ async def search( stmt = select(*_COLUMNS).order_by(User.email) if exclude_ids: stmt = stmt.where(User.id.not_in(list(parse_user_ids(exclude_ids)))) + if exclude_roles: + role_names = [name for name in exclude_roles if name] + if role_names: + excluded_role_subq = ( + select(UserRole.user_id) + .join(Role, Role.id == UserRole.role_id) + .where(UserRole.user_id == User.id, Role.name.in_(role_names)) + ) + stmt = stmt.where(~exists(excluded_role_subq)) if active_only: stmt = stmt.where(User.is_active.is_(True), User.disabled_at.is_(None)) if exact_email: From 2be326807cb8c14793b5078ac5133d4f3e9346b4 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Mon, 30 Nov 2026 16:29:59 +0100 Subject: [PATCH 2/9] fix(users): refresh session user_ctx and enforce full_name validation (#1314, #1315, #1335) --- host_cli/smdev_cli/openapi.json | 15 ++- .../test_users_session_ctx_refresh.py | 91 ++++++++++++++ .../auth_local/api/test_users_me_full_name.py | 115 ++++++++++++++++++ .../contracts/test_full_name_validation.py | 26 ++++ modules/users/users/accounts/provider.py | 5 +- modules/users/users/accounts/session_ctx.py | 30 +++++ modules/users/users/admin/api.py | 8 +- modules/users/users/auth_local/api.py | 7 +- modules/users/users/contracts/schemas.py | 24 ++-- 9 files changed, 297 insertions(+), 24 deletions(-) create mode 100644 modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py create mode 100644 modules/users/tests/auth_local/api/test_users_me_full_name.py create mode 100644 modules/users/users/accounts/session_ctx.py diff --git a/host_cli/smdev_cli/openapi.json b/host_cli/smdev_cli/openapi.json index 7994248be..f44e4632a 100644 --- a/host_cli/smdev_cli/openapi.json +++ b/host_cli/smdev_cli/openapi.json @@ -8227,7 +8227,7 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200 }, { "type": "null" @@ -10021,7 +10021,8 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200, + "minLength": 1 }, { "type": "null" @@ -11703,7 +11704,8 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200, + "minLength": 1 }, { "type": "null" @@ -11816,7 +11818,7 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200 }, { "type": "null" @@ -11850,7 +11852,8 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200, + "minLength": 1 }, { "type": "null" @@ -11873,7 +11876,7 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200 }, { "type": "null" diff --git a/modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py b/modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py new file mode 100644 index 000000000..87ad54e1c --- /dev/null +++ b/modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py @@ -0,0 +1,91 @@ +"""Regression tests: cached session user_ctx refreshes after profile/admin updates (#1314).""" + +from __future__ import annotations + +import uuid + +import pytest +from fastapi_users.password import PasswordHelper +from sqlalchemy import select +from users.models import Role, User, UserRole + +_pw = PasswordHelper() +_INERTIA_HEADERS = {"X-Inertia": "true"} + + +async def _create_user( + session, *, email: str, full_name: str, role_names: list[str] | None = None +) -> User: + user = User( + id=uuid.uuid4(), + email=email, + hashed_password=_pw.hash("SecurePass1!"), + is_active=True, + is_superuser=False, + is_verified=True, + full_name=full_name, + ) + session.add(user) + await session.flush() + if role_names: + roles = ( + (await session.execute(select(Role).where(Role.name.in_(role_names)))).scalars().all() + ) + for role in roles: + session.add(UserRole(user_id=user.id, role_id=role.id)) + await session.commit() + await session.refresh(user) + return user + + +async def _login(client, email: str) -> None: + resp = await client.post( + "/api/users/auth/login", + data={"username": email, "password": "SecurePass1!"}, + ) + assert resp.status_code == 204 + + +@pytest.mark.anyio +async def test_self_update_refreshes_cached_auth_user_name(anon_client, users_db): + await _create_user(users_db, email="alice@example.com", full_name="Old Name") + await _login(anon_client, "alice@example.com") + + # First Inertia request populates session["user_ctx"] with the initial name. + first = await anon_client.get("/users/me", headers=_INERTIA_HEADERS) + assert first.status_code == 200 + assert first.json()["props"]["auth"]["user"]["name"] == "Old Name" + + patch_resp = await anon_client.patch("/api/users/me", json={"full_name": "New Name"}) + assert patch_resp.status_code == 200 + assert patch_resp.json()["full_name"] == "New Name" + + # Next request must re-load from DB and expose the updated name in shared auth props. + second = await anon_client.get("/users/me", headers=_INERTIA_HEADERS) + assert second.status_code == 200 + assert second.json()["props"]["auth"]["user"]["name"] == "New Name" + + +@pytest.mark.anyio +async def test_admin_self_update_refreshes_cached_auth_user(anon_client, users_db): + admin = await _create_user( + users_db, email="admin-self@example.com", full_name="Admin Before", role_names=["admin"] + ) + await _login(anon_client, "admin-self@example.com") + + first = await anon_client.get("/users/me", headers=_INERTIA_HEADERS) + assert first.status_code == 200 + assert first.json()["props"]["auth"]["user"]["name"] == "Admin Before" + assert first.json()["props"]["auth"]["user"]["email"] == "admin-self@example.com" + + patch_resp = await anon_client.patch( + f"/api/users/admin/{admin.id}", + json={"email": "admin-after@example.com", "full_name": "Admin After"}, + ) + assert patch_resp.status_code == 200 + + second = await anon_client.get("/users/me", headers=_INERTIA_HEADERS) + assert second.status_code == 200 + auth_user = second.json()["props"]["auth"]["user"] + assert auth_user["name"] == "Admin After" + assert auth_user["email"] == "admin-after@example.com" diff --git a/modules/users/tests/auth_local/api/test_users_me_full_name.py b/modules/users/tests/auth_local/api/test_users_me_full_name.py new file mode 100644 index 000000000..cd0eb3641 --- /dev/null +++ b/modules/users/tests/auth_local/api/test_users_me_full_name.py @@ -0,0 +1,115 @@ +"""API validation tests for full_name on /api/users/me and /api/users/admin (#1315, #1335).""" + +from __future__ import annotations + +import uuid + +import pytest +from fastapi_users.password import PasswordHelper +from sqlalchemy import select +from users.models import Role, User, UserRole + +_pw = PasswordHelper() + + +async def _create_user( + session, *, email: str, full_name: str, role_names: list[str] | None = None +) -> User: + user = User( + id=uuid.uuid4(), + email=email, + hashed_password=_pw.hash("SecurePass1!"), + is_active=True, + is_superuser=False, + is_verified=True, + full_name=full_name, + ) + session.add(user) + await session.flush() + if role_names: + roles = ( + (await session.execute(select(Role).where(Role.name.in_(role_names)))).scalars().all() + ) + for role in roles: + session.add(UserRole(user_id=user.id, role_id=role.id)) + await session.commit() + await session.refresh(user) + return user + + +async def _login(client, email: str) -> None: + resp = await client.post( + "/api/users/auth/login", + data={"username": email, "password": "SecurePass1!"}, + ) + assert resp.status_code == 204 + + +def _has_full_name_error(resp) -> bool: + detail = resp.json().get("detail", []) + return isinstance(detail, list) and any( + isinstance(item, dict) and item.get("loc") == ["body", "full_name"] for item in detail + ) + + +@pytest.mark.anyio +async def test_patch_me_validates_and_trims_full_name(anon_client, users_db): + await _create_user(users_db, email="me-val@example.com", full_name="Original") + await _login(anon_client, "me-val@example.com") + + for bad in ("", " ", "a" * 201, "a" * 256): + resp = await anon_client.patch("/api/users/me", json={"full_name": bad}) + assert resp.status_code == 422, f"Expected 422 for {bad!r}, got {resp.status_code}" + assert _has_full_name_error(resp) + + # Omitted or null leaves full_name unchanged. + for payload in ({}, {"full_name": None}): + resp = await anon_client.patch("/api/users/me", json=payload) + assert resp.status_code == 200 + assert resp.json()["full_name"] == "Original" + + # Whitespace is stripped. + resp = await anon_client.patch("/api/users/me", json={"full_name": " Trimmed Name "}) + assert resp.status_code == 200 + assert resp.json()["full_name"] == "Trimmed Name" + + # Exactly 200 characters is accepted. + max_name = "x" * 200 + resp = await anon_client.patch("/api/users/me", json={"full_name": max_name}) + assert resp.status_code == 200 + assert resp.json()["full_name"] == max_name + + +@pytest.mark.anyio +async def test_admin_update_and_create_validate_full_name(admin_client, users_db): + target = await _create_user(users_db, email="adm-target@example.com", full_name="Initial") + + for bad in ("", " ", "a" * 201, "a" * 256): + resp = await admin_client.patch(f"/api/users/admin/{target.id}", json={"full_name": bad}) + assert resp.status_code == 422, f"Expected 422 for {bad!r}, got {resp.status_code}" + assert _has_full_name_error(resp) + + create_resp = await admin_client.post( + "/api/users/admin", + json={"email": "new-bad@example.com", "password": "SecurePass1!", "full_name": bad}, + ) + assert create_resp.status_code == 422 + assert _has_full_name_error(create_resp) + + # Null / omitted leaves existing full_name unchanged on update. + for payload in ({}, {"full_name": None}): + resp = await admin_client.patch(f"/api/users/admin/{target.id}", json=payload) + assert resp.status_code == 200 + assert resp.json()["full_name"] == "Initial" + + # Trimmed + 200-char accepted on update. + resp = await admin_client.patch( + f"/api/users/admin/{target.id}", json={"full_name": " Updated Admin "} + ) + assert resp.status_code == 200 + assert resp.json()["full_name"] == "Updated Admin" + + max_name = "y" * 200 + resp = await admin_client.patch(f"/api/users/admin/{target.id}", json={"full_name": max_name}) + assert resp.status_code == 200 + assert resp.json()["full_name"] == max_name diff --git a/modules/users/tests/contracts/test_full_name_validation.py b/modules/users/tests/contracts/test_full_name_validation.py index a06d3452b..201be2457 100644 --- a/modules/users/tests/contracts/test_full_name_validation.py +++ b/modules/users/tests/contracts/test_full_name_validation.py @@ -37,3 +37,29 @@ def test_full_name_enforces_max_length(schema_cls, base_payload): errors = exc_info.value.errors() assert any(e["loc"] == ("full_name",) and e["type"] == "string_too_long" for e in errors) + + +def test_max_full_name_length_is_200(): + assert MAX_FULL_NAME_LENGTH == 200 + + +@pytest.mark.parametrize( + ("schema_cls", "base_payload"), + [ + (SelfProfileUpdate, {}), + (UserUpdate, {}), + (UserAdminCreate, {"email": "a@example.com", "password": "Password1!"}), + (UserDetailsUpdate, {"email": "a@example.com"}), + ], +) +def test_full_name_trims_and_rejects_blank(schema_cls, base_payload): + trimmed = schema_cls(**base_payload, full_name=" Alice Example ") + assert trimmed.full_name == "Alice Example" + + assert schema_cls(**base_payload, full_name=None).full_name is None + + for blank in ("", " ", "\t\n"): + with pytest.raises(ValidationError) as exc_info: + schema_cls(**base_payload, full_name=blank) + errors = exc_info.value.errors() + assert any(e["loc"] == ("full_name",) and e["type"] == "string_too_short" for e in errors) diff --git a/modules/users/users/accounts/provider.py b/modules/users/users/accounts/provider.py index 51bcc9131..929968ce6 100644 --- a/modules/users/users/accounts/provider.py +++ b/modules/users/users/accounts/provider.py @@ -29,6 +29,7 @@ # Re-exported: the cache lives in its own module (see its docstring), but # ``users.accounts.provider`` is where callers reach for it. +from users.accounts.session_ctx import SESSION_USER_CTX_KEY as _SESSION_USER_CTX_KEY from users.accounts.session_version_cache import ( # noqa: F401 SESSION_VERSION_TTL_SECONDS, clear_session_version_cache, @@ -42,10 +43,6 @@ logger = logging.getLogger(__name__) -# Not in ``users.core.constants``: nothing outside this file writes it, and the -# shape it holds is this provider's own caching detail. -_SESSION_USER_CTX_KEY = "user_ctx" - def _stamped_version(session) -> int: """The revocation counter this session was minted under. diff --git a/modules/users/users/accounts/session_ctx.py b/modules/users/users/accounts/session_ctx.py new file mode 100644 index 000000000..c0fdc08af --- /dev/null +++ b/modules/users/users/accounts/session_ctx.py @@ -0,0 +1,30 @@ +"""Browser-session ``UserContext`` cache key and invalidation helper.""" + +from __future__ import annotations + +import uuid as uuid_mod + +from starlette.requests import Request + +from users.core.constants import SESSION_USER_ID_KEY + +SESSION_USER_CTX_KEY = "user_ctx" + + +def invalidate_session_user_ctx( + request: Request, user_id: uuid_mod.UUID | str | None = None +) -> None: + """Drop the cached ``UserContext`` in the current browser session. + + When *user_id* is given, only clears the cache if the session belongs to + that user (so an admin editing another account leaves their own session + cache intact). Safe to call on bearer-only requests with no session. + """ + session = request.scope.get("session") + if isinstance(session, dict) and ( + user_id is None or str(session.get(SESSION_USER_ID_KEY, "")) == str(user_id) + ): + session.pop(SESSION_USER_CTX_KEY, None) + + +__all__ = ["SESSION_USER_CTX_KEY", "invalidate_session_user_ctx"] diff --git a/modules/users/users/admin/api.py b/modules/users/users/admin/api.py index abc58b4fc..1e9cc8e2b 100644 --- a/modules/users/users/admin/api.py +++ b/modules/users/users/admin/api.py @@ -15,6 +15,7 @@ from simple_module_hosting.frontend.pagination import page_params from sqlalchemy.ext.asyncio import AsyncSession +from users.accounts.session_ctx import invalidate_session_user_ctx from users.admin.api_detail import detail_router from users.admin.events import publish_admin_event from users.admin.links import admin_link_base @@ -160,20 +161,19 @@ async def admin_create_user( async def admin_update_user( user_id: uuid.UUID, data: UserDetailsUpdate, + request: Request, service: UserService = Depends(get_user_service), ): """Update a user's email and full name.""" try: user = await service.update_details( - user_id, - data.email, - data.full_name, - update_full_name="full_name" in data.model_fields_set, + user_id, data.email, data.full_name, update_full_name=data.full_name is not None ) except UserNotFoundError: raise HTTPException(status_code=404, detail="User not found") from None except EmailAlreadyExistsError: raise HTTPException(status_code=409, detail=_DUPLICATE_EMAIL) from None + invalidate_session_user_ctx(request, user.id) return service.to_list_item(user) diff --git a/modules/users/users/auth_local/api.py b/modules/users/users/auth_local/api.py index 41701fd3e..43df94ce2 100644 --- a/modules/users/users/auth_local/api.py +++ b/modules/users/users/auth_local/api.py @@ -36,6 +36,7 @@ from users.accounts.backend import cookie_login_response from users.accounts.db_adapter import get_access_token_db from users.accounts.manager import UserManager +from users.accounts.session_ctx import invalidate_session_user_ctx from users.auth_local.browser_guard import require_browser_csrf from users.auth_local.browser_sessions import end_browser_session from users.auth_local.lockout import ( @@ -242,11 +243,13 @@ async def update_me( user_manager: UserManager = Depends(get_user_manager), ): """Update the currently authenticated user's profile.""" - return await user_manager.update( - UserUpdate(**data.model_dump(exclude_unset=True)), # ty: ignore[invalid-argument-type] + updated = await user_manager.update( + UserUpdate(**data.model_dump(exclude_unset=True, exclude_none=True)), # ty: ignore[invalid-argument-type] user, request=request, ) + invalidate_session_user_ctx(request, updated.id) + return updated # ── Self password + session revocation ─────────────────────────────────────── diff --git a/modules/users/users/contracts/schemas.py b/modules/users/users/contracts/schemas.py index 4c44459cd..bc7387ee9 100644 --- a/modules/users/users/contracts/schemas.py +++ b/modules/users/users/contracts/schemas.py @@ -4,9 +4,10 @@ import uuid from datetime import datetime +from typing import Annotated from fastapi_users.schemas import CreateUpdateDictModel -from pydantic import ConfigDict, EmailStr +from pydantic import ConfigDict, EmailStr, StringConstraints from sqlmodel import Field, SQLModel MAX_BULK_INVITE_BODY_ADDRESSES = 1000 @@ -21,11 +22,18 @@ paragraph of context, short enough that it cannot be used to stuff arbitrary content into outbound mail.""" -MAX_FULL_NAME_LENGTH = 255 +MAX_FULL_NAME_LENGTH = 200 """Ceiling on a user's display name across profile, invite and admin forms. -Matches the ``VARCHAR(255)`` column on ``users_user.full_name`` so oversized -inputs fail cleanly with 422 instead of a database truncation error.""" +Shared by client inputs and server schemas (safely inside the ``VARCHAR(255)`` +column on ``users_user.full_name``) so oversized inputs fail cleanly with 422 +instead of a database truncation error.""" + +FullNameStr = Annotated[ + str, + StringConstraints(strip_whitespace=True, min_length=1, max_length=MAX_FULL_NAME_LENGTH), +] +"""Trimmed, non-blank display name up to :data:`MAX_FULL_NAME_LENGTH` chars.""" USER_STATES = ("active", "unverified", "invited", "disabled") """What a row in the users table *is*, as one word. @@ -69,7 +77,7 @@ class UserCreate(CreateUpdateDictModel, SQLModel): class UserUpdate(CreateUpdateDictModel, SQLModel): password: str | None = None email: EmailStr | None = None - full_name: str | None = Field(default=None, max_length=MAX_FULL_NAME_LENGTH) + full_name: FullNameStr | None = None # Admin + invite + self profile @@ -127,13 +135,13 @@ class BulkInviteResponse(SQLModel): class UserAdminCreate(SQLModel): email: EmailStr password: str - full_name: str | None = Field(default=None, max_length=MAX_FULL_NAME_LENGTH) + full_name: FullNameStr | None = None role_names: list[str] = [] class UserDetailsUpdate(SQLModel): email: EmailStr | None = None - full_name: str | None = Field(default=None, max_length=MAX_FULL_NAME_LENGTH) + full_name: FullNameStr | None = None class UserListItem(SQLModel): @@ -197,7 +205,7 @@ class PasswordResetLink(SQLModel): class SelfProfileUpdate(SQLModel): - full_name: str | None = Field(default=None, max_length=MAX_FULL_NAME_LENGTH) + full_name: FullNameStr | None = None class SelfPasswordChange(SQLModel): From 8d3818fc695f8c1f03dec5b4d77838e7dfa91fef Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Mon, 30 Nov 2026 16:29:59 +0100 Subject: [PATCH 3/9] fix(users): use h2 headings on Profile cards and unify full_name maxLength (#1316, #1335) --- .../tests-js/users_profile_headings.test.tsx | 60 +++++++++++++++++++ .../auth_local/components/PasswordCard.tsx | 2 +- .../auth_local/components/PreferencesCard.tsx | 2 +- .../components/ProfileDetailsCard.tsx | 4 +- .../auth_local/components/SessionsCard.tsx | 2 +- modules/users/users/pages/Register.tsx | 1 + .../Users/components/CreateUserFields.tsx | 1 + 7 files changed, 67 insertions(+), 5 deletions(-) create mode 100644 modules/users/tests-js/users_profile_headings.test.tsx diff --git a/modules/users/tests-js/users_profile_headings.test.tsx b/modules/users/tests-js/users_profile_headings.test.tsx new file mode 100644 index 000000000..1f2eb37c5 --- /dev/null +++ b/modules/users/tests-js/users_profile_headings.test.tsx @@ -0,0 +1,60 @@ +import '@testing-library/jest-dom/vitest'; +import { configureI18n, keys } from '@simple-module-py/i18n'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('@inertiajs/react', () => ({ + Head: () => null, + Link: ({ children, href }: { children: React.ReactNode; href: string }) => ( + {children} + ), + usePage: () => ({ + props: { + i18n: { locale: 'en', supportedLocales: ['en', 'de'] }, + }, + }), +})); + +import Profile from '../users/pages/Profile'; + +configureI18n({ + locale: 'en', + messages: { + [keys.users.profile.title]: 'Your profile', + [keys.users.profile.details_title]: 'Details', + [keys.users.profile.password_title]: 'Password', + [keys.users.profile.sessions_title]: 'Sessions', + [keys.users.profile.preferences_title]: 'Preferences', + }, +}); + +describe('Profile heading hierarchy (#1316)', () => { + it('renders h1 page title followed by h2 card headings without skipping levels', () => { + render( + , + ); + + const headings = screen.getAllByRole('heading'); + const levels = headings.map((el) => Number(el.tagName.slice(1))); + + expect(levels[0]).toBe(1); + expect(headings[0]).toHaveTextContent('Your profile'); + + // Every card title is an h2, and no heading jumps more than one level. + expect(levels).toEqual([1, 2, 2, 2, 2]); + expect(headings.slice(1).map((el) => el.textContent)).toEqual([ + 'Details', + 'Password', + 'Sessions', + 'Preferences', + ]); + }); +}); diff --git a/modules/users/users/auth_local/components/PasswordCard.tsx b/modules/users/users/auth_local/components/PasswordCard.tsx index 3ed94b634..15ff31060 100644 --- a/modules/users/users/auth_local/components/PasswordCard.tsx +++ b/modules/users/users/auth_local/components/PasswordCard.tsx @@ -76,7 +76,7 @@ export function PasswordCard() { return ( - {t(keys.users.profile.password_title)} + {t(keys.users.profile.password_title)}
diff --git a/modules/users/users/auth_local/components/PreferencesCard.tsx b/modules/users/users/auth_local/components/PreferencesCard.tsx index f357d507d..f37feb67e 100644 --- a/modules/users/users/auth_local/components/PreferencesCard.tsx +++ b/modules/users/users/auth_local/components/PreferencesCard.tsx @@ -76,7 +76,7 @@ export function PreferencesCard() { return ( - {t(keys.users.profile.preferences_title)} + {t(keys.users.profile.preferences_title)}
{i18n && (
diff --git a/modules/users/users/auth_local/components/ProfileDetailsCard.tsx b/modules/users/users/auth_local/components/ProfileDetailsCard.tsx index 88adf69bd..4472e57fe 100644 --- a/modules/users/users/auth_local/components/ProfileDetailsCard.tsx +++ b/modules/users/users/auth_local/components/ProfileDetailsCard.tsx @@ -61,7 +61,7 @@ export function ProfileDetailsCard({ user }: { user: ProfileUser }) { return ( - {t(keys.users.profile.details_title)} + {t(keys.users.profile.details_title)}
{initials(user.full_name, user.email ?? '')} @@ -89,7 +89,7 @@ export function ProfileDetailsCard({ user }: { user: ProfileUser }) { if (fullNameError) setFullNameError(null); }} placeholder={t(keys.users.common.name_placeholder)} - maxLength={255} + maxLength={200} disabled={saving} aria-invalid={!!fullNameError} aria-describedby={fullNameError ? nameErrorId : undefined} diff --git a/modules/users/users/auth_local/components/SessionsCard.tsx b/modules/users/users/auth_local/components/SessionsCard.tsx index 4516ec387..f3cb4d979 100644 --- a/modules/users/users/auth_local/components/SessionsCard.tsx +++ b/modules/users/users/auth_local/components/SessionsCard.tsx @@ -64,7 +64,7 @@ export function SessionsCard({ lastLoginAt }: Props) { return ( - {t(keys.users.profile.sessions_title)} + {t(keys.users.profile.sessions_title)}
diff --git a/modules/users/users/pages/Users/components/useEditUserForm.ts b/modules/users/users/pages/Users/components/useEditUserForm.ts index ae7a7a6b8..8e23bdcc3 100644 --- a/modules/users/users/pages/Users/components/useEditUserForm.ts +++ b/modules/users/users/pages/Users/components/useEditUserForm.ts @@ -2,7 +2,7 @@ import type { PendingVisit } from '@inertiajs/core'; import { router } from '@inertiajs/react'; import { keys, useT } from '@simple-module-py/i18n'; import { useLeaveGuard } from '@simple-module-py/ui/hooks/useLeaveGuard'; -import { apiResult, NETWORK_FAILURE } from '@simple-module-py/ui/lib/api'; +import { apiResult, type FieldErrors, NETWORK_FAILURE } from '@simple-module-py/ui/lib/api'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { toast } from 'sonner'; import { adminFailureMessage } from '../../../ui/utils/failureMessage'; @@ -54,6 +54,7 @@ export function useEditUserForm(user: EditableUser) { const [baseline, setBaseline] = useState(initial); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); + const [fieldErrors, setFieldErrors] = useState({}); // Re-seed after a server reload, or the form would keep showing pre-save // values against a record that has already moved on. @@ -61,8 +62,17 @@ export function useEditUserForm(user: EditableUser) { setForm(initial); setBaseline(initial); setError(null); + setFieldErrors({}); }, [initial]); + const clearFieldError = useCallback((field: string) => { + setFieldErrors((prev) => { + if (!(field in prev)) return prev; + const { [field]: _, ...rest } = prev; + return rest; + }); + }, []); + const emailDirty = form.email !== baseline.email; const nameDirty = form.fullName !== baseline.fullName; const rolesDirty = !sameRoles(form.roles, baseline.roles); @@ -114,6 +124,7 @@ export function useEditUserForm(user: EditableUser) { async function save() { setSaving(true); setError(null); + setFieldErrors({}); savingRef.current = true; try { // Only the parts that changed — sending roles untouched would rewrite @@ -129,19 +140,23 @@ export function useEditUserForm(user: EditableUser) { params: { path: { user_id: user.id } }, body: { ...(form.email !== baseline.email ? { email: form.email } : {}), - ...(form.fullName !== baseline.fullName ? { full_name: form.fullName || null } : {}), + ...(form.fullName !== baseline.fullName ? { full_name: form.fullName } : {}), }, }), ); if (!resp.ok) { - setError( - adminFailureMessage( - resp, - t(keys.users.edit.error_details), - t(keys.users.common.error_occurred), - t, - ), - ); + const nextFieldErrors = resp.fieldErrors ?? {}; + setFieldErrors(nextFieldErrors); + if (!nextFieldErrors.email && !nextFieldErrors.full_name) { + setError( + adminFailureMessage( + resp, + t(keys.users.edit.error_details), + t(keys.users.common.error_occurred), + t, + ), + ); + } return; } setBaseline((prev) => ({ ...prev, email: form.email, fullName: form.fullName })); @@ -183,8 +198,14 @@ export function useEditUserForm(user: EditableUser) { dirtyCount, saving, error, + fieldErrors, + clearFieldError, toggleRole, save, - discard: () => setForm(baseline), + discard: () => { + setForm(baseline); + setError(null); + setFieldErrors({}); + }, }; } From 8eb60c5eb9c71fd3bdcfdfdea7ae8bfb9025f2fa Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Mon, 30 Nov 2026 16:29:59 +0100 Subject: [PATCH 5/9] docs(changelog): document users directory and profile fixes (#1313, #1314, #1315, #1316, #1335, #1337) --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95b2ec4ce..3bf403fbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ All notable changes to this project are documented in this file. The format is b - Branding / Users / UI: let apps brand the stock login page without overriding it — add optional `login_heading` and `login_tagline` fields to `BrandingSettings` (shared as `branding.loginHeading` / `branding.loginTagline` and editable at `/admin/branding` and per tenant), add a `LoginAside` layout override on `LayoutComponents` (`registry.registerLayout('LoginAside', ...)`), and export `LoginForm`, `WaitingOnYou`, `DemoSignIn`, `useLoginState`, and `signIn` from `@simple-module-py/users/ui` (`modules/users/users/ui/index.ts`) (#1340). - Hosting: `HostSettings.logout_redirect_url` (`SM_LOGOUT_REDIRECT_URL`, blank by default) configures the post-logout destination for local Users sign-out; when unset, `logout_redirect_url(app)` redirects to `/` if the host serves a root route and falls back to `/users/login` otherwise (#1330). - Users / Docs: document the app upgrade workflow across framework versions and the schema changes Alembic autogenerate misses (partial/expression indexes such as `ix_users_user_email_lower` gaining `WHERE email IS NOT NULL`, and pre-migration uniqueness checks), and export reusable Alembic helpers `check_unique_oauth_identities(op)` and `recreate_user_email_lower_index(op, *, partial=True)` from `users.contracts.migrations` (#1333). +- Users / Core: `UserDirectory.search(..., exclude_roles=...)` (implemented in SQL via `NOT EXISTS` in `UsersDirectory.search` before `LIMIT` is applied, and accepted by `NullUserDirectory` and `CacheDirectory`) lets callers exclude users holding specified roles without post-limit filtering (#1313). ### Changed @@ -43,6 +44,10 @@ All notable changes to this project are documented in this file. The format is b - UI / CLI scaffold: `--font-display` now falls back to `"DM Sans"` before system fonts, and the scaffolded `templates/index.html` now loads `Sora` and `JetBrains Mono` alongside `DM Sans` and sets `` (#1330). - i18n: `configureI18n` and `updateI18n` now synchronize `document.documentElement.lang` with the active locale on boot and Inertia locale switches (#1330). - Users: `POST /users/logout` now uses `logout_redirect_url(app)` so hosts without a `/` route do not 404 after sign-out, and `GET /users/login` redirects already signed-in users (unless displaying a recognized `oauth_error`) in `?next=` → saved session destination → `login_redirect_url` order, guarding against self-redirects and falling back to `/users/me` when the host default resolves to `/` without a root route (#1330). +- Users: invalidate the cached browser-session `user_ctx` on `PATCH /api/users/me` and on `PATCH /api/users/admin/{user_id}` when editing the currently signed-in user, so shared `auth.user` props reflect updated name and email on the next request (#1314). +- Users: unify `MAX_FULL_NAME_LENGTH` to 200 characters across server schemas and client inputs, trim leading/trailing whitespace, and reject blank, whitespace-only, or over-limit `full_name` values with 422 field errors instead of storing blank strings or returning 500 (#1315, #1335). +- Users: render Profile page card titles (`Details`, `Password`, `Sessions`, `Preferences`) as `

` headings under the `

` page title so the heading hierarchy no longer skips a level (#1316). +- Users: display inline 422 field validation errors for `email` and `full_name` on the admin user edit Details card instead of collapsing them into a generic failure banner (#1337). ## [0.0.51] — 2026-11-29 From dfed40f534eefb876ca7fb9f81702ca50ef9e393 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Mon, 30 Nov 2026 17:07:59 +0100 Subject: [PATCH 6/9] fix: address code review findings (round 1, pass 1) --- CHANGELOG.md | 2 +- docs/framework/user-directory.md | 2 +- host_cli/smdev_cli/openapi.json | 6 +- .../users_details_card_errors.test.tsx | 52 ++++++-- modules/users/tests/_users_admin_support.py | 18 ++- .../test_users_session_ctx_refresh.py | 46 +------ .../auth_local/api/test_users_me_full_name.py | 121 ++++++++++-------- .../contracts/test_full_name_validation.py | 2 + modules/users/users/admin/api.py | 3 +- modules/users/users/auth_local/api.py | 2 +- modules/users/users/contracts/schemas.py | 4 +- modules/users/users/pages/AcceptInvite.tsx | 17 ++- modules/users/users/pages/Register.tsx | 2 +- modules/users/users/pages/Users/Edit.tsx | 11 +- .../pages/Users/components/DetailsCard.tsx | 21 +-- .../pages/Users/components/useEditUserForm.ts | 39 +++++- 16 files changed, 209 insertions(+), 139 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bf403fbb..65da9a63d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,7 +45,7 @@ All notable changes to this project are documented in this file. The format is b - i18n: `configureI18n` and `updateI18n` now synchronize `document.documentElement.lang` with the active locale on boot and Inertia locale switches (#1330). - Users: `POST /users/logout` now uses `logout_redirect_url(app)` so hosts without a `/` route do not 404 after sign-out, and `GET /users/login` redirects already signed-in users (unless displaying a recognized `oauth_error`) in `?next=` → saved session destination → `login_redirect_url` order, guarding against self-redirects and falling back to `/users/me` when the host default resolves to `/` without a root route (#1330). - Users: invalidate the cached browser-session `user_ctx` on `PATCH /api/users/me` and on `PATCH /api/users/admin/{user_id}` when editing the currently signed-in user, so shared `auth.user` props reflect updated name and email on the next request (#1314). -- Users: unify `MAX_FULL_NAME_LENGTH` to 200 characters across server schemas and client inputs, trim leading/trailing whitespace, and reject blank, whitespace-only, or over-limit `full_name` values with 422 field errors instead of storing blank strings or returning 500 (#1315, #1335). +- Users: unify `MAX_FULL_NAME_LENGTH` to 200 characters across server schemas and client inputs, trim leading/trailing whitespace, and reject blank, whitespace-only, or over-limit `full_name` values with 422 field errors instead of storing blank strings or returning 500 (`AcceptInviteRequest` keeps the admin-supplied pre-filled name when left blank) (#1315, #1335). - Users: render Profile page card titles (`Details`, `Password`, `Sessions`, `Preferences`) as `

` headings under the `

` page title so the heading hierarchy no longer skips a level (#1316). - Users: display inline 422 field validation errors for `email` and `full_name` on the admin user edit Details card instead of collapsing them into a generic failure banner (#1337). diff --git a/docs/framework/user-directory.md b/docs/framework/user-directory.md index b3c2bc7f9..a08a31b85 100644 --- a/docs/framework/user-directory.md +++ b/docs/framework/user-directory.md @@ -20,7 +20,7 @@ found = await directory.get_many(db, ["3f0c…", "celery-worker"]) # {id: Direc | Member | Returns | |---|---| | `get_many(db, ids, *, with_roles=False)` | `{id: DirectoryUser}` keyed by **your** id strings. Ids that are not uuids or name nobody are absent, never an error. Implementations chunk (`GET_MANY_CHUNK`, 500 ids per query). | -| `search(db, term, *, limit, include_ids=None, exclude_ids=(), active_only=False, exact_email=False, match_email=True)` | Users ordered by email. Filters apply before the limit: optional allowed ids, excluded ids, usable accounts only, or exact case-insensitive email instead of name/email substring. `match_email=False` searches full names only. Defaults keep the unrestricted search. | +| `search(db, term, *, limit, include_ids=None, exclude_ids=(), exclude_roles=None, active_only=False, exact_email=False, match_email=True)` | Users ordered by email. Filters apply before the limit: optional allowed ids, excluded ids, excluded role names (applied in SQL by the local `users` provider; ignored by OIDC/Keycloak caches, which do not store roles), usable accounts only, or exact case-insensitive email instead of name/email substring. `match_email=False` searches full names only. Defaults keep the unrestricted search. | | `find_by_email(db, email)` | One `DirectoryUser` or `None`, using a case-insensitive exact email match. Available on every built-in directory through the optional `EmailLookupUserDirectory` protocol. | | `match_ids(term)` | An **unexecuted** `SELECT` of the matching text ids, for use as an unbounded subquery (the audit log's Actor filter). `None` when the provider cannot express it. | | `stats(db, *, active_window)` | `DirectoryStats(total, active_since, created_this_month)`; a `None` field means "cannot say", not zero. | diff --git a/host_cli/smdev_cli/openapi.json b/host_cli/smdev_cli/openapi.json index f44e4632a..40dd1a5ba 100644 --- a/host_cli/smdev_cli/openapi.json +++ b/host_cli/smdev_cli/openapi.json @@ -11818,7 +11818,8 @@ "anyOf": [ { "type": "string", - "maxLength": 200 + "maxLength": 200, + "minLength": 1 }, { "type": "null" @@ -11876,7 +11877,8 @@ "anyOf": [ { "type": "string", - "maxLength": 200 + "maxLength": 200, + "minLength": 1 }, { "type": "null" diff --git a/modules/users/tests-js/users_details_card_errors.test.tsx b/modules/users/tests-js/users_details_card_errors.test.tsx index de7a0205c..a306305ff 100644 --- a/modules/users/tests-js/users_details_card_errors.test.tsx +++ b/modules/users/tests-js/users_details_card_errors.test.tsx @@ -1,6 +1,6 @@ import '@testing-library/jest-dom/vitest'; import { configureI18n, keys } from '@simple-module-py/i18n'; -import { fireEvent, render, screen } from '@testing-library/react'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; vi.mock('@inertiajs/react', () => ({ @@ -46,19 +46,14 @@ function DetailsHarness() { { - form.setForm((prev) => ({ ...prev, email })); - form.clearFieldError('email'); - }} - onFullNameChange={(fullName) => { - form.setForm((prev) => ({ ...prev, fullName })); - form.clearFieldError('full_name'); - }} + onEmailChange={form.setEmail} + onFullNameChange={form.setFullName} roles={[]} selectedRoles={form.form.roles} onToggleRole={form.toggleRole} userId="u1" hasPermissionsModule={false} + disabled={form.saving} error={form.error} fieldErrors={form.fieldErrors} /> @@ -138,4 +133,43 @@ describe('Admin DetailsCard 422 inline field errors (#1337)', () => { const req = fetchMock.mock.calls[0]?.[0] as Request; expect(await req.clone().json()).toEqual({ full_name: '' }); }); + + it('ignores stale 422 field errors if the field changed while save was in flight', async () => { + let resolveResp: ((res: Response) => void) | undefined; + const fetchMock = stubFetch( + () => + new Promise((resolve) => { + resolveResp = resolve; + }), + ); + + render(); + const emailInput = screen.getByLabelText('Email'); + + fireEvent.change(emailInput, { target: { value: 'bad@' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(emailInput).toBeDisabled(); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + + // Simulate a programmatic/in-flight value change before the 422 settles. + fireEvent.change(emailInput, { target: { value: 'fixed@example.com' } }); + + await act(async () => { + resolveResp?.( + json(422, { + detail: [ + { + loc: ['body', 'email'], + msg: 'value is not a valid email address', + type: 'value_error', + }, + ], + }), + ); + }); + + await waitFor(() => expect(emailInput).not.toBeDisabled()); + expect(emailInput).toHaveAttribute('aria-invalid', 'false'); + expect(screen.queryAllByRole('alert')).toHaveLength(0); + }); }); diff --git a/modules/users/tests/_users_admin_support.py b/modules/users/tests/_users_admin_support.py index 4333960ef..f70841699 100644 --- a/modules/users/tests/_users_admin_support.py +++ b/modules/users/tests/_users_admin_support.py @@ -10,7 +10,14 @@ _pw = PasswordHelper() -async def _make_user(session, email, password="SecurePass1!", verified=True, role_names=None): +async def _make_user( + session, + email, + password="SecurePass1!", + verified=True, + role_names=None, + full_name: str | None = None, +): from sqlalchemy import select user = User( @@ -20,6 +27,7 @@ async def _make_user(session, email, password="SecurePass1!", verified=True, rol is_active=True, is_superuser=False, is_verified=verified, + full_name=full_name, ) session.add(user) await session.flush() @@ -36,6 +44,14 @@ async def _make_user(session, email, password="SecurePass1!", verified=True, rol return user +async def _login(client, email: str, password: str = "SecurePass1!") -> None: + resp = await client.post( + "/api/users/auth/login", + data={"username": email, "password": password}, + ) + assert resp.status_code == 204 + + def _build_service(session, users_app_empty): """Build a UserService directly (bypass FastAPI Depends).""" from users.accounts.db_adapter import UserDatabaseWithRoles diff --git a/modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py b/modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py index 87ad54e1c..83923e3ae 100644 --- a/modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py +++ b/modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py @@ -2,53 +2,15 @@ from __future__ import annotations -import uuid - import pytest -from fastapi_users.password import PasswordHelper -from sqlalchemy import select -from users.models import Role, User, UserRole +from _users_admin_support import _login, _make_user -_pw = PasswordHelper() _INERTIA_HEADERS = {"X-Inertia": "true"} -async def _create_user( - session, *, email: str, full_name: str, role_names: list[str] | None = None -) -> User: - user = User( - id=uuid.uuid4(), - email=email, - hashed_password=_pw.hash("SecurePass1!"), - is_active=True, - is_superuser=False, - is_verified=True, - full_name=full_name, - ) - session.add(user) - await session.flush() - if role_names: - roles = ( - (await session.execute(select(Role).where(Role.name.in_(role_names)))).scalars().all() - ) - for role in roles: - session.add(UserRole(user_id=user.id, role_id=role.id)) - await session.commit() - await session.refresh(user) - return user - - -async def _login(client, email: str) -> None: - resp = await client.post( - "/api/users/auth/login", - data={"username": email, "password": "SecurePass1!"}, - ) - assert resp.status_code == 204 - - @pytest.mark.anyio async def test_self_update_refreshes_cached_auth_user_name(anon_client, users_db): - await _create_user(users_db, email="alice@example.com", full_name="Old Name") + await _make_user(users_db, "alice@example.com", full_name="Old Name") await _login(anon_client, "alice@example.com") # First Inertia request populates session["user_ctx"] with the initial name. @@ -68,8 +30,8 @@ async def test_self_update_refreshes_cached_auth_user_name(anon_client, users_db @pytest.mark.anyio async def test_admin_self_update_refreshes_cached_auth_user(anon_client, users_db): - admin = await _create_user( - users_db, email="admin-self@example.com", full_name="Admin Before", role_names=["admin"] + admin = await _make_user( + users_db, "admin-self@example.com", full_name="Admin Before", role_names=["admin"] ) await _login(anon_client, "admin-self@example.com") diff --git a/modules/users/tests/auth_local/api/test_users_me_full_name.py b/modules/users/tests/auth_local/api/test_users_me_full_name.py index cd0eb3641..a5c0bc2f9 100644 --- a/modules/users/tests/auth_local/api/test_users_me_full_name.py +++ b/modules/users/tests/auth_local/api/test_users_me_full_name.py @@ -1,48 +1,9 @@ -"""API validation tests for full_name on /api/users/me and /api/users/admin (#1315, #1335).""" +"""API validation tests for full_name across users endpoints (#1315, #1335).""" from __future__ import annotations -import uuid - import pytest -from fastapi_users.password import PasswordHelper -from sqlalchemy import select -from users.models import Role, User, UserRole - -_pw = PasswordHelper() - - -async def _create_user( - session, *, email: str, full_name: str, role_names: list[str] | None = None -) -> User: - user = User( - id=uuid.uuid4(), - email=email, - hashed_password=_pw.hash("SecurePass1!"), - is_active=True, - is_superuser=False, - is_verified=True, - full_name=full_name, - ) - session.add(user) - await session.flush() - if role_names: - roles = ( - (await session.execute(select(Role).where(Role.name.in_(role_names)))).scalars().all() - ) - for role in roles: - session.add(UserRole(user_id=user.id, role_id=role.id)) - await session.commit() - await session.refresh(user) - return user - - -async def _login(client, email: str) -> None: - resp = await client.post( - "/api/users/auth/login", - data={"username": email, "password": "SecurePass1!"}, - ) - assert resp.status_code == 204 +from _users_admin_support import _login, _make_user def _has_full_name_error(resp) -> bool: @@ -54,7 +15,7 @@ def _has_full_name_error(resp) -> bool: @pytest.mark.anyio async def test_patch_me_validates_and_trims_full_name(anon_client, users_db): - await _create_user(users_db, email="me-val@example.com", full_name="Original") + await _make_user(users_db, "me-val@example.com", full_name="Original") await _login(anon_client, "me-val@example.com") for bad in ("", " ", "a" * 201, "a" * 256): @@ -62,11 +23,15 @@ async def test_patch_me_validates_and_trims_full_name(anon_client, users_db): assert resp.status_code == 422, f"Expected 422 for {bad!r}, got {resp.status_code}" assert _has_full_name_error(resp) - # Omitted or null leaves full_name unchanged. - for payload in ({}, {"full_name": None}): - resp = await anon_client.patch("/api/users/me", json=payload) - assert resp.status_code == 200 - assert resp.json()["full_name"] == "Original" + # Omitted leaves full_name unchanged. + resp = await anon_client.patch("/api/users/me", json={}) + assert resp.status_code == 200 + assert resp.json()["full_name"] == "Original" + + # Explicit null clears full_name. + resp = await anon_client.patch("/api/users/me", json={"full_name": None}) + assert resp.status_code == 200 + assert resp.json()["full_name"] is None # Whitespace is stripped. resp = await anon_client.patch("/api/users/me", json={"full_name": " Trimmed Name "}) @@ -82,7 +47,7 @@ async def test_patch_me_validates_and_trims_full_name(anon_client, users_db): @pytest.mark.anyio async def test_admin_update_and_create_validate_full_name(admin_client, users_db): - target = await _create_user(users_db, email="adm-target@example.com", full_name="Initial") + target = await _make_user(users_db, "adm-target@example.com", full_name="Initial") for bad in ("", " ", "a" * 201, "a" * 256): resp = await admin_client.patch(f"/api/users/admin/{target.id}", json={"full_name": bad}) @@ -96,11 +61,22 @@ async def test_admin_update_and_create_validate_full_name(admin_client, users_db assert create_resp.status_code == 422 assert _has_full_name_error(create_resp) - # Null / omitted leaves existing full_name unchanged on update. - for payload in ({}, {"full_name": None}): - resp = await admin_client.patch(f"/api/users/admin/{target.id}", json=payload) - assert resp.status_code == 200 - assert resp.json()["full_name"] == "Initial" + invite_resp = await admin_client.post( + "/api/users/admin/invite", + json={"email": "inv-bad@example.com", "full_name": bad}, + ) + assert invite_resp.status_code == 422 + assert _has_full_name_error(invite_resp) + + # Omitted leaves existing full_name unchanged on update. + resp = await admin_client.patch(f"/api/users/admin/{target.id}", json={}) + assert resp.status_code == 200 + assert resp.json()["full_name"] == "Initial" + + # Explicit null clears full_name on update. + resp = await admin_client.patch(f"/api/users/admin/{target.id}", json={"full_name": None}) + assert resp.status_code == 200 + assert resp.json()["full_name"] is None # Trimmed + 200-char accepted on update. resp = await admin_client.patch( @@ -113,3 +89,42 @@ async def test_admin_update_and_create_validate_full_name(admin_client, users_db resp = await admin_client.patch(f"/api/users/admin/{target.id}", json={"full_name": max_name}) assert resp.status_code == 200 assert resp.json()["full_name"] == max_name + + # Invite trims padded full_name. + invite_ok = await admin_client.post( + "/api/users/admin/invite", + json={"email": "inv-trim@example.com", "full_name": " Invited Person "}, + ) + assert invite_ok.status_code == 201 + assert invite_ok.json()["full_name"] == "Invited Person" + + +@pytest.mark.anyio +async def test_register_validates_and_trims_full_name(anon_client, users_app): + users_app.state.users.settings.allow_signup = True + + for bad in ("", " ", "a" * 201): + resp = await anon_client.post( + "/api/users/auth/register", + json={"email": "reg-bad@example.com", "password": "SecurePass1!", "full_name": bad}, + ) + assert resp.status_code == 422 + assert _has_full_name_error(resp) + + omitted = await anon_client.post( + "/api/users/auth/register", + json={"email": "reg-omit@example.com", "password": "SecurePass1!"}, + ) + assert omitted.status_code == 201 + assert omitted.json()["full_name"] is None + + trimmed = await anon_client.post( + "/api/users/auth/register", + json={ + "email": "reg-trim@example.com", + "password": "SecurePass1!", + "full_name": " Reg User ", + }, + ) + assert trimmed.status_code == 201 + assert trimmed.json()["full_name"] == "Reg User" diff --git a/modules/users/tests/contracts/test_full_name_validation.py b/modules/users/tests/contracts/test_full_name_validation.py index 201be2457..0909cc4af 100644 --- a/modules/users/tests/contracts/test_full_name_validation.py +++ b/modules/users/tests/contracts/test_full_name_validation.py @@ -48,6 +48,8 @@ def test_max_full_name_length_is_200(): [ (SelfProfileUpdate, {}), (UserUpdate, {}), + (UserCreate, {"email": "a@example.com", "password": "Password1!"}), + (UserInvite, {"email": "a@example.com"}), (UserAdminCreate, {"email": "a@example.com", "password": "Password1!"}), (UserDetailsUpdate, {"email": "a@example.com"}), ], diff --git a/modules/users/users/admin/api.py b/modules/users/users/admin/api.py index 1e9cc8e2b..2d2f23d5c 100644 --- a/modules/users/users/admin/api.py +++ b/modules/users/users/admin/api.py @@ -166,8 +166,9 @@ async def admin_update_user( ): """Update a user's email and full name.""" try: + has_name = "full_name" in data.model_fields_set user = await service.update_details( - user_id, data.email, data.full_name, update_full_name=data.full_name is not None + user_id, data.email, data.full_name, update_full_name=has_name ) except UserNotFoundError: raise HTTPException(status_code=404, detail="User not found") from None diff --git a/modules/users/users/auth_local/api.py b/modules/users/users/auth_local/api.py index 43df94ce2..29573f2bb 100644 --- a/modules/users/users/auth_local/api.py +++ b/modules/users/users/auth_local/api.py @@ -244,7 +244,7 @@ async def update_me( ): """Update the currently authenticated user's profile.""" updated = await user_manager.update( - UserUpdate(**data.model_dump(exclude_unset=True, exclude_none=True)), # ty: ignore[invalid-argument-type] + UserUpdate(**data.model_dump(exclude_unset=True)), # ty: ignore[invalid-argument-type] user, request=request, ) diff --git a/modules/users/users/contracts/schemas.py b/modules/users/users/contracts/schemas.py index bc7387ee9..83fb3050c 100644 --- a/modules/users/users/contracts/schemas.py +++ b/modules/users/users/contracts/schemas.py @@ -71,7 +71,7 @@ class UserCreate(CreateUpdateDictModel, SQLModel): is_active: bool | None = True is_superuser: bool | None = False is_verified: bool | None = False - full_name: str | None = Field(default=None, max_length=MAX_FULL_NAME_LENGTH) + full_name: FullNameStr | None = None class UserUpdate(CreateUpdateDictModel, SQLModel): @@ -83,7 +83,7 @@ class UserUpdate(CreateUpdateDictModel, SQLModel): # Admin + invite + self profile class UserInvite(SQLModel): email: EmailStr - full_name: str | None = Field(default=None, max_length=MAX_FULL_NAME_LENGTH) + full_name: FullNameStr | None = None role_names: list[str] = [] diff --git a/modules/users/users/pages/AcceptInvite.tsx b/modules/users/users/pages/AcceptInvite.tsx index 73017996a..0ecf4650f 100644 --- a/modules/users/users/pages/AcceptInvite.tsx +++ b/modules/users/users/pages/AcceptInvite.tsx @@ -41,11 +41,13 @@ function AcceptInvite({ token, invite, branding }: Props) { const [confirm, setConfirm] = useState(''); const [mismatch, setMismatch] = useState(false); const [error, setError] = useState(null); + const [fullNameError, setFullNameError] = useState(null); const [loading, setLoading] = useState(false); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); setError(null); + setFullNameError(null); if (password !== confirm) { setMismatch(true); return; @@ -69,6 +71,8 @@ function AcceptInvite({ token, invite, branding }: Props) { router.visit(homeUrl); } else if (res.detail === 'INVITE_BAD_TOKEN') { setError(t(keys.users.accept_invite.error_bad_token)); + } else if (res.fieldErrors.full_name) { + setFullNameError(res.fieldErrors.full_name); } else { setError(res.detail || t(keys.users.accept_invite.error_failed)); } @@ -118,14 +122,23 @@ function AcceptInvite({ token, invite, branding }: Props) { {t(keys.users.accept_invite.heading)}

- + setFullName(e.target.value)} + onChange={(e) => { + setFullName(e.target.value); + if (fullNameError) setFullNameError(null); + }} placeholder={t(keys.users.common.name_placeholder)} + maxLength={200} autoComplete="name" + aria-invalid={!!fullNameError} /> { if (res.status === 201) { diff --git a/modules/users/users/pages/Users/Edit.tsx b/modules/users/users/pages/Users/Edit.tsx index 9f93a6cb5..ebb85b0c8 100644 --- a/modules/users/users/pages/Users/Edit.tsx +++ b/modules/users/users/pages/Users/Edit.tsx @@ -106,19 +106,14 @@ function Edit({ { - form.setForm((prev) => ({ ...prev, email })); - form.clearFieldError('email'); - }} - onFullNameChange={(fullName) => { - form.setForm((prev) => ({ ...prev, fullName })); - form.clearFieldError('full_name'); - }} + onEmailChange={form.setEmail} + onFullNameChange={form.setFullName} roles={roles} selectedRoles={form.form.roles} onToggleRole={form.toggleRole} userId={user.id} hasPermissionsModule={has_permissions_module} + disabled={form.saving} error={form.error} fieldErrors={form.fieldErrors} /> diff --git a/modules/users/users/pages/Users/components/DetailsCard.tsx b/modules/users/users/pages/Users/components/DetailsCard.tsx index fbef0f9fd..fc7bedf8a 100644 --- a/modules/users/users/pages/Users/components/DetailsCard.tsx +++ b/modules/users/users/pages/Users/components/DetailsCard.tsx @@ -2,6 +2,7 @@ import { Link } from '@inertiajs/react'; import { keys, useT } from '@simple-module-py/i18n'; import { SectionTitle } from '@simple-module-py/ui/components/SectionTitle'; import { Card, CardContent } from '@simple-module-py/ui/components/ui/card'; +import { FieldError } from '@simple-module-py/ui/components/ui/field'; import { Input } from '@simple-module-py/ui/components/ui/input'; import { Label } from '@simple-module-py/ui/components/ui/label'; import type { FieldErrors } from '@simple-module-py/ui/lib/api'; @@ -19,6 +20,7 @@ interface Props { onToggleRole: (roleName: string) => void; userId: string; hasPermissionsModule: boolean; + disabled?: boolean; error?: string | null; fieldErrors?: FieldErrors; } @@ -40,6 +42,7 @@ export function DetailsCard({ onToggleRole, userId, hasPermissionsModule, + disabled, error, fieldErrors, }: Props) { @@ -65,14 +68,13 @@ export function DetailsCard({ onChange={(e) => onFullNameChange(e.target.value)} placeholder={t(keys.users.details_card.name_placeholder)} maxLength={200} + disabled={disabled} aria-invalid={!!fullNameError} aria-describedby={fullNameError ? nameErrorId : undefined} /> - {fullNameError && ( - - )} + + {fullNameError} +

diff --git a/modules/users/users/pages/Users/components/useEditUserForm.ts b/modules/users/users/pages/Users/components/useEditUserForm.ts index 8e23bdcc3..b21f3f8d7 100644 --- a/modules/users/users/pages/Users/components/useEditUserForm.ts +++ b/modules/users/users/pages/Users/components/useEditUserForm.ts @@ -48,6 +48,8 @@ export function useEditUserForm(user: EditableUser) { ); const [form, setForm] = useState(initial); + const formRef = useRef(form); + formRef.current = form; // What is currently persisted. Starts at the server's values and advances // per section as each save lands, so "unsaved changes" stays truthful even // when only part of a save succeeded. @@ -73,6 +75,22 @@ export function useEditUserForm(user: EditableUser) { }); }, []); + const setEmail = useCallback( + (email: string) => { + setForm((prev) => ({ ...prev, email })); + clearFieldError('email'); + }, + [clearFieldError], + ); + + const setFullName = useCallback( + (fullName: string) => { + setForm((prev) => ({ ...prev, fullName })); + clearFieldError('full_name'); + }, + [clearFieldError], + ); + const emailDirty = form.email !== baseline.email; const nameDirty = form.fullName !== baseline.fullName; const rolesDirty = !sameRoles(form.roles, baseline.roles); @@ -135,19 +153,28 @@ export function useEditUserForm(user: EditableUser) { // "unsaved" — it is already persisted, and saying otherwise invites the // admin to redo work or distrust the indicator entirely. if (detailsDirty) { + const submittedEmail = form.email; + const submittedFullName = form.fullName; const resp = await apiResult( api.PATCH('/api/users/admin/{user_id}', { params: { path: { user_id: user.id } }, body: { - ...(form.email !== baseline.email ? { email: form.email } : {}), - ...(form.fullName !== baseline.fullName ? { full_name: form.fullName } : {}), + ...(emailDirty ? { email: submittedEmail } : {}), + ...(nameDirty ? { full_name: submittedFullName } : {}), }, }), ); if (!resp.ok) { - const nextFieldErrors = resp.fieldErrors ?? {}; + const { fieldErrors: rawFieldErrors } = resp; + const nextFieldErrors: FieldErrors = {}; + if (rawFieldErrors.email && formRef.current.email === submittedEmail) { + nextFieldErrors.email = rawFieldErrors.email; + } + if (rawFieldErrors.full_name && formRef.current.fullName === submittedFullName) { + nextFieldErrors.full_name = rawFieldErrors.full_name; + } setFieldErrors(nextFieldErrors); - if (!nextFieldErrors.email && !nextFieldErrors.full_name) { + if (!rawFieldErrors.email && !rawFieldErrors.full_name) { setError( adminFailureMessage( resp, @@ -159,7 +186,7 @@ export function useEditUserForm(user: EditableUser) { } return; } - setBaseline((prev) => ({ ...prev, email: form.email, fullName: form.fullName })); + setBaseline((prev) => ({ ...prev, email: submittedEmail, fullName: submittedFullName })); } if (rolesDirty) { const resp = await apiResult( @@ -195,6 +222,8 @@ export function useEditUserForm(user: EditableUser) { return { form, setForm, + setEmail, + setFullName, dirtyCount, saving, error, From a5a00fd9e801ef78a47a551971268a3319c156b4 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Mon, 30 Nov 2026 17:11:22 +0100 Subject: [PATCH 7/9] fix: address code review findings (round 1, pass 2) --- .../tests-js/users_admin_error_details.test.tsx | 2 +- .../tests-js/users_details_card_errors.test.tsx | 15 +++++++++++++++ .../tests/contracts/test_full_name_validation.py | 8 ++++++++ .../users/auth_local/components/AuthField.tsx | 10 ++++++++-- modules/users/users/contracts/schemas.py | 5 ++++- modules/users/users/core/directory.py | 14 ++++++-------- modules/users/users/pages/AcceptInvite.tsx | 4 ++++ .../pages/Users/components/useEditUserForm.ts | 8 +++++--- 8 files changed, 51 insertions(+), 15 deletions(-) diff --git a/modules/users/tests-js/users_admin_error_details.test.tsx b/modules/users/tests-js/users_admin_error_details.test.tsx index 34a18394d..aaf273395 100644 --- a/modules/users/tests-js/users_admin_error_details.test.tsx +++ b/modules/users/tests-js/users_admin_error_details.test.tsx @@ -66,7 +66,7 @@ describe.each(['en', 'de'])('users admin errors (%s)', (locale) => { const { result } = renderHook(() => useEditUserForm(user)); act(() => { result.current.toggleRole('Admin'); - if (detailsDirty) result.current.setForm((prev) => ({ ...prev, fullName: 'New name' })); + if (detailsDirty) result.current.setFullName('New name'); }); await act(async () => result.current.save()); const reason = diff --git a/modules/users/tests-js/users_details_card_errors.test.tsx b/modules/users/tests-js/users_details_card_errors.test.tsx index a306305ff..6b5b28a2e 100644 --- a/modules/users/tests-js/users_details_card_errors.test.tsx +++ b/modules/users/tests-js/users_details_card_errors.test.tsx @@ -172,4 +172,19 @@ describe('Admin DetailsCard 422 inline field errors (#1337)', () => { expect(emailInput).toHaveAttribute('aria-invalid', 'false'); expect(screen.queryAllByRole('alert')).toHaveLength(0); }); + + it('reconciles form and baseline with server-trimmed full_name when roles PUT fails', async () => { + stubFetch((req) => + req.method === 'PATCH' + ? json(200, { id: 'u1', email: 'alice@example.com', full_name: 'Trimmed Alice' }) + : json(403, { detail: 'Forbidden' }), + ); + + render(); + const nameInput = screen.getByLabelText('Full name'); + fireEvent.change(nameInput, { target: { value: ' Trimmed Alice ' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + + await waitFor(() => expect(nameInput).toHaveValue('Trimmed Alice')); + }); }); diff --git a/modules/users/tests/contracts/test_full_name_validation.py b/modules/users/tests/contracts/test_full_name_validation.py index 0909cc4af..287c05afb 100644 --- a/modules/users/tests/contracts/test_full_name_validation.py +++ b/modules/users/tests/contracts/test_full_name_validation.py @@ -65,3 +65,11 @@ def test_full_name_trims_and_rejects_blank(schema_cls, base_payload): schema_cls(**base_payload, full_name=blank) errors = exc_info.value.errors() assert any(e["loc"] == ("full_name",) and e["type"] == "string_too_short" for e in errors) + + +def test_accept_invite_strips_before_length_and_allows_blank(): + padded = AcceptInviteRequest(token="tok", password="Password1!", full_name=" " + "a" * 200) + assert padded.full_name == "a" * 200 + + blank = AcceptInviteRequest(token="tok", password="Password1!", full_name=" " * 205) + assert blank.full_name == "" diff --git a/modules/users/users/auth_local/components/AuthField.tsx b/modules/users/users/auth_local/components/AuthField.tsx index 7262f4db0..108271428 100644 --- a/modules/users/users/auth_local/components/AuthField.tsx +++ b/modules/users/users/auth_local/components/AuthField.tsx @@ -9,6 +9,8 @@ interface AuthFieldProps { action?: React.ReactNode; /** Field-level message, shown under the control in the destructive tone. */ error?: string | null; + /** Optional ID for `aria-describedby` wiring on the associated control. */ + errorId?: string; children: React.ReactNode; } @@ -20,7 +22,7 @@ interface AuthFieldProps { * for exactly one field. Kept in one place so a field-level error looks the * same on register, reset and invite instead of drifting into three variants. */ -export function AuthField({ htmlFor, label, action, error, children }: AuthFieldProps) { +export function AuthField({ htmlFor, label, action, error, errorId, children }: AuthFieldProps) { return (
@@ -30,7 +32,11 @@ export function AuthField({ htmlFor, label, action, error, children }: AuthField {action}
{children} - {error &&

{error}

} + {error && ( + + )}
); } diff --git a/modules/users/users/contracts/schemas.py b/modules/users/users/contracts/schemas.py index 83fb3050c..3497b7a8c 100644 --- a/modules/users/users/contracts/schemas.py +++ b/modules/users/users/contracts/schemas.py @@ -194,7 +194,10 @@ class LoginRequest(SQLModel): class AcceptInviteRequest(SQLModel): token: str password: str - full_name: str | None = Field(default=None, max_length=MAX_FULL_NAME_LENGTH) + full_name: ( + Annotated[str, StringConstraints(strip_whitespace=True, max_length=MAX_FULL_NAME_LENGTH)] + | None + ) = None """What the invitee calls themselves. Optional because an admin may have filled it in when minting the invite, in which case the form pre-fills and a blank submit must not wipe it.""" diff --git a/modules/users/users/core/directory.py b/modules/users/users/core/directory.py index 7bfe2c9d8..6b7f3bd5b 100644 --- a/modules/users/users/core/directory.py +++ b/modules/users/users/core/directory.py @@ -117,14 +117,12 @@ async def search( if exclude_ids: stmt = stmt.where(User.id.not_in(list(parse_user_ids(exclude_ids)))) if exclude_roles: - role_names = [name for name in exclude_roles if name] - if role_names: - excluded_role_subq = ( - select(UserRole.user_id) - .join(Role, Role.id == UserRole.role_id) - .where(UserRole.user_id == User.id, Role.name.in_(role_names)) - ) - stmt = stmt.where(~exists(excluded_role_subq)) + excluded_role_subq = ( + select(UserRole.user_id) + .join(Role, Role.id == UserRole.role_id) + .where(UserRole.user_id == User.id, Role.name.in_(list(exclude_roles))) + ) + stmt = stmt.where(~exists(excluded_role_subq)) if active_only: stmt = stmt.where(User.is_active.is_(True), User.disabled_at.is_(None)) if exact_email: diff --git a/modules/users/users/pages/AcceptInvite.tsx b/modules/users/users/pages/AcceptInvite.tsx index 0ecf4650f..72104c336 100644 --- a/modules/users/users/pages/AcceptInvite.tsx +++ b/modules/users/users/pages/AcceptInvite.tsx @@ -43,6 +43,7 @@ function AcceptInvite({ token, invite, branding }: Props) { const [error, setError] = useState(null); const [fullNameError, setFullNameError] = useState(null); const [loading, setLoading] = useState(false); + const nameErrorId = 'accept-invite-full-name-error'; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); @@ -126,6 +127,7 @@ function AcceptInvite({ token, invite, branding }: Props) { htmlFor="full_name" label={t(keys.users.common.full_name)} error={fullNameError ?? undefined} + errorId={nameErrorId} > ({ ...prev, email: submittedEmail, fullName: submittedFullName })); + const savedEmail = resp.data?.email ?? submittedEmail; + const savedFullName = + resp.data && 'full_name' in resp.data ? (resp.data.full_name ?? '') : submittedFullName; + setBaseline((prev) => ({ ...prev, email: savedEmail, fullName: savedFullName })); + setForm((prev) => ({ ...prev, email: savedEmail, fullName: savedFullName })); } if (rolesDirty) { const resp = await apiResult( @@ -221,14 +225,12 @@ export function useEditUserForm(user: EditableUser) { return { form, - setForm, setEmail, setFullName, dirtyCount, saving, error, fieldErrors, - clearFieldError, toggleRole, save, discard: () => { From 0272716f562f23c64ee9f400a72cea1cce25be4c Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Mon, 30 Nov 2026 17:14:38 +0100 Subject: [PATCH 8/9] test(users): exercise partial-save retry and document exclude_roles compatibility --- docs/framework/user-directory.md | 6 +++--- .../tests-js/users_details_card_errors.test.tsx | 13 +++++++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/framework/user-directory.md b/docs/framework/user-directory.md index a08a31b85..4cc11110a 100644 --- a/docs/framework/user-directory.md +++ b/docs/framework/user-directory.md @@ -77,9 +77,9 @@ satisfy `isinstance(directory, UserDirectory)`. Inherit `EmailLookupUserDirector to get its default `find_by_email`, or implement that method directly. Callers using an unknown provider can check `isinstance(directory, EmailLookupUserDirectory)` before calling it; otherwise use the existing -`search(db, email, limit=1, exact_email=True)` contract. Third-party providers -must accept `match_email` to support the new name-only search option; existing -calls that omit it keep their previous behavior. +`search(db, email, limit=1, exact_email=True)` contract. Third-party providers must accept `match_email` and `exclude_roles` (ignoring +`exclude_roles` when they do not store roles); existing calls that omit them +keep their previous behavior. ## Who uses it diff --git a/modules/users/tests-js/users_details_card_errors.test.tsx b/modules/users/tests-js/users_details_card_errors.test.tsx index 6b5b28a2e..8304384f2 100644 --- a/modules/users/tests-js/users_details_card_errors.test.tsx +++ b/modules/users/tests-js/users_details_card_errors.test.tsx @@ -23,6 +23,7 @@ configureI18n({ [keys.users.common.email]: 'Email', [keys.users.common.roles]: 'Roles', [keys.users.edit.error_details]: 'Failed to update details', + [keys.users.edit.error_partial]: 'Details saved, but roles failed:', [keys.users.common.error_occurred]: 'An error occurred', }, }); @@ -48,7 +49,7 @@ function DetailsHarness() { fullName={form.form.fullName} onEmailChange={form.setEmail} onFullNameChange={form.setFullName} - roles={[]} + roles={[{ id: 'r1', name: 'Editor' }]} selectedRoles={form.form.roles} onToggleRole={form.toggleRole} userId="u1" @@ -174,7 +175,7 @@ describe('Admin DetailsCard 422 inline field errors (#1337)', () => { }); it('reconciles form and baseline with server-trimmed full_name when roles PUT fails', async () => { - stubFetch((req) => + const fetchMock = stubFetch((req) => req.method === 'PATCH' ? json(200, { id: 'u1', email: 'alice@example.com', full_name: 'Trimmed Alice' }) : json(403, { detail: 'Forbidden' }), @@ -183,8 +184,16 @@ describe('Admin DetailsCard 422 inline field errors (#1337)', () => { render(); const nameInput = screen.getByLabelText('Full name'); fireEvent.change(nameInput, { target: { value: ' Trimmed Alice ' } }); + fireEvent.click(screen.getByRole('button', { name: 'Editor' })); fireEvent.click(screen.getByRole('button', { name: 'Save' })); await waitFor(() => expect(nameInput).toHaveValue('Trimmed Alice')); + expect(await screen.findByText(/Details saved, but roles failed:/)).toBeInTheDocument(); + expect(fetchMock.mock.calls.map((c) => (c[0] as Request).method)).toEqual(['PATCH', 'PUT']); + + // Retrying now sends only the roles PUT because details baseline is already reconciled. + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3)); + expect((fetchMock.mock.calls[2]?.[0] as Request | undefined)?.method).toBe('PUT'); }); }); From 293325627faf8c53452f82cccccfba7d76152c6c Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Mon, 30 Nov 2026 18:58:02 +0100 Subject: [PATCH 9/9] docs(changelog): note CacheDirectory exclude_roles no-op caveat --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65da9a63d..a1906d830 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,7 @@ All notable changes to this project are documented in this file. The format is b - Branding / Users / UI: let apps brand the stock login page without overriding it — add optional `login_heading` and `login_tagline` fields to `BrandingSettings` (shared as `branding.loginHeading` / `branding.loginTagline` and editable at `/admin/branding` and per tenant), add a `LoginAside` layout override on `LayoutComponents` (`registry.registerLayout('LoginAside', ...)`), and export `LoginForm`, `WaitingOnYou`, `DemoSignIn`, `useLoginState`, and `signIn` from `@simple-module-py/users/ui` (`modules/users/users/ui/index.ts`) (#1340). - Hosting: `HostSettings.logout_redirect_url` (`SM_LOGOUT_REDIRECT_URL`, blank by default) configures the post-logout destination for local Users sign-out; when unset, `logout_redirect_url(app)` redirects to `/` if the host serves a root route and falls back to `/users/login` otherwise (#1330). - Users / Docs: document the app upgrade workflow across framework versions and the schema changes Alembic autogenerate misses (partial/expression indexes such as `ix_users_user_email_lower` gaining `WHERE email IS NOT NULL`, and pre-migration uniqueness checks), and export reusable Alembic helpers `check_unique_oauth_identities(op)` and `recreate_user_email_lower_index(op, *, partial=True)` from `users.contracts.migrations` (#1333). -- Users / Core: `UserDirectory.search(..., exclude_roles=...)` (implemented in SQL via `NOT EXISTS` in `UsersDirectory.search` before `LIMIT` is applied, and accepted by `NullUserDirectory` and `CacheDirectory`) lets callers exclude users holding specified roles without post-limit filtering (#1313). +- Users / Core: `UserDirectory.search(..., exclude_roles=...)` (implemented in SQL via `NOT EXISTS` in `UsersDirectory.search` before `LIMIT` is applied; accepted as a no-op by `NullUserDirectory` and OIDC/Keycloak `CacheDirectory`, which do not store roles) lets callers exclude users holding specified roles without post-limit filtering (#1313). ### Changed