diff --git a/CHANGELOG.md b/CHANGELOG.md index 95b2ec4ce..a1906d830 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; 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 @@ -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 (`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). ## [0.0.51] — 2026-11-29 diff --git a/docs/framework/user-directory.md b/docs/framework/user-directory.md index b3c2bc7f9..4cc11110a 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. | @@ -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/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/host_cli/smdev_cli/openapi.json b/host_cli/smdev_cli/openapi.json index 7994248be..40dd1a5ba 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,8 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200, + "minLength": 1 }, { "type": "null" @@ -11850,7 +11853,8 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200, + "minLength": 1 }, { "type": "null" @@ -11873,7 +11877,8 @@ "anyOf": [ { "type": "string", - "maxLength": 255 + "maxLength": 200, + "minLength": 1 }, { "type": "null" 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-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 new file mode 100644 index 000000000..8304384f2 --- /dev/null +++ b/modules/users/tests-js/users_details_card_errors.test.tsx @@ -0,0 +1,199 @@ +import '@testing-library/jest-dom/vitest'; +import { configureI18n, keys } from '@simple-module-py/i18n'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('@inertiajs/react', () => ({ + Link: ({ children, href }: { children: React.ReactNode; href: string }) => ( + {children} + ), + router: { reload: vi.fn(), on: vi.fn(() => vi.fn()) }, +})); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +import { DetailsCard } from '../users/pages/Users/components/DetailsCard'; +import { useEditUserForm } from '../users/pages/Users/components/useEditUserForm'; +import { json, stubFetch } from './users_fixtures'; + +configureI18n({ + locale: 'en', + messages: { + [keys.users.details_card.title]: 'Details', + [keys.users.common.full_name]: 'Full name', + [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', + }, +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +const TEST_USER = { + id: 'u1', + email: 'alice@example.com', + full_name: 'Alice', + roles: [] as string[], +}; + +function DetailsHarness() { + const form = useEditUserForm(TEST_USER); + return ( +
+ + +
+ ); +} + +describe('Admin DetailsCard 422 inline field errors (#1337)', () => { + it('shows inline field errors for email and full_name on 422 and clears each on edit', async () => { + stubFetch(() => + json(422, { + detail: [ + { + loc: ['body', 'email'], + msg: 'value is not a valid email address', + type: 'value_error', + }, + { + loc: ['body', 'full_name'], + msg: 'String should have at most 200 characters', + type: 'string_too_long', + }, + ], + }), + ); + + render(); + const nameInput = screen.getByLabelText('Full name'); + const emailInput = screen.getByLabelText('Email'); + + expect(nameInput).toHaveAttribute('maxlength', '200'); + + fireEvent.change(emailInput, { target: { value: 'user@' } }); + fireEvent.change(nameInput, { target: { value: 'a'.repeat(201) } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + + const alerts = await screen.findAllByRole('alert'); + expect(alerts.map((el) => el.textContent)).toEqual([ + 'String should have at most 200 characters', + 'value is not a valid email address', + ]); + expect(nameInput).toHaveAttribute('aria-invalid', 'true'); + expect(emailInput).toHaveAttribute('aria-invalid', 'true'); + expect(screen.queryByText('Failed to update details')).not.toBeInTheDocument(); + + fireEvent.change(emailInput, { target: { value: 'bob@example.com' } }); + expect(emailInput).toHaveAttribute('aria-invalid', 'false'); + expect(nameInput).toHaveAttribute('aria-invalid', 'true'); + + fireEvent.change(nameInput, { target: { value: 'Bob' } }); + expect(nameInput).toHaveAttribute('aria-invalid', 'false'); + expect(screen.queryAllByRole('alert')).toHaveLength(0); + }); + + it('sends blank full_name string rather than null so server 422 surfaces inline', async () => { + const fetchMock = stubFetch(() => + json(422, { + detail: [ + { + loc: ['body', 'full_name'], + msg: 'String should have at least 1 character', + type: 'string_too_short', + }, + ], + }), + ); + + render(); + fireEvent.change(screen.getByLabelText('Full name'), { target: { value: '' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('String should have at least 1 character'); + 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); + }); + + it('reconciles form and baseline with server-trimmed full_name when roles PUT fails', async () => { + const fetchMock = 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: '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'); + }); +}); 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/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 new file mode 100644 index 000000000..83923e3ae --- /dev/null +++ b/modules/users/tests/accounts/provider/test_users_session_ctx_refresh.py @@ -0,0 +1,53 @@ +"""Regression tests: cached session user_ctx refreshes after profile/admin updates (#1314).""" + +from __future__ import annotations + +import pytest +from _users_admin_support import _login, _make_user + +_INERTIA_HEADERS = {"X-Inertia": "true"} + + +@pytest.mark.anyio +async def test_self_update_refreshes_cached_auth_user_name(anon_client, users_db): + 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. + 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 _make_user( + users_db, "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..a5c0bc2f9 --- /dev/null +++ b/modules/users/tests/auth_local/api/test_users_me_full_name.py @@ -0,0 +1,130 @@ +"""API validation tests for full_name across users endpoints (#1315, #1335).""" + +from __future__ import annotations + +import pytest +from _users_admin_support import _login, _make_user + + +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 _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): + 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 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 "}) + 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 _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}) + 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) + + 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( + 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 + + # 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 a06d3452b..287c05afb 100644 --- a/modules/users/tests/contracts/test_full_name_validation.py +++ b/modules/users/tests/contracts/test_full_name_validation.py @@ -37,3 +37,39 @@ 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, {}), + (UserCreate, {"email": "a@example.com", "password": "Password1!"}), + (UserInvite, {"email": "a@example.com"}), + (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) + + +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/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/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..2d2f23d5c 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,20 @@ 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: + has_name = "full_name" in data.model_fields_set 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=has_name ) 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..29573f2bb 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( + updated = await user_manager.update( UserUpdate(**data.model_dump(exclude_unset=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/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/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)}

- + setFullName(e.target.value)} + onChange={(e) => { + setFullName(e.target.value); + if (fullNameError) setFullNameError(null); + }} placeholder={t(keys.users.common.name_placeholder)} + maxLength={200} + disabled={loading} autoComplete="name" + aria-invalid={!!fullNameError} + aria-describedby={fullNameError ? nameErrorId : undefined} /> { if (res.status === 201) { @@ -151,6 +151,7 @@ function Register({ require_verification = true }: RegisterProps) { value={fullName} onChange={(e) => setFullName(e.target.value)} placeholder={t(keys.users.register.name_placeholder)} + maxLength={200} autoComplete="name" /> diff --git a/modules/users/users/pages/Users/Edit.tsx b/modules/users/users/pages/Users/Edit.tsx index 48451e7fe..ebb85b0c8 100644 --- a/modules/users/users/pages/Users/Edit.tsx +++ b/modules/users/users/pages/Users/Edit.tsx @@ -106,14 +106,16 @@ function Edit({ form.setForm((prev) => ({ ...prev, email }))} - onFullNameChange={(fullName) => form.setForm((prev) => ({ ...prev, fullName }))} + 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} /> onFullNameChange(e.target.value)} placeholder={t(keys.users.create_fields.name_placeholder)} + maxLength={200} /> diff --git a/modules/users/users/pages/Users/components/DetailsCard.tsx b/modules/users/users/pages/Users/components/DetailsCard.tsx index aecd94d57..fc7bedf8a 100644 --- a/modules/users/users/pages/Users/components/DetailsCard.tsx +++ b/modules/users/users/pages/Users/components/DetailsCard.tsx @@ -2,9 +2,12 @@ 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'; import { TOUCH_TARGET_CLASS } from '@simple-module-py/ui/lib/utils'; +import { useId } from 'react'; import { type Role, RolePicker } from './RolePicker'; interface Props { @@ -17,7 +20,9 @@ interface Props { onToggleRole: (roleName: string) => void; userId: string; hasPermissionsModule: boolean; + disabled?: boolean; error?: string | null; + fieldErrors?: FieldErrors; } /** @@ -37,9 +42,16 @@ export function DetailsCard({ onToggleRole, userId, hasPermissionsModule, + disabled, error, + fieldErrors, }: Props) { const { t } = useT(); + const nameErrorId = useId(); + const emailErrorId = useId(); + const fullNameError = fieldErrors?.full_name; + const emailError = fieldErrors?.email; + return ( @@ -55,7 +67,14 @@ export function DetailsCard({ value={fullName} 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} +
diff --git a/modules/users/users/pages/Users/components/useEditUserForm.ts b/modules/users/users/pages/Users/components/useEditUserForm.ts index ae7a7a6b8..b93e5f570 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'; @@ -48,12 +48,15 @@ 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. 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 +64,33 @@ 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 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); @@ -114,6 +142,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 @@ -124,27 +153,44 @@ 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 || null } : {}), + ...(emailDirty ? { email: submittedEmail } : {}), + ...(nameDirty ? { full_name: submittedFullName } : {}), }, }), ); if (!resp.ok) { - setError( - adminFailureMessage( - resp, - t(keys.users.edit.error_details), - t(keys.users.common.error_occurred), - t, - ), - ); + 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 (!rawFieldErrors.email && !rawFieldErrors.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 })); + 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( @@ -179,12 +225,18 @@ export function useEditUserForm(user: EditableUser) { return { form, - setForm, + setEmail, + setFullName, dirtyCount, saving, error, + fieldErrors, toggleRole, save, - discard: () => setForm(baseline), + discard: () => { + setForm(baseline); + setError(null); + setFieldErrors({}); + }, }; }