diff --git a/aidlc-docs/features/identity-email-notifications/aidlc-state.md b/aidlc-docs/features/identity-email-notifications/aidlc-state.md index 5dd9e35..cf05e23 100644 --- a/aidlc-docs/features/identity-email-notifications/aidlc-state.md +++ b/aidlc-docs/features/identity-email-notifications/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: identity-email-notifications - **Project Type**: Brownfield - **Start Date**: 2026-11-08 -- **Current Stage**: CONSTRUCTION - U1 mail-foundation code generated and tested (local commits, not pushed); requirements and design approved by Bryan (relayed), D1 and D2 decided +- **Current Stage**: CONSTRUCTION - U1 and U2 code generated and tested; requirements and design approved by Bryan (relayed), D1 and D2 decided - **Branch**: feature/identity-email-notifications (branched from feature/andreaslop-site-hosting at e9feb37; own branch, not merged anywhere) - **Request Type**: Feature (Bryan chose real e-mail over a workaround button; relayed by session "CMS & API") @@ -48,5 +48,5 @@ ### CONSTRUCTION - [x] U1 mail-foundation - Infrastructure Design (construction/mail-foundation/infrastructure-design/infrastructure-design.md), Code Generation done, build and tests green (see code-summary.md); hand-back pending -- [ ] U2 identity-mail-flows -- [ ] U3 password-reset (includes D2: security stamp in the access token) +- [x] U2 identity-mail-flows - Code Generation done, build and tests green (see construction/identity-mail-flows/code/code-summary.md); includes D1 and D2; hand-back pending +- [ ] U3 password-reset (D2, the security stamp in the access token, was built in U2) diff --git a/aidlc-docs/features/identity-email-notifications/audit.md b/aidlc-docs/features/identity-email-notifications/audit.md index 3c6d090..c414a5c 100644 --- a/aidlc-docs/features/identity-email-notifications/audit.md +++ b/aidlc-docs/features/identity-email-notifications/audit.md @@ -69,3 +69,15 @@ **Context**: Construction U1, per-unit build and test done; completion message to follow via the peer session. --- + +## Construction U2 - code generation + +**Timestamp**: 2026-11-08T22:00:00Z + +**User Input**: "(Relayed by 'CMS & API') Start nu U2 identity-mail-flows (Bryan heeft ontwerp, D1 en D2 goedgekeurd): taal per gebruiker (kolom + profielkeuze), uitnodigingsmail met door beheerder gekozen taal, nieuwe link, opnieuw versturen (respons-resultaat, knop bij openstaande uitnodigingen), meldingen bij deactiveren/heractiveren/rolwijziging, plus de D2 security-stamp-controle. ... Bryan zegt in zijn chat: 'Er mag door jullie gecommit en gepusht worden.' ... Dat geldt NIET voor mergen naar master, deploy naar productie of rollen van mail-secrets; ASF test deploy blijft toegestaan zoals eerder." + +**AI Response**: "Built U2 (migration AddLanguagePreference, IdentityMailService, invite/regenerate/resend with mail result, notices on deactivation/reactivation/role change, language preference in the profile and at sign-in, D2 stamp claim and check). Tests: Core 478 (incl. MariaDB-backed migration up/down/up on a real container), Identity 115, frontend 345. Pushing the branch and dispatching deploy_asf_test (mail stays off until the host gets its mail settings)." + +**Context**: Construction U2 complete; completion message via the peer session. + +--- diff --git a/aidlc-docs/features/identity-email-notifications/construction/identity-mail-flows/code/code-summary.md b/aidlc-docs/features/identity-email-notifications/construction/identity-mail-flows/code/code-summary.md new file mode 100644 index 0000000..19f574f --- /dev/null +++ b/aidlc-docs/features/identity-email-notifications/construction/identity-mail-flows/code/code-summary.md @@ -0,0 +1,25 @@ +# Code summary - U2 identity-mail-flows + +## What was built +**Data (migration `AddLanguagePreference`, additive, reversible)**: `Users.PreferredLanguage` (nullable, nl/en), `Invitations.Language` (nullable). + +**Core** +- `IIdentityMailService` / `IdentityMailService`: one orchestration point for invitation, new-link, deactivation, reactivation and role-change mails. Builds the link as `App:PublicBaseUrl + /admin + path`, resolves the language (user preference, else the invitation's, else `App:DefaultLanguage`, else nl), takes the sender and name from the site settings, logo and colour from config, renders, sends, logs only kind and recipient domain, and never throws (a failure is a `MailSendResult`). Returns `disabled` when the site has no SMTP host. +- `InvitationService`: language stored normalised on the invitation and copied to the new account's `PreferredLanguage` on completion. +- **D2**: the security stamp is a claim of the access token (`AuthService`) and is compared in `ActiveUserTokenValidation`. A password change or reset changes the stamp, so every access token issued before it is refused; a token without the claim (issued before this release) is refused once; the refresh token silently issues a new one that carries the claim. +- `UserResponse`/`UserDto` carry `Language`. + +**Identity module (`UsersController`)** +- `POST Users/invite` accepts `language`, sends the mail, returns `{ inviteLink, mail }` (the invitation exists whatever happens to the mail). `POST Users/{id}/regenerate-invite` now also mails the new link. New `POST Users/{id}/resend-invite`: resends the current link, or creates a new one first when expired. `mail` is `{ sent, error }`, or null on a site without mail. Same role-hierarchy rules as the other invitation actions. +- Deactivate, reactivate and role change send a notice only on a real change (and not for invitations); a failure never fails the action. +- `PUT Users/me` accepts `language` (null = unchanged, "" = clear, nl/en, anything else 400). + +**Frontend**: language select in the profile (applied immediately; clearing falls back to the site default), the saved language is applied at sign-in and on the first silent refresh after a page load (not on later refreshes, so a temporary top-bar switch survives); invite dialog gets a language select (default = site language) and shows "mail sent to X" or a failure with a short reason next to the copyable link; users list gets "Uitnodiging opnieuw mailen" and the regenerate action reports the mail result; everything mail-related is hidden when the site has no mail (`emailEnabled` false). + +## Tests +- Core.Tests 478: `IdentityMailServiceTests` (link, sender, logo, lifetime, language chain, disabled, failure value, exceptions never escape, notices, role names, `BuildLink`), invitation language (normalised, unsupported ignored, copied to the account), D2 (`DeactivatedUserAccessTests`: stamp change ends tokens for GET and POST, missing and wrong stamp refused; `SessionEndsOnPasswordChangeTests`: real Identity password change with real tokens, the old access token is refused, the refresh token gives a working new one, login response carries the language). MariaDB-backed migration test now covers both new migrations up, down, up (verified on a real MariaDB container). +- Identity.Tests 115: `UsersControllerMailTests` (invite with language and result, failure still succeeds, no mail result without mail, unsupported language, regenerate/resend including expired and failed, hierarchy, notices only on real change, notice failure never fails the action, role change of an invitation sends nothing, profile language set/clear/unchanged/invalid, list shows languages). +- Frontend 345: invite dialog (no language field without mail, default site language, chosen language sent, sent/failed/no mail line), resend (hidden without mail, success, failure hands over the link, expired), profile language, language applied at sign-in or left alone. ESLint and tsc clean; asf build ok. + +## Behaviour change for SlpSoftware (and every host) +1. After deploy, access tokens issued before it lack the stamp and are refused once; the silent refresh issues a new one (users stay signed in). 2. A password change now ends earlier access tokens immediately (refresh tokens are not revoked by a plain password change; only the reset flow in U3 revokes them). 3. Two nullable columns are added by migration. 4. Mail only when `Email:Smtp:Host` is set; otherwise nothing changes (the new `language` field of the invite request is ignored when mail is off in the UI). diff --git a/frontend/src/features/auth/context/AuthProvider.tsx b/frontend/src/features/auth/context/AuthProvider.tsx index c6efc4b..dedd4ec 100644 --- a/frontend/src/features/auth/context/AuthProvider.tsx +++ b/frontend/src/features/auth/context/AuthProvider.tsx @@ -1,8 +1,14 @@ -import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import type { AuthResponse } from '@/features/auth/services/types'; import { api } from '@/lib/api-client'; +import { changeLanguage } from '@/i18n/config'; import { AuthContext, type AuthContextValue, type AuthStatus } from '@/features/auth/context/auth-context'; +/** The user's own language choice wins over the browser default; no preference leaves things alone. */ +function applyPreferredLanguage(language: 'nl' | 'en' | null | undefined) { + if (language === 'nl' || language === 'en') void changeLanguage(language); +} + /** * Owns the in-memory authentication session. On mount it attempts a silent * refresh using the httpOnly cookie (BR-U1-01) and wires the ApiClient's @@ -14,7 +20,15 @@ export function AuthProvider({ children }: { children: ReactNode }) { const [expiresAt, setExpiresAt] = useState(null); const [status, setStatus] = useState('loading'); + // The user's saved language is applied once per sign-in (the first session after the page loads and + // after each login), not on every later token refresh, so a temporary switch in the top bar survives. + const applyLanguageNext = useRef(true); + const applySession = useCallback((data: AuthResponse) => { + if (applyLanguageNext.current) { + applyLanguageNext.current = false; + applyPreferredLanguage(data.user.language); + } setUser(data.user); setAccessToken(data.accessToken); setExpiresAt(data.expiresAt); @@ -50,6 +64,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { { email, password }, { skipAuthRefresh: true }, ); + applyLanguageNext.current = true; applySession(data); }, [applySession], diff --git a/frontend/src/features/auth/services/types.ts b/frontend/src/features/auth/services/types.ts index ec7a8c9..1a78315 100644 --- a/frontend/src/features/auth/services/types.ts +++ b/frontend/src/features/auth/services/types.ts @@ -7,6 +7,8 @@ export interface User { name: string; role: UserRole; isActive: boolean; + /** Preferred language (also for e-mails); absent or null = the site default. */ + language?: 'nl' | 'en' | null; } export interface AuthResponse { diff --git a/frontend/src/features/invitation/components/InviteUserDialog.tsx b/frontend/src/features/invitation/components/InviteUserDialog.tsx index 05c2f12..b7bc27c 100644 --- a/frontend/src/features/invitation/components/InviteUserDialog.tsx +++ b/frontend/src/features/invitation/components/InviteUserDialog.tsx @@ -23,6 +23,9 @@ import { import { FormErrorBanner } from '@/components/ui/FormErrorBanner'; import { FieldError } from '@/components/ui/FieldError'; import { useInviteUser } from '@/features/users/services/useUsers'; +import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities'; +import type { MailResult } from '@/features/users/services/types'; +import { mailErrorText } from '@/features/users/mailErrors'; import { inviteUserSchema, type InviteUserFormData } from '@/features/users/schemas/users'; import { NetworkError, ProblemDetailsError } from '@/lib/api-client'; @@ -36,6 +39,13 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps) const [step, setStep] = useState<1 | 2>(1); const [inviteLink, setInviteLink] = useState(null); const [serverError, setServerError] = useState(null); + const [mailResult, setMailResult] = useState(null); + const [invitedEmail, setInvitedEmail] = useState(''); + const { data: capabilities } = useSystemCapabilities(); + const emailEnabled = capabilities?.emailEnabled ?? false; + const [language, setLanguage] = useState<'nl' | 'en' | null>(null); + // Default = the site's language until the administrator picks another. + const chosenLanguage = language ?? capabilities?.defaultLanguage ?? 'nl'; const inviteUser = useInviteUser({ onError: (err) => { if (err instanceof NetworkError) { @@ -63,6 +73,8 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps) if (!nextOpen) { setStep(1); setInviteLink(null); + setMailResult(null); + setLanguage(null); setServerError(null); inviteUser.reset(); reset(); @@ -73,8 +85,10 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps) const onSubmit = handleSubmit(async (values) => { setServerError(null); try { - const response = await inviteUser.mutateAsync(values); + const response = await inviteUser.mutateAsync(emailEnabled ? { ...values, language: chosenLanguage } : values); setInviteLink(response.inviteLink); + setMailResult(response.mail ?? null); + setInvitedEmail(values.email); setStep(2); } catch { // error shown via serverError state @@ -146,6 +160,23 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps) )} + {emailEnabled && ( +
+ + +

{t('users.invite.languageHelp')}

+
+ )} +