Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 `<html lang="{{ request.state.locale or 'en' }}">` (#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 `<h2>` headings under the `<h1>` 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

Expand Down
8 changes: 4 additions & 4 deletions docs/framework/user-directory.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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

Expand Down
4 changes: 4 additions & 0 deletions framework/core/simple_module_core/access/user_directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,16 @@ 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,
) -> list[DirectoryUser]:
"""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
Expand Down Expand Up @@ -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,
Expand Down
17 changes: 11 additions & 6 deletions host_cli/smdev_cli/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -8227,7 +8227,7 @@
"anyOf": [
{
"type": "string",
"maxLength": 255
"maxLength": 200
},
{
"type": "null"
Expand Down Expand Up @@ -10021,7 +10021,8 @@
"anyOf": [
{
"type": "string",
"maxLength": 255
"maxLength": 200,
"minLength": 1
},
{
"type": "null"
Expand Down Expand Up @@ -11703,7 +11704,8 @@
"anyOf": [
{
"type": "string",
"maxLength": 255
"maxLength": 200,
"minLength": 1
},
{
"type": "null"
Expand Down Expand Up @@ -11816,7 +11818,8 @@
"anyOf": [
{
"type": "string",
"maxLength": 255
"maxLength": 200,
"minLength": 1
},
{
"type": "null"
Expand Down Expand Up @@ -11850,7 +11853,8 @@
"anyOf": [
{
"type": "string",
"maxLength": 255
"maxLength": 200,
"minLength": 1
},
{
"type": "null"
Expand All @@ -11873,7 +11877,8 @@
"anyOf": [
{
"type": "string",
"maxLength": 255
"maxLength": 200,
"minLength": 1
},
{
"type": "null"
Expand Down
4 changes: 3 additions & 1 deletion modules/auth/auth/oidc_common/directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,16 @@ 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,
) -> list[DirectoryUser]:
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():
Expand Down
2 changes: 1 addition & 1 deletion modules/users/tests-js/users_admin_error_details.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
199 changes: 199 additions & 0 deletions modules/users/tests-js/users_details_card_errors.test.tsx
Original file line number Diff line number Diff line change
@@ -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 }) => (
<a href={href}>{children}</a>
),
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 (
<div>
<DetailsCard
email={form.form.email}
fullName={form.form.fullName}
onEmailChange={form.setEmail}
onFullNameChange={form.setFullName}
roles={[{ id: 'r1', name: 'Editor' }]}
selectedRoles={form.form.roles}
onToggleRole={form.toggleRole}
userId="u1"
hasPermissionsModule={false}
disabled={form.saving}
error={form.error}
fieldErrors={form.fieldErrors}
/>
<button type="button" onClick={form.save}>
Save
</button>
</div>
);
}

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(<DetailsHarness />);
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(<DetailsHarness />);
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<Response>((resolve) => {
resolveResp = resolve;
}),
);

render(<DetailsHarness />);
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(<DetailsHarness />);
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');
});
});
Loading
Loading