U3 password-reset (frontend en documentatie): wachtwoord vergeten en nieuw wachtwoord kiezen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -49,4 +49,4 @@
|
||||
### 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
|
||||
- [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)
|
||||
- [x] U3 password-reset - Code Generation done, build and tests green (see construction/password-reset/code/code-summary.md); hand-back pending (D2, the security stamp in the access token, was built in U2)
|
||||
|
||||
@@ -81,3 +81,15 @@
|
||||
**Context**: Construction U2 complete; completion message via the peer session.
|
||||
|
||||
---
|
||||
|
||||
## Construction U3 - code generation
|
||||
|
||||
**Timestamp**: 2026-11-08T23:00:00Z
|
||||
|
||||
**User Input**: "(Relayed by 'CMS & API') Bryan: gewone wachtwoordwijziging trekt alleen oude access-tokens in, NIET de refresh-tokens (zoals nu). Alleen de voltooide reset (U3) trekt alle refresh-tokens in. Ga door met U3 password-reset, niet je beurt beeindigen voor U3 gebouwd en getest is."
|
||||
|
||||
**AI Response**: "Built U3 (forgot-password / reset-password, token providers, cooldown, background dispatcher, pages and login link). Tests: Core 500 (reset flow with real Identity and tokens: a request touches nothing, a completed reset ends all sessions), Identity 126, frontend 355. A plain password change keeps refresh tokens (only access tokens end through the stamp), as decided. Design deviation noted: the anonymous forgot-password endpoint handles the request after answering, to keep the response time uniform."
|
||||
|
||||
**Context**: Construction U3 complete; Build and Test and Operations follow.
|
||||
|
||||
---
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# Code summary - U3 password-reset
|
||||
|
||||
## What was built
|
||||
**Core**
|
||||
- Identity gets the default token providers (stateless data-protection reset token, single use through the security stamp). `PasswordResetSettings` (section `Identity:PasswordReset`: `TokenLifetimeMinutes` default 60, range 5..1440; `CooldownMinutes` default 5, range 1..60), validated at start-up; the reset link lifetime is the data-protection token lifetime.
|
||||
- `IPasswordResetService`:
|
||||
- `RequestAsync(email)`: only when mail is on and the cooldown allows; unknown, deactivated and blank addresses do nothing; sends the reset mail. It writes nothing else: no password, security stamp, access token or refresh token is touched. Never throws.
|
||||
- `ResetAsync(userId, token, newPassword)`: `UserManager.ResetPasswordAsync`; a bad, expired, used or foreign token, an unknown or deactivated user are one generic `InvalidLink`; a password-policy failure (checked after the token, so only a link holder sees it) is `PasswordRejected` and does not use up the link. **Only a completed reset revokes every refresh token of the account**; earlier access tokens end through the changed security stamp (D2).
|
||||
- `ResetCooldown` (in memory, `TimeProvider`-driven): one mail per address per window, unknown addresses included, bounded memory (purge, hard cap 10,000, refuse new addresses when full).
|
||||
- `IPasswordResetDispatcher` / `BackgroundPasswordResetDispatcher`: the anonymous endpoint answers first and the request is handled afterwards in its own scope, so the response time does not tell whether the address exists and a slow SMTP server cannot hold the request (a deliberate difference from the in-request sending of administrator-triggered mails).
|
||||
- `IIdentityMailService.SendPasswordResetAsync`: link `App:PublicBaseUrl/admin/reset-password?uid=<user id>&token=<token>` (user id, no e-mail address in a URL), recipient's language, lifetime stated in the mail.
|
||||
|
||||
**Identity module (`AuthController`)**: `POST auth/forgot-password` (anonymous, `login` rate limiter): 404 on a site without mail, 400 for a malformed address, otherwise always the same 202 body. `POST auth/reset-password` (anonymous, `login` rate limiter): input bounds (token 2048, password 128, non-empty user id), 200, or 400 with `invalid_link` / `password_rejected`.
|
||||
|
||||
**Frontend**: `/forgot-password` (neutral "if this address belongs to an account..." message; 404 explained), `/reset-password?uid&token` (same password rules as everywhere, success, one generic "link invalid or expired" page with "request a new link", a rejected password keeps the form), "Wachtwoord vergeten?" on the login page only when `emailEnabled`, nl/en strings.
|
||||
|
||||
## Tests
|
||||
- Core.Tests (real Identity, real data-protection tokens, real bearer check on a TestServer): **a request leaves password hash, security stamp, refresh tokens, the earlier access token and the old password all working** (Bryan's rule); **a completed reset sets the new password, ends the earlier access token (401), revokes the refresh token, no active refresh tokens remain, the old password fails**; the link works once; an expired link is refused and the password stays; another user's token, garbage and an unknown user are refused; a weak password is reported without using up the link; unknown, deactivated and blank addresses send nothing and do not throw; a deactivated account cannot complete a reset; a site without mail does nothing; one mail per address per window (case-insensitive) then works again; the cooldown also applies to unknown addresses; cooldown memory bound; property-based: for any request sequence two accepted requests for one address are never closer than the window (PBT-03); settings ranges; DI wiring and start-up validation; dispatcher returns at once and handles in the background, a failing request never surfaces; reset mail link carries the user id and no address.
|
||||
- Identity.Tests 126: both endpoints anonymous and under the `login` limiter, same 202 for any well-formed address, malformed addresses rejected without dispatching, 404 without mail, outcome mapping, bounds.
|
||||
- Frontend 355: login link only with mail, validation, neutral sent message, 404, missing link, rules, token/uid sent, generic invalid page, rejected password keeps the form.
|
||||
|
||||
## Behaviour change for SlpSoftware (and every host)
|
||||
Identity registration now includes the default token providers (inert unless a reset is requested); the two endpoints answer 404 while mail is off; nothing else changes without mail.
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||
import { forgotPasswordFormSchema, type ForgotPasswordFormData } from '@/features/auth/schemas/auth';
|
||||
import { useForgotPassword } from '@/features/auth/services/usePasswordReset';
|
||||
|
||||
/**
|
||||
* Asks for a reset link. The answer never says whether the address belongs to an account: it is the same
|
||||
* message for every well-formed address.
|
||||
*/
|
||||
export function ForgotPasswordPage() {
|
||||
const { t } = useTranslation();
|
||||
const forgot = useForgotPassword();
|
||||
const [sent, setSent] = useState(false);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<ForgotPasswordFormData>({
|
||||
resolver: zodResolver(forgotPasswordFormSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: { email: '' },
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
await forgot.mutateAsync({ email: values.email.trim() });
|
||||
setSent(true);
|
||||
} catch (err) {
|
||||
if (err instanceof NetworkError) setServerError(t('errors.network'));
|
||||
else if (err instanceof ProblemDetailsError && err.status === 404) setServerError(t('forgotPassword.unavailable'));
|
||||
else setServerError(t('errors.generic'));
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>{t('forgotPassword.title')}</CardTitle>
|
||||
<CardDescription>{sent ? t('forgotPassword.sentTitle') : t('forgotPassword.description')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{sent ? (
|
||||
<p className="text-sm" data-testid="forgot-sent">
|
||||
{t('forgotPassword.sentMessage')}
|
||||
</p>
|
||||
) : (
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4">
|
||||
{serverError !== null && (
|
||||
<div
|
||||
role="alert"
|
||||
data-testid="forgot-error"
|
||||
className="rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive"
|
||||
>
|
||||
{serverError}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="forgot-email">{t('login.email')}</Label>
|
||||
<Input
|
||||
id="forgot-email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder={t('login.emailPlaceholder')}
|
||||
data-testid="forgot-email-input"
|
||||
aria-invalid={errors.email !== undefined}
|
||||
{...register('email')}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p className="text-sm text-destructive" data-testid="forgot-email-error">
|
||||
{errors.email.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={isSubmitting} data-testid="forgot-submit">
|
||||
{isSubmitting ? t('login.submitting') : t('forgotPassword.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
<Link to="/login" className="block text-center text-sm underline" data-testid="forgot-back">
|
||||
{t('forgotPassword.backToLogin')}
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import { Label } from '@/components/ui/label';
|
||||
import { useAuth } from '@/features/auth/context/auth-context';
|
||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||
import { loginFormSchema, type LoginFormData } from '@/features/auth/schemas/auth';
|
||||
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
|
||||
export function LoginPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -17,6 +19,7 @@ export function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const search = useSearch({ strict: false }) as { redirect?: string };
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const { data: capabilities } = useSystemCapabilities();
|
||||
|
||||
const {
|
||||
register,
|
||||
@@ -114,6 +117,15 @@ export function LoginPage() {
|
||||
{isSubmitting ? t('login.submitting') : t('login.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
{capabilities?.emailEnabled && (
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
className="mt-4 block text-center text-sm underline"
|
||||
data-testid="login-forgot-link"
|
||||
>
|
||||
{t('login.forgotPassword')}
|
||||
</Link>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { renderApp, mockGuest } from '@/test/utils';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
});
|
||||
|
||||
const AUTH = `${API_BASE}/api/v1/auth`;
|
||||
|
||||
function mailOn() {
|
||||
server.use(
|
||||
http.get('*/System/capabilities', () =>
|
||||
HttpResponse.json({ modules: ['Identity'], emailEnabled: true, defaultLanguage: 'nl' }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe('login page link', () => {
|
||||
it('offers "forgot password" only where mail is on', async () => {
|
||||
mockGuest();
|
||||
renderApp('/login');
|
||||
await screen.findByTestId('login-form-submit-button', {}, { timeout: 10000 });
|
||||
expect(screen.queryByTestId('login-forgot-link')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the link when mail is on', async () => {
|
||||
mockGuest();
|
||||
mailOn();
|
||||
renderApp('/login');
|
||||
|
||||
expect(await screen.findByTestId('login-forgot-link', {}, { timeout: 10000 })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ForgotPasswordPage', () => {
|
||||
it('validates the address before anything is sent', async () => {
|
||||
mockGuest();
|
||||
renderApp('/forgot-password');
|
||||
|
||||
await userEvent.type(await screen.findByTestId('forgot-email-input', {}, { timeout: 10000 }), 'not-an-address');
|
||||
await userEvent.click(screen.getByTestId('forgot-submit'));
|
||||
|
||||
expect(await screen.findByTestId('forgot-email-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sends the address and shows one neutral message', async () => {
|
||||
mockGuest();
|
||||
let body: Record<string, unknown> | undefined;
|
||||
server.use(
|
||||
http.post(`${AUTH}/forgot-password`, async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ message: 'whatever' }, { status: 202 });
|
||||
}),
|
||||
);
|
||||
renderApp('/forgot-password');
|
||||
|
||||
await userEvent.type(await screen.findByTestId('forgot-email-input', {}, { timeout: 10000 }), ' someone@example.org ');
|
||||
await userEvent.click(screen.getByTestId('forgot-submit'));
|
||||
|
||||
const sent = await screen.findByTestId('forgot-sent');
|
||||
expect(body).toEqual({ email: 'someone@example.org' });
|
||||
// The text says "if this address belongs to an account", never that it does or does not.
|
||||
expect(sent).toHaveTextContent(/if this address belongs to an account/i);
|
||||
});
|
||||
|
||||
it('says so plainly when the site has no mail (404)', async () => {
|
||||
mockGuest();
|
||||
server.use(http.post(`${AUTH}/forgot-password`, () => new HttpResponse(null, { status: 404 })));
|
||||
renderApp('/forgot-password');
|
||||
|
||||
await userEvent.type(await screen.findByTestId('forgot-email-input', {}, { timeout: 10000 }), 'a@example.org');
|
||||
await userEvent.click(screen.getByTestId('forgot-submit'));
|
||||
|
||||
expect(await screen.findByTestId('forgot-error')).toHaveTextContent(/not available/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ResetPasswordPage', () => {
|
||||
it('without a link in the address it explains and offers a new request', async () => {
|
||||
mockGuest();
|
||||
renderApp('/reset-password');
|
||||
|
||||
expect(await screen.findByTestId('reset-invalid', {}, { timeout: 10000 })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('reset-request-new')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies the same password rules as everywhere else', async () => {
|
||||
mockGuest();
|
||||
renderApp('/reset-password?uid=11111111-1111-1111-1111-111111111111&token=abc');
|
||||
|
||||
await userEvent.type(await screen.findByTestId('reset-password-input', {}, { timeout: 10000 }), 'short');
|
||||
await userEvent.type(screen.getByTestId('reset-confirm-input'), 'different');
|
||||
await userEvent.click(screen.getByTestId('reset-submit'));
|
||||
|
||||
expect(await screen.findByTestId('reset-password-error')).toBeInTheDocument();
|
||||
expect(await screen.findByTestId('reset-confirm-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sets the new password with the user id and token from the link', async () => {
|
||||
mockGuest();
|
||||
let body: Record<string, unknown> | undefined;
|
||||
server.use(
|
||||
http.post(`${AUTH}/reset-password`, async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ message: 'ok' });
|
||||
}),
|
||||
);
|
||||
renderApp('/reset-password?uid=11111111-1111-1111-1111-111111111111&token=to%2Fken%2B1%3D');
|
||||
|
||||
await userEvent.type(await screen.findByTestId('reset-password-input', {}, { timeout: 10000 }), 'Brand-New-Pass9!');
|
||||
await userEvent.type(screen.getByTestId('reset-confirm-input'), 'Brand-New-Pass9!');
|
||||
await userEvent.click(screen.getByTestId('reset-submit'));
|
||||
|
||||
expect(await screen.findByTestId('reset-done')).toBeInTheDocument();
|
||||
expect(body).toEqual({
|
||||
userId: '11111111-1111-1111-1111-111111111111',
|
||||
token: 'to/ken+1=',
|
||||
newPassword: 'Brand-New-Pass9!',
|
||||
});
|
||||
});
|
||||
|
||||
it('shows one generic "invalid or expired" page for a bad, used or expired link', async () => {
|
||||
mockGuest();
|
||||
server.use(
|
||||
http.post(`${AUTH}/reset-password`, () =>
|
||||
HttpResponse.json({ code: 'invalid_link', detail: 'This link is invalid or has expired.' }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
renderApp('/reset-password?uid=11111111-1111-1111-1111-111111111111&token=stale');
|
||||
|
||||
await userEvent.type(await screen.findByTestId('reset-password-input', {}, { timeout: 10000 }), 'Brand-New-Pass9!');
|
||||
await userEvent.type(screen.getByTestId('reset-confirm-input'), 'Brand-New-Pass9!');
|
||||
await userEvent.click(screen.getByTestId('reset-submit'));
|
||||
|
||||
expect(await screen.findByTestId('reset-invalid')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the form when the server rejects the password, so another one can be tried', async () => {
|
||||
mockGuest();
|
||||
server.use(
|
||||
http.post(`${AUTH}/reset-password`, () =>
|
||||
HttpResponse.json({ code: 'password_rejected', detail: 'x', problems: ['too weak'] }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
renderApp('/reset-password?uid=11111111-1111-1111-1111-111111111111&token=abc');
|
||||
|
||||
await userEvent.type(await screen.findByTestId('reset-password-input', {}, { timeout: 10000 }), 'Brand-New-Pass9!');
|
||||
await userEvent.type(screen.getByTestId('reset-confirm-input'), 'Brand-New-Pass9!');
|
||||
await userEvent.click(screen.getByTestId('reset-submit'));
|
||||
|
||||
expect(await screen.findByTestId('reset-error')).toHaveTextContent(/does not meet the requirements/i);
|
||||
expect(screen.getByTestId('reset-form')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Link, useNavigate, useSearch } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||
import { resetPasswordFormSchema, type ResetPasswordFormData } from '@/features/auth/schemas/auth';
|
||||
import { useResetPassword } from '@/features/auth/services/usePasswordReset';
|
||||
|
||||
type View = 'form' | 'done' | 'invalid';
|
||||
|
||||
/** Sets a new password with the link from the mail (?uid=...&token=...). */
|
||||
export function ResetPasswordPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const search = useSearch({ strict: false }) as { uid?: string; token?: string };
|
||||
const reset = useResetPassword();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [view, setView] = useState<View>(search.uid && search.token ? 'form' : 'invalid');
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<ResetPasswordFormData>({
|
||||
resolver: zodResolver(resetPasswordFormSchema),
|
||||
mode: 'onBlur',
|
||||
defaultValues: { password: '', confirmPassword: '' },
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
await reset.mutateAsync({ userId: search.uid!, token: search.token!, newPassword: values.password });
|
||||
setView('done');
|
||||
setTimeout(() => void navigate({ to: '/login' }), 2500);
|
||||
} catch (err) {
|
||||
if (err instanceof NetworkError) {
|
||||
setServerError(t('errors.network'));
|
||||
} else if (err instanceof ProblemDetailsError && err.status === 400) {
|
||||
const code = (err.problem as { code?: string }).code;
|
||||
if (code === 'password_rejected') setServerError(t('resetPassword.passwordRejected'));
|
||||
else setView('invalid');
|
||||
} else {
|
||||
setServerError(t('errors.generic'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (view === 'invalid') {
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4" data-testid="reset-invalid">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive">{t('resetPassword.invalidTitle')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">{t('resetPassword.invalidMessage')}</p>
|
||||
<Button asChild variant="outline" className="w-full">
|
||||
<Link to="/forgot-password" data-testid="reset-request-new">
|
||||
{t('resetPassword.requestNew')}
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (view === 'done') {
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4" data-testid="reset-done">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardContent className="space-y-3 pt-6 text-center">
|
||||
<div className="text-lg font-medium text-green-600">✓ {t('resetPassword.success')}</div>
|
||||
<Link to="/login" className="text-sm underline">
|
||||
{t('forgotPassword.backToLogin')}
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>{t('resetPassword.title')}</CardTitle>
|
||||
<CardDescription>{t('resetPassword.description')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4" data-testid="reset-form">
|
||||
{serverError !== null && (
|
||||
<div
|
||||
role="alert"
|
||||
data-testid="reset-error"
|
||||
className="rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive"
|
||||
>
|
||||
{serverError}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="reset-password">{t('resetPassword.passwordLabel')}</Label>
|
||||
<Input
|
||||
id="reset-password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
data-testid="reset-password-input"
|
||||
aria-invalid={errors.password !== undefined}
|
||||
{...register('password')}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p className="text-sm text-destructive" data-testid="reset-password-error">
|
||||
{errors.password.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="reset-confirm">{t('resetPassword.confirmLabel')}</Label>
|
||||
<Input
|
||||
id="reset-confirm"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
data-testid="reset-confirm-input"
|
||||
aria-invalid={errors.confirmPassword !== undefined}
|
||||
{...register('confirmPassword')}
|
||||
/>
|
||||
{errors.confirmPassword && (
|
||||
<p className="text-sm text-destructive" data-testid="reset-confirm-error">
|
||||
{errors.confirmPassword.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={isSubmitting || reset.isPending} data-testid="reset-submit">
|
||||
{isSubmitting || reset.isPending ? '...' : t('resetPassword.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -59,3 +59,23 @@ export const loginFormSchema = z.object({
|
||||
});
|
||||
|
||||
export type LoginFormData = z.infer<typeof loginFormSchema>;
|
||||
|
||||
// Forgot password: only an address.
|
||||
export const forgotPasswordFormSchema = z.object({
|
||||
email: z.string()
|
||||
.min(1, 'E-mailadres is vereist')
|
||||
.email('Voer een geldig e-mailadres in')
|
||||
});
|
||||
|
||||
export type ForgotPasswordFormData = z.infer<typeof forgotPasswordFormSchema>;
|
||||
|
||||
// Reset password: a new password twice (same rules as everywhere else).
|
||||
export const resetPasswordFormSchema = z.object({
|
||||
password: passwordSchema,
|
||||
confirmPassword: confirmPasswordSchema
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Wachtwoorden komen niet overeen',
|
||||
path: ['confirmPassword']
|
||||
});
|
||||
|
||||
export type ResetPasswordFormData = z.infer<typeof resetPasswordFormSchema>;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
|
||||
/** Always answers the same for a well-formed address, whether the account exists or not. */
|
||||
export function useForgotPassword() {
|
||||
return useMutation<{ message: string }, Error, { email: string }>({
|
||||
mutationFn: (data) =>
|
||||
api.post<{ message: string }>('/api/v1/auth/forgot-password', data, { skipAuthRefresh: true }),
|
||||
});
|
||||
}
|
||||
|
||||
export interface ResetPasswordPayload {
|
||||
userId: string;
|
||||
token: string;
|
||||
newPassword: string;
|
||||
}
|
||||
|
||||
export function useResetPassword() {
|
||||
return useMutation<{ message: string }, Error, ResetPasswordPayload>({
|
||||
mutationFn: (data) =>
|
||||
api.post<{ message: string }>('/api/v1/auth/reset-password', data, { skipAuthRefresh: true }),
|
||||
});
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
"login": {
|
||||
"title": "Sign in",
|
||||
"subtitle": "Sign in to your SlpModularCms account",
|
||||
"forgotPassword": "Forgot your password?",
|
||||
"email": "Email",
|
||||
"emailPlaceholder": "you@example.com",
|
||||
"password": "Password",
|
||||
@@ -36,6 +37,27 @@
|
||||
"generic": "Something went wrong. Please try again."
|
||||
}
|
||||
},
|
||||
"forgotPassword": {
|
||||
"title": "Forgot password",
|
||||
"description": "Enter your e-mail address. If it belongs to an account you will get an e-mail with a link to choose a new password.",
|
||||
"submit": "Send link",
|
||||
"sentTitle": "Check your e-mail",
|
||||
"sentMessage": "If this address belongs to an account, an e-mail with a link is on its way. Nothing arrived? Check your spam folder or ask the administrator for help.",
|
||||
"backToLogin": "Back to sign in",
|
||||
"unavailable": "Resetting your password by e-mail is not available on this site. Ask the administrator for help."
|
||||
},
|
||||
"resetPassword": {
|
||||
"title": "Choose a new password",
|
||||
"description": "Choose a new password for your account.",
|
||||
"passwordLabel": "New password",
|
||||
"confirmLabel": "Confirm new password",
|
||||
"submit": "Save password",
|
||||
"success": "Your password has been changed. You can sign in now.",
|
||||
"passwordRejected": "This password does not meet the requirements. Choose another one.",
|
||||
"invalidTitle": "Link invalid or expired",
|
||||
"invalidMessage": "This link has expired, was already used or is invalid. Request a new link.",
|
||||
"requestNew": "Request a new link"
|
||||
},
|
||||
"setup": {
|
||||
"title": "Create first account",
|
||||
"nameLabel": "Display name",
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"login": {
|
||||
"title": "Inloggen",
|
||||
"subtitle": "Log in op je SlpModularCms-account",
|
||||
"forgotPassword": "Wachtwoord vergeten?",
|
||||
"email": "E-mail",
|
||||
"emailPlaceholder": "jij@voorbeeld.nl",
|
||||
"password": "Wachtwoord",
|
||||
@@ -36,6 +37,27 @@
|
||||
"generic": "Er is iets misgegaan. Probeer het opnieuw."
|
||||
}
|
||||
},
|
||||
"forgotPassword": {
|
||||
"title": "Wachtwoord vergeten",
|
||||
"description": "Vul je e-mailadres in. Hoort het bij een account, dan krijg je een e-mail met een link om een nieuw wachtwoord te kiezen.",
|
||||
"submit": "Link versturen",
|
||||
"sentTitle": "Controleer je e-mail",
|
||||
"sentMessage": "Als dit adres bij een account hoort, is er een e-mail met een link onderweg. Geen e-mail gekregen? Kijk ook in je spam of vraag de beheerder om hulp.",
|
||||
"backToLogin": "Terug naar inloggen",
|
||||
"unavailable": "Wachtwoord opnieuw instellen per e-mail is op deze site niet beschikbaar. Vraag de beheerder om hulp."
|
||||
},
|
||||
"resetPassword": {
|
||||
"title": "Nieuw wachtwoord kiezen",
|
||||
"description": "Kies een nieuw wachtwoord voor je account.",
|
||||
"passwordLabel": "Nieuw wachtwoord",
|
||||
"confirmLabel": "Nieuw wachtwoord bevestigen",
|
||||
"submit": "Wachtwoord opslaan",
|
||||
"success": "Je wachtwoord is gewijzigd. Je kunt nu inloggen.",
|
||||
"passwordRejected": "Dit wachtwoord voldoet niet aan de eisen. Kies een ander wachtwoord.",
|
||||
"invalidTitle": "Link ongeldig of verlopen",
|
||||
"invalidMessage": "Deze link is verlopen, al gebruikt of ongeldig. Vraag een nieuwe link aan.",
|
||||
"requestNew": "Nieuwe link aanvragen"
|
||||
},
|
||||
"setup": {
|
||||
"title": "Eerste account aanmaken",
|
||||
"nameLabel": "Weergavenaam",
|
||||
|
||||
@@ -153,6 +153,27 @@ const loginRoute = createRoute({
|
||||
component: LoginPage,
|
||||
});
|
||||
|
||||
const forgotPasswordRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/forgot-password',
|
||||
beforeLoad: ({ context }) => {
|
||||
if (context.auth.isAuthenticated) {
|
||||
throw redirect({ to: '/dashboard' });
|
||||
}
|
||||
},
|
||||
component: lazyPage(() => import('@/features/auth/pages/ForgotPasswordPage'), 'ForgotPasswordPage'),
|
||||
});
|
||||
|
||||
const resetPasswordRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/reset-password',
|
||||
validateSearch: (search: Record<string, unknown>): { uid?: string; token?: string } => ({
|
||||
uid: typeof search.uid === 'string' ? search.uid : undefined,
|
||||
token: typeof search.token === 'string' ? search.token : undefined,
|
||||
}),
|
||||
component: lazyPage(() => import('@/features/auth/pages/ResetPasswordPage'), 'ResetPasswordPage'),
|
||||
});
|
||||
|
||||
const setupRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/setup',
|
||||
@@ -268,6 +289,8 @@ const accessDeniedRoute = createRoute({
|
||||
export const routeTree = rootRoute.addChildren([
|
||||
indexRoute,
|
||||
loginRoute,
|
||||
forgotPasswordRoute,
|
||||
resetPasswordRoute,
|
||||
setupRoute,
|
||||
inviteCompleteRoute,
|
||||
accessDeniedRoute,
|
||||
|
||||
Reference in New Issue
Block a user