diff --git a/CLAUDE.md b/CLAUDE.md index cc6ca44..b2c5719 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,8 +14,11 @@ docker compose exec web python manage.py createsuperuser docker compose exec web pytest # tests (HTTP mocké avec respx) docker compose exec web sh -c 'ruff check . && ruff format --check .' docker compose exec web python manage.py makemigrations --check --dry-run +docker compose exec web python manage.py purge_pending_accounts # tâche périodique (cron) ``` +E-mails en développement : capturés par Mailpit (`http://localhost:8025`). + Dépendances : `backend/pyproject.toml` + `uv.lock` (uv). Après modification : `uv lock` (dans un conteneur Python 3.12), puis `docker compose build web`. Front (`frontend/`, Node 24, hors Docker) : @@ -32,7 +35,10 @@ URL en dev : front `http://localhost:5173`, API `http://localhost:8000/api/v1/`, ## Architecture (`backend/`) - `config/` : settings (tout par variables d'environnement via django-environ). URL et couches des sources externes dans `PRISM_SOURCES`. -- `accounts/` : `User` (e-mail = identifiant, `status` ; seul `active` peut se connecter), `MailEvent`. Rôles = Groups « Médecin », « Cellule SSMG », « Admin » (migration `0002_roles`). Routes `/api/v1/auth/login|logout|me/` (session + CSRF, `me` dépose le cookie CSRF) ; 2FA, inscription et réinitialisation pas encore écrites. +- `accounts/` : `User` (e-mail = identifiant, `status` ; seul `active` peut se connecter), `MailEvent`, `RecoveryCode` (codes de secours hachés). Rôles = Groups « Médecin », « Cellule SSMG », « Admin » (migration `0002_roles`). + - Routes `/api/v1/auth/` : `login` (étape 1, renvoie `mfa_required`), `2fa/verify` (étape 2 : TOTP ou code de secours), `logout`, `me` (dépose le cookie CSRF), `register`, `verify-email`, `verify-email/resend`, `password/change`, `password-reset` (+ `validate`, `confirm`), `2fa/setup|enable|disable|recovery-codes`. + - `services.py` : inscription, validation/refus (actions de l'admin), 2FA (django-otp `TOTPDevice`). `tokens.py` : jetons des liens e-mail (confirmation : signés, usage unique déduit du statut ; réinitialisation : jeton de Django `uid.jeton`, 1 h, invalidé par le changement de mot de passe). `emails.py` + `templates/accounts/emails/` : les 8 e-mails, envoyés après commit et tracés dans `MailEvent`. + - L'admin Django exige la 2FA si `ADMIN_REQUIRE_OTP` (vrai hors DEBUG). Commande `purge_pending_accounts` : supprime les demandes non confirmées après 7 jours. - `factors/` : `Factor`, `DataSource`, `ThresholdClass` (valeur source → niveau 1–4 + couleur, par région ; `BE` = repli national), `ContentBlock` (textes, statut brouillon/validé, historique), `Reference` + `ContentReference` (notes numérotées). - `assessments/` : - `geocoding/` : chaîne Best Address (désactivée tant que `BEST_ADDRESS_URL` est vide, format à confirmer) → Nominatim. Région déduite du code postal. @@ -41,7 +47,7 @@ URL en dev : front `http://localhost:5173`, API `http://localhost:8000/api/v1/`, ## Front (`frontend/`) -Vue 3 + TS, sans bibliothèque de composants : composants maison stylés avec Bootstrap (CSS seul) et les variables de `src/styles/main.css`, reprises des maquettes Penpot (fichier « PRISM », page « PRISM – Mockups »). Textes dans `src/locales/fr.json`. Le front appelle l'API en même origine via le proxy Vite ; tests Vitest dans `src/__tests__/` (MapLibre mocké, pas de WebGL dans jsdom). +Vue 3 + TS (favicon de la SSMG dans `public/`), sans bibliothèque de composants : composants maison stylés avec Bootstrap (CSS seul) et les variables de `src/styles/main.css`, reprises des maquettes Penpot (fichier « PRISM », page « PRISM – Mockups »). Textes dans `src/locales/fr.json`. Pages : `/login` (avec étape 2FA), `/inscription`, `/inscription/statut`, `/mot-de-passe-oublie`, `/reinitialisation/:jeton` (liens des e-mails : le jeton est retiré de l'URL à l'arrivée), `/compte` (mot de passe, 2FA), `/`, `/403`, `/404`. MapLibre : l'URL du worker est fixée explicitement (`ResultMap.vue`), sinon les couches raster ne se chargent pas avec Vite. Le front appelle l'API en même origine via le proxy Vite ; tests Vitest dans `src/__tests__/` (MapLibre mocké, pas de WebGL dans jsdom). État des sources : bruit et inondation Wallonie via WalOnMap (ArcGIS REST `query`), air via irCELine (WMS `GetFeatureInfo`, moyennes annuelles). Bruxelles (bruit, inondation) et radon (AFCN) ne sont pas raccordés : ils renvoient `unavailable`. Pas de PostGIS pour l'instant (aucune donnée géographique stockée). diff --git a/README.md b/README.md index e0a4b90..1613f7a 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ Tests et qualité : `docker compose exec web pytest`, `docker compose exec web r ## État du projet - Spécifications et maquettes : en cours de validation. -- Code : back-end (modèles, raccordement des API WalOnMap et irCELine, API REST, connexion) et front Vue (connexion, évaluation avec carte MapLibre, pages d'erreur). Restent : Bruxelles, radon, Best Address, inscription, 2FA, mot de passe oublié, page « Mon compte ». +- Code : back-end (modèles, raccordement des API WalOnMap et irCELine, API REST, comptes : inscription avec validation par la cellule SSMG, double authentification TOTP, mot de passe oublié, e-mails) et front Vue (connexion, inscription, mot de passe oublié, évaluation avec carte MapLibre, « Mon compte », pages d'erreur). Restent : Bruxelles, radon, Best Address. - Échéance de la Phase 1 : livraison avant le 31 décembre 2026. ## Licence diff --git a/frontend/index.html b/frontend/index.html index a423eb3..35ebe30 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -2,7 +2,10 @@ - + + + + PRISM – Environnement et santé diff --git a/frontend/public/apple-touch-icon.png b/frontend/public/apple-touch-icon.png new file mode 100644 index 0000000..7fbc9c2 Binary files /dev/null and b/frontend/public/apple-touch-icon.png differ diff --git a/frontend/public/favicon-32.png b/frontend/public/favicon-32.png new file mode 100644 index 0000000..a9a1e89 Binary files /dev/null and b/frontend/public/favicon-32.png differ diff --git a/frontend/public/favicon-57.png b/frontend/public/favicon-57.png new file mode 100644 index 0000000..0e93f0e Binary files /dev/null and b/frontend/public/favicon-57.png differ diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico deleted file mode 100644 index df36fcf..0000000 Binary files a/frontend/public/favicon.ico and /dev/null differ diff --git a/frontend/src/__tests__/CodeInput.spec.ts b/frontend/src/__tests__/CodeInput.spec.ts new file mode 100644 index 0000000..f69d5aa --- /dev/null +++ b/frontend/src/__tests__/CodeInput.spec.ts @@ -0,0 +1,68 @@ +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import { defineComponent, ref } from 'vue' + +import CodeInput from '@/components/CodeInput.vue' + +// Parent avec v-model : reproduit l'usage réel (la valeur ne remonte qu'au rendu du parent). +function mountWithModel() { + const completed: string[] = [] + const Parent = defineComponent({ + components: { CodeInput }, + setup: () => ({ code: ref(''), completed }), + template: '', + }) + const wrapper = mount(Parent, { attachTo: document.body }) + return { wrapper, completed } +} + +function paste(input: Element, text: string) { + const event = new Event('paste', { bubbles: true, cancelable: true }) as ClipboardEvent + Object.defineProperty(event, 'clipboardData', { value: { getData: () => text } }) + input.dispatchEvent(event) +} + +describe('CodeInput', () => { + it('affiche six cases étiquetées', () => { + const { wrapper } = mountWithModel() + const digits = wrapper.findAll('input') + expect(digits).toHaveLength(6) + expect(digits[0]!.attributes('autocomplete')).toBe('one-time-code') + expect(digits[5]!.attributes('aria-label')).toBe('Code – chiffre 6') + wrapper.unmount() + }) + + it('répartit un code collé et émet complete', async () => { + const { wrapper, completed } = mountWithModel() + paste(wrapper.find('input').element, '123 456') + await wrapper.vm.$nextTick() + expect(wrapper.findAll('input').map((i) => (i.element as HTMLInputElement).value)).toEqual([ + '1', + '2', + '3', + '4', + '5', + '6', + ]) + expect(completed).toEqual(['123456']) + wrapper.unmount() + }) + + it('émet complete à la saisie du dernier chiffre', async () => { + const { wrapper, completed } = mountWithModel() + const inputs = wrapper.findAll('input') + for (const [index, digit] of [...'987654'].entries()) { + await inputs[index]!.setValue(digit) + } + expect(completed).toEqual(['987654']) + wrapper.unmount() + }) + + it('ignore les caractères non numériques', async () => { + const { wrapper, completed } = mountWithModel() + await wrapper.find('input').setValue('a') + expect((wrapper.find('input').element as HTMLInputElement).value).toBe('') + expect(completed).toEqual([]) + wrapper.unmount() + }) +}) diff --git a/frontend/src/__tests__/helpers.ts b/frontend/src/__tests__/helpers.ts index c613608..d21e88f 100644 --- a/frontend/src/__tests__/helpers.ts +++ b/frontend/src/__tests__/helpers.ts @@ -13,6 +13,7 @@ export const USER: User = { last_name: 'Dupont', roles: ['Médecin'], is_staff: false, + mfa_enabled: false, } export function factor(overrides: Partial = {}): FactorResult { diff --git a/frontend/src/__tests__/mfa.spec.ts b/frontend/src/__tests__/mfa.spec.ts new file mode 100644 index 0000000..4cbe488 --- /dev/null +++ b/frontend/src/__tests__/mfa.spec.ts @@ -0,0 +1,245 @@ +import { flushPromises } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { resetAuth, useAuth } from '@/composables/useAuth' +import MfaPanel from '@/components/MfaPanel.vue' +import AccountView from '@/views/AccountView.vue' +import LoginView from '@/views/LoginView.vue' + +import { jsonResponse, makeRouter, mockFetch, mountWithPlugins, USER } from './helpers' + +beforeEach(resetAuth) +afterEach(() => vi.unstubAllGlobals()) + +const SETUP = { + secret: 'ABCD EFGH IJKL MNOP', + otpauth_url: 'otpauth://totp/PRISM:x?secret=ABCD', + qr_code: 'data:image/svg+xml;base64,PHN2Zy8+', +} +const CODES = Array.from({ length: 8 }, (_, i) => `AAAA-000${i}`) + +async function pasteCode(wrapper: ReturnType, code: string) { + const event = new Event('paste', { bubbles: true, cancelable: true }) + Object.defineProperty(event, 'clipboardData', { value: { getData: () => code } }) + wrapper.find('.digit').element.dispatchEvent(event) + await flushPromises() +} + +async function signIn(user = USER) { + mockFetch(jsonResponse(200, user)) + await useAuth().load() + vi.unstubAllGlobals() +} + +describe('LoginView – seconde étape', () => { + async function toSecondStep() { + const router = makeRouter() + const push = vi.spyOn(router, 'push').mockResolvedValue(undefined) + const wrapper = mountWithPlugins(LoginView, { router, attachTo: document.body }) + await wrapper.find('#email').setValue('medecin@exemple.be') + await wrapper.find('#password').setValue('secret') + await wrapper.find('form').trigger('submit') + await flushPromises() + return { wrapper, push } + } + + it('demande le code quand la 2FA est active, sans ouvrir de session', async () => { + const fetch = mockFetch(jsonResponse(200, { mfa_required: true, user: null })) + const { wrapper, push } = await toSecondStep() + + expect(wrapper.find('h1').text()).toBe('Vérification en deux étapes') + expect(wrapper.findAll('.digit')).toHaveLength(6) + expect(fetch).toHaveBeenCalledTimes(1) + expect(push).not.toHaveBeenCalled() + expect(useAuth().user.value).toBeNull() + wrapper.unmount() + }) + + it('valide automatiquement un code complet puis redirige', async () => { + const fetch = mockFetch( + jsonResponse(200, { mfa_required: true, user: null }), + jsonResponse(200, { mfa_required: false, user: USER }), + jsonResponse(200, USER), + ) + const { wrapper, push } = await toSecondStep() + + await pasteCode(wrapper, '123456') + + expect(fetch.mock.calls[1]![0]).toBe('/api/v1/auth/2fa/verify/') + expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ code: '123456' }) + expect(useAuth().user.value).toEqual(USER) + expect(push).toHaveBeenCalledWith({ name: 'assessment' }) + wrapper.unmount() + }) + + it('code faux : message et cases vidées', async () => { + mockFetch( + jsonResponse(200, { mfa_required: true, user: null }), + jsonResponse(400, { code: 'invalid_code', detail: 'Code incorrect ou expiré.' }), + ) + const { wrapper } = await toSecondStep() + + await pasteCode(wrapper, '000000') + + expect(wrapper.find('[role="alert"]').text()).toBe('Code incorrect ou expiré.') + expect(wrapper.findAll('.digit').map((d) => (d.element as HTMLInputElement).value)).toEqual( + Array(6).fill(''), + ) + wrapper.unmount() + }) + + it('code de secours', async () => { + const fetch = mockFetch( + jsonResponse(200, { mfa_required: true, user: null }), + jsonResponse(200, { mfa_required: false, user: USER }), + jsonResponse(200, USER), + ) + const { wrapper, push } = await toSecondStep() + + await wrapper + .findAll('button') + .find((b) => b.text() === 'Utiliser un code de secours')! + .trigger('click') + await wrapper.find('#recovery').setValue('ABCD-EFGH') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ code: 'ABCD-EFGH' }) + expect(push).toHaveBeenCalled() + wrapper.unmount() + }) + + it('étape expirée : retour au mot de passe', async () => { + mockFetch( + jsonResponse(200, { mfa_required: true, user: null }), + jsonResponse(400, { code: 'mfa_expired', detail: 'Recommencez la connexion.' }), + ) + const { wrapper } = await toSecondStep() + await pasteCode(wrapper, '123456') + + expect(wrapper.find('h1').text()).toBe('Connexion') + expect(wrapper.find('[role="alert"]').text()).toBe('Recommencez la connexion.') + wrapper.unmount() + }) +}) + +describe('MfaPanel', () => { + it('active la 2FA : QR code, code, puis codes de secours', async () => { + await signIn() + const fetch = mockFetch( + jsonResponse(200, SETUP), + jsonResponse(200, { recovery_codes: CODES }), + jsonResponse(200, { ...USER, mfa_enabled: true }), + ) + const wrapper = mountWithPlugins(MfaPanel, { attachTo: document.body }) + expect(wrapper.find('.status').text()).toBe('Désactivée') + + await wrapper.find('button').trigger('click') + await flushPromises() + expect(wrapper.find('img.qr').attributes('src')).toBe(SETUP.qr_code) + expect(wrapper.text()).toContain('ABCD EFGH IJKL MNOP') + + await pasteCode(wrapper, '123456') + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ code: '123456' }) + expect(wrapper.findAll('.codes li').map((li) => li.text())).toEqual(CODES) + + const finish = wrapper.findAll('button').find((b) => b.text() === 'Terminer')! + expect(finish.attributes('disabled')).toBeDefined() + await wrapper.find('#codes-saved').setValue(true) + await finish.trigger('click') + await flushPromises() + + expect(wrapper.find('.status').text()).toBe('Activée') + expect(wrapper.text()).toContain('La double authentification est activée.') + wrapper.unmount() + }) + + it('désactive avec mot de passe et code', async () => { + await signIn({ ...USER, mfa_enabled: true }) + const fetch = mockFetch(jsonResponse(204), jsonResponse(200, { ...USER, mfa_enabled: false })) + const wrapper = mountWithPlugins(MfaPanel) + + await wrapper + .findAll('button') + .find((b) => b.text() === 'Désactiver')! + .trigger('click') + await wrapper.find('#mfa-password').setValue('secret') + await wrapper.find('#mfa-code').setValue('AAAA-0001') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ + password: 'secret', + code: 'AAAA-0001', + }) + expect(wrapper.find('.status').text()).toBe('Désactivée') + }) + + it('compte du personnel : 2FA obligatoire, pas de bouton Désactiver', async () => { + await signIn({ ...USER, is_staff: true, mfa_enabled: true }) + const wrapper = mountWithPlugins(MfaPanel) + expect(wrapper.findAll('button').map((b) => b.text())).not.toContain('Désactiver') + }) + + it('signale la 2FA obligatoire à un compte du personnel qui ne l’a pas', async () => { + await signIn({ ...USER, is_staff: true }) + const wrapper = mountWithPlugins(MfaPanel) + expect(wrapper.find('[role="alert"]').text()).toContain('obligatoire') + }) + + it('régénère les codes de secours', async () => { + await signIn({ ...USER, mfa_enabled: true }) + mockFetch(jsonResponse(200, { recovery_codes: CODES })) + const wrapper = mountWithPlugins(MfaPanel) + + await wrapper + .findAll('button') + .find((b) => b.text() === 'Régénérer les codes de secours')! + .trigger('click') + await wrapper.find('#mfa-code').setValue('123456') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.findAll('.codes li')).toHaveLength(8) + }) +}) + +describe('AccountView', () => { + it('affiche le profil et change le mot de passe', async () => { + await signIn() + const fetch = mockFetch(jsonResponse(204)) + const wrapper = mountWithPlugins(AccountView) + + expect(wrapper.find('.avatar').text()).toBe('JD') + expect(wrapper.find('.name').text()).toBe('Dr Jean Dupont') + + await wrapper.find('#current').setValue('ancien-mot-de-passe') + await wrapper.find('#next').setValue('un-nouveau-mot-de-passe') + await wrapper.find('#confirm').setValue('un-nouveau-mot-de-passe') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ + current_password: 'ancien-mot-de-passe', + new_password: 'un-nouveau-mot-de-passe', + }) + expect(wrapper.text()).toContain('Mot de passe modifié') + expect((wrapper.find('#current').element as HTMLInputElement).value).toBe('') + }) + + it('affiche l’erreur sur le mot de passe actuel', async () => { + await signIn() + mockFetch(jsonResponse(400, { current_password: ['Mot de passe actuel incorrect.'] })) + const wrapper = mountWithPlugins(AccountView) + await wrapper.find('#current').setValue('faux') + await wrapper.find('#next').setValue('un-nouveau-mot-de-passe') + await wrapper.find('#confirm').setValue('un-nouveau-mot-de-passe') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.find('#current').classes()).toContain('is-invalid') + expect(wrapper.text()).toContain('Mot de passe actuel incorrect.') + }) +}) diff --git a/frontend/src/__tests__/passwordReset.spec.ts b/frontend/src/__tests__/passwordReset.spec.ts new file mode 100644 index 0000000..9b04bbd --- /dev/null +++ b/frontend/src/__tests__/passwordReset.spec.ts @@ -0,0 +1,156 @@ +import { flushPromises } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { resetAuth } from '@/composables/useAuth' +import ForgotPasswordView from '@/views/ForgotPasswordView.vue' +import LoginView from '@/views/LoginView.vue' +import ResetPasswordView from '@/views/ResetPasswordView.vue' + +import { jsonResponse, makeRouter, mockFetch, mountWithPlugins } from './helpers' + +beforeEach(resetAuth) +afterEach(() => { + vi.unstubAllGlobals() + history.replaceState(null, '') +}) + +const NEW_PASSWORD = 'un-tout-nouveau-mot-de-passe' + +describe('ForgotPasswordView', () => { + it('envoie la demande puis affiche « Vérifiez votre boîte mail »', async () => { + const fetch = mockFetch(jsonResponse(202), jsonResponse(202)) + const wrapper = mountWithPlugins(ForgotPasswordView) + + await wrapper.find('#email').setValue('medecin@exemple.be') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(fetch.mock.calls[0]![0]).toBe('/api/v1/auth/password-reset/') + expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ + email: 'medecin@exemple.be', + }) + expect(wrapper.find('h1').text()).toBe('Vérifiez votre boîte mail') + expect(wrapper.text()).toContain('Si un compte existe pour medecin@exemple.be') + + await wrapper.find('button').trigger('click') + await flushPromises() + expect(fetch).toHaveBeenCalledTimes(2) + expect(wrapper.find('button').attributes('disabled')).toBeDefined() + }) + + it('signale la limitation de débit', async () => { + mockFetch(jsonResponse(429, { detail: 'Throttled' })) + const wrapper = mountWithPlugins(ForgotPasswordView) + await wrapper.find('#email').setValue('medecin@exemple.be') + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(wrapper.find('[role="alert"]').text()).toContain('Trop de demandes') + }) +}) + +describe('ResetPasswordView', () => { + async function mountWithToken(token: string | null, ...responses: Response[]) { + const fetch = mockFetch(...responses) + const router = makeRouter() + await router.push(token ? `/reinitialisation/${token}` : '/reinitialisation') + const push = vi.spyOn(router, 'push') + const wrapper = mountWithPlugins(ResetPasswordView, { router }) + await flushPromises() + return { wrapper, router, fetch, push } + } + + it('vérifie le lien, retire le jeton de l’URL et affiche le formulaire', async () => { + const { wrapper, router, fetch } = await mountWithToken('Mw.abc-123', jsonResponse(204)) + expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ token: 'Mw.abc-123' }) + expect(router.currentRoute.value.fullPath).toBe('/reinitialisation') + expect(wrapper.find('h1').text()).toBe('Nouveau mot de passe') + }) + + it('lien invalide ou expiré : propose un nouveau lien', async () => { + const { wrapper } = await mountWithToken( + 'vieux', + jsonResponse(400, { code: 'invalid_token', detail: '' }), + ) + expect(wrapper.find('h1').text()).toBe('Lien invalide ou expiré') + expect(wrapper.find('a.btn').attributes('href')).toBe('/mot-de-passe-oublie') + }) + + it('sans jeton : lien invalide, sans appel à l’API', async () => { + const { wrapper, fetch } = await mountWithToken(null) + expect(wrapper.find('h1').text()).toBe('Lien invalide ou expiré') + expect(fetch).not.toHaveBeenCalled() + }) + + it('enregistre le mot de passe puis renvoie à la connexion avec un message', async () => { + const { wrapper, fetch, push } = await mountWithToken( + 'Mw.abc-123', + jsonResponse(204), + jsonResponse(204), + ) + push.mockResolvedValue(undefined) + await wrapper.find('#password').setValue(NEW_PASSWORD) + await wrapper.find('#confirm').setValue(NEW_PASSWORD) + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(fetch.mock.calls[1]![0]).toBe('/api/v1/auth/password-reset/confirm/') + expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ + token: 'Mw.abc-123', + new_password: NEW_PASSWORD, + }) + expect(push).toHaveBeenCalledWith({ name: 'login', state: { notice: 'password-reset' } }) + }) + + it('bloque l’envoi si les mots de passe diffèrent ou sont trop courts', async () => { + const { wrapper } = await mountWithToken('Mw.abc-123', jsonResponse(204)) + const button = () => wrapper.find('button[type="submit"]') + await wrapper.find('#password').setValue(NEW_PASSWORD) + await wrapper.find('#confirm').setValue('autre-mot-de-passe-long') + expect(button().attributes('disabled')).toBeDefined() + expect(wrapper.find('#confirm').classes()).toContain('is-invalid') + await wrapper.find('#password').setValue('court') + await wrapper.find('#confirm').setValue('court') + expect(button().attributes('disabled')).toBeDefined() + }) + + it('affiche le refus du mot de passe par le serveur', async () => { + const { wrapper } = await mountWithToken( + 'Mw.abc-123', + jsonResponse(204), + jsonResponse(400, { new_password: ['Ce mot de passe est trop courant.'] }), + ) + await wrapper.find('#password').setValue(NEW_PASSWORD) + await wrapper.find('#confirm').setValue(NEW_PASSWORD) + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(wrapper.find('#password').classes()).toContain('is-invalid') + expect(wrapper.text()).toContain('Ce mot de passe est trop courant.') + }) + + it('lien devenu invalide entre-temps : écran « Lien invalide »', async () => { + const { wrapper } = await mountWithToken( + 'Mw.abc-123', + jsonResponse(204), + jsonResponse(400, { code: 'invalid_token', detail: '' }), + ) + await wrapper.find('#password').setValue(NEW_PASSWORD) + await wrapper.find('#confirm').setValue(NEW_PASSWORD) + await wrapper.find('form').trigger('submit') + await flushPromises() + expect(wrapper.find('h1').text()).toBe('Lien invalide ou expiré') + }) +}) + +describe('LoginView', () => { + it('propose le lien « Mot de passe oublié ? »', () => { + const wrapper = mountWithPlugins(LoginView) + const link = wrapper.findAll('a').find((a) => a.text() === 'Mot de passe oublié ?') + expect(link?.attributes('href')).toBe('/mot-de-passe-oublie') + }) + + it('affiche la confirmation après réinitialisation', () => { + history.replaceState({ notice: 'password-reset' }, '') + const wrapper = mountWithPlugins(LoginView) + expect(wrapper.find('[role="status"]').text()).toContain('Votre mot de passe a été modifié') + }) +}) diff --git a/frontend/src/__tests__/registration.spec.ts b/frontend/src/__tests__/registration.spec.ts new file mode 100644 index 0000000..0d88013 --- /dev/null +++ b/frontend/src/__tests__/registration.spec.ts @@ -0,0 +1,151 @@ +import { flushPromises } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { resetAuth } from '@/composables/useAuth' +import RegisterStatusView from '@/views/RegisterStatusView.vue' +import RegisterView from '@/views/RegisterView.vue' + +import { jsonResponse, makeRouter, mockFetch, mountWithPlugins } from './helpers' + +beforeEach(resetAuth) +afterEach(() => { + vi.unstubAllGlobals() + history.replaceState(null, '') +}) + +const PASSWORD = 'un-mot-de-passe-solide' + +async function fill(wrapper: ReturnType, overrides = {}) { + const values = { + '#first_name': 'Marie', + '#last_name': 'Curie', + '#email': 'marie@exemple.be', + '#inami': '', + '#password': PASSWORD, + '#confirm': PASSWORD, + ...overrides, + } + for (const [selector, value] of Object.entries(values)) { + await wrapper.find(selector).setValue(value) + } + await wrapper.find('#terms').setValue(true) +} + +describe('RegisterView', () => { + it('envoie la demande puis affiche « Vérifiez votre boîte mail » sans e-mail dans l’URL', async () => { + const fetch = mockFetch(jsonResponse(201)) + const router = makeRouter() + const push = vi.spyOn(router, 'push').mockResolvedValue(undefined) + const wrapper = mountWithPlugins(RegisterView, { router }) + + await fill(wrapper) + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ + first_name: 'Marie', + last_name: 'Curie', + email: 'marie@exemple.be', + inami_number: '', + password: PASSWORD, + accept_terms: true, + }) + expect(push).toHaveBeenCalledWith({ + name: 'register-status', + state: { email: 'marie@exemple.be' }, + }) + }) + + it('bloque l’envoi si les mots de passe diffèrent, sont trop courts ou sans conditions', async () => { + const wrapper = mountWithPlugins(RegisterView) + const button = () => wrapper.find('button[type="submit"]') + + await fill(wrapper, { '#confirm': 'autre-mot-de-passe' }) + expect(button().attributes('disabled')).toBeDefined() + expect(wrapper.find('#confirm').classes()).toContain('is-invalid') + + await fill(wrapper, { '#password': 'court', '#confirm': 'court' }) + expect(button().attributes('disabled')).toBeDefined() + + await fill(wrapper) + expect(button().attributes('disabled')).toBeUndefined() + await wrapper.find('#terms').setValue(false) + expect(button().attributes('disabled')).toBeDefined() + }) + + it('affiche les erreurs de validation du serveur sous chaque champ', async () => { + mockFetch( + jsonResponse(400, { + password: ['Ce mot de passe est trop courant.'], + email: ['Saisissez une adresse e-mail valide.'], + }), + ) + const wrapper = mountWithPlugins(RegisterView) + await fill(wrapper) + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.find('[role="alert"]').text()).toBe('Corrigez les champs signalés.') + expect(wrapper.find('#password').classes()).toContain('is-invalid') + expect(wrapper.text()).toContain('Ce mot de passe est trop courant.') + expect(wrapper.text()).toContain('Saisissez une adresse e-mail valide.') + }) +}) + +describe('RegisterStatusView', () => { + async function mountAt(path: string, state?: Record) { + const router = makeRouter() + await router.push(router.resolve(path)).catch(() => {}) + if (state) history.replaceState(state, '') + const wrapper = mountWithPlugins(RegisterStatusView, { router }) + await flushPromises() + return { wrapper, router } + } + + it('après inscription : « Vérifiez votre boîte mail » et renvoi par e-mail', async () => { + const fetch = mockFetch(jsonResponse(202)) + const { wrapper } = await mountAt('/inscription/statut', { email: 'marie@exemple.be' }) + + expect(wrapper.find('h1').text()).toBe('Vérifiez votre boîte mail') + expect(wrapper.text()).toContain('marie@exemple.be') + + await wrapper.find('button').trigger('click') + await flushPromises() + expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ + email: 'marie@exemple.be', + }) + expect(wrapper.find('button').attributes('disabled')).toBeDefined() + expect(wrapper.text()).toContain('un nouvel e-mail vient d’être envoyé'.replace('’', "'")) + }) + + it('lien valide : adresse confirmée et jeton retiré de l’URL', async () => { + const fetch = mockFetch(jsonResponse(200, { status: 'approval_pending' })) + const { wrapper, router } = await mountAt('/inscription/statut?jeton=abc') + + expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ token: 'abc' }) + expect(wrapper.find('h1').text()).toBe('Adresse confirmée') + expect(router.currentRoute.value.fullPath).toBe('/inscription/statut') + }) + + it('lien expiré : renvoi à partir du jeton', async () => { + const fetch = mockFetch( + jsonResponse(400, { code: 'expired_token', detail: 'Ce lien a expiré.' }), + jsonResponse(202), + ) + const { wrapper } = await mountAt('/inscription/statut?jeton=vieux') + + expect(wrapper.find('h1').text()).toBe('Lien expiré') + await wrapper.find('button').trigger('click') + await flushPromises() + expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ token: 'vieux' }) + }) + + it.each([ + ['invalid_token', 'Lien invalide'], + ['used_token', 'Adresse confirmée'], + ])('%s → « %s »', async (code, title) => { + mockFetch(jsonResponse(400, { code, detail: '' })) + const { wrapper } = await mountAt('/inscription/statut?jeton=x') + expect(wrapper.find('h1').text()).toBe(title) + }) +}) diff --git a/frontend/src/__tests__/router.spec.ts b/frontend/src/__tests__/router.spec.ts index 221b10e..2b37618 100644 --- a/frontend/src/__tests__/router.spec.ts +++ b/frontend/src/__tests__/router.spec.ts @@ -36,6 +36,32 @@ describe('garde de navigation', () => { expect(route.name).toBe('not-found') }) + it('protège /compte et laisse /inscription aux visiteurs', async () => { + mockFetch(jsonResponse(403, {})) + expect((await navigate('/compte')).name).toBe('login') + resetAuth() + mockFetch(jsonResponse(403, {})) + expect((await navigate('/inscription')).name).toBe('register') + }) + + it('renvoie un utilisateur connecté de /inscription vers l’évaluation', async () => { + mockFetch(jsonResponse(200, USER)) + expect((await navigate('/inscription')).name).toBe('assessment') + }) + + it('laisse /inscription/statut ouverte à tous (lien reçu par e-mail)', async () => { + mockFetch(jsonResponse(200, USER)) + expect((await navigate('/inscription/statut')).name).toBe('register-status') + }) + + it('mot de passe oublié réservé aux visiteurs, lien de réinitialisation ouvert à tous', async () => { + mockFetch(jsonResponse(200, USER)) + expect((await navigate('/mot-de-passe-oublie')).name).toBe('assessment') + resetAuth() + mockFetch(jsonResponse(200, USER)) + expect((await navigate('/reinitialisation/abc')).name).toBe('reset-password') + }) + it('laisse la page 403 publique', async () => { mockFetch(jsonResponse(403, {})) expect((await navigate('/403')).name).toBe('forbidden') diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index e615b3b..84d19e1 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -5,7 +5,7 @@ * pour toutes les requêtes qui modifient l'état. */ -import type { Assessment, User } from './types' +import type { Assessment, LoginResult, RegisterPayload, TotpSetup, User } from './types' const BASE = '/api/v1' @@ -22,6 +22,15 @@ export class ApiError extends Error { get code(): string | undefined { return typeof this.body.code === 'string' ? this.body.code : undefined } + + /** Messages de validation par champ (réponse 400 de DRF). */ + fieldErrors(): Record { + const errors: Record = {} + for (const [field, value] of Object.entries(this.body)) { + if (Array.isArray(value) && typeof value[0] === 'string') errors[field] = value.join(' ') + } + return errors + } } export function csrfToken(): string { @@ -56,7 +65,28 @@ async function request(method: string, path: string, body?: unknown): Promise export const api = { me: () => request('GET', '/auth/me/'), login: (email: string, password: string) => - request<{ mfa_required: boolean; user: User }>('POST', '/auth/login/', { email, password }), + request('POST', '/auth/login/', { email, password }), + verifyMfa: (code: string) => request('POST', '/auth/2fa/verify/', { code }), logout: () => request('POST', '/auth/logout/'), + register: (payload: RegisterPayload) => request('POST', '/auth/register/', payload), + verifyEmail: (token: string) => + request<{ status: string }>('POST', '/auth/verify-email/', { token }), + resendVerification: (target: { email?: string; token?: string }) => + request('POST', '/auth/verify-email/resend/', target), + changePassword: (current_password: string, new_password: string) => + request('POST', '/auth/password/change/', { current_password, new_password }), + requestPasswordReset: (email: string) => + request('POST', '/auth/password-reset/', { email }), + validateResetToken: (token: string) => + request('POST', '/auth/password-reset/validate/', { token }), + resetPassword: (token: string, new_password: string) => + request('POST', '/auth/password-reset/confirm/', { token, new_password }), + setupTotp: () => request('POST', '/auth/2fa/setup/'), + enableTotp: (code: string) => + request<{ recovery_codes: string[] }>('POST', '/auth/2fa/enable/', { code }), + disableTotp: (password: string, code: string) => + request('POST', '/auth/2fa/disable/', { password, code }), + regenerateRecoveryCodes: (code: string) => + request<{ recovery_codes: string[] }>('POST', '/auth/2fa/recovery-codes/', { code }), assess: (address: string) => request('POST', '/assessments/', { address }), } diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index ef7de7f..cdcbe1d 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -8,6 +8,27 @@ export interface User { last_name: string roles: string[] is_staff: boolean + mfa_enabled: boolean +} + +export interface LoginResult { + mfa_required: boolean + user: User | null +} + +export interface RegisterPayload { + first_name: string + last_name: string + email: string + inami_number: string + password: string + accept_terms: boolean +} + +export interface TotpSetup { + secret: string + otpauth_url: string + qr_code: string } export interface Detail { diff --git a/frontend/src/components/AppHeader.vue b/frontend/src/components/AppHeader.vue index 4898966..5ec279b 100644 --- a/frontend/src/components/AppHeader.vue +++ b/frontend/src/components/AppHeader.vue @@ -30,6 +30,9 @@ async function onLogout() {