From 0617fa8dc4a9d4804c71ca6d1bfb8ec72af56bec Mon Sep 17 00:00:00 2001 From: Boris Waaub Date: Tue, 24 Nov 2026 13:27:34 +0100 Subject: [PATCH] Ajoute les pages de compte au front et le favicon de la SSMG MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Inscription, suivi de l'inscription (lien de confirmation), seconde étape de connexion (code à 6 chiffres ou code de secours), mot de passe oublié et réinitialisation, page « Mon compte » (mot de passe, 2FA avec QR code et codes de secours), d'après les maquettes Penpot. - Les jetons reçus par e-mail sont retirés de l'URL dès l'arrivée. - Favicon de la SSMG (ssmg.be) ; retour en haut de page à chaque navigation. - 93 tests Vitest ; README et CLAUDE.md mis à jour. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 10 +- README.md | 2 +- frontend/index.html | 5 +- frontend/public/apple-touch-icon.png | Bin 0 -> 6913 bytes frontend/public/favicon-32.png | Bin 0 -> 1055 bytes frontend/public/favicon-57.png | Bin 0 -> 2462 bytes frontend/public/favicon.ico | Bin 4286 -> 0 bytes frontend/src/__tests__/CodeInput.spec.ts | 68 +++++ frontend/src/__tests__/helpers.ts | 1 + frontend/src/__tests__/mfa.spec.ts | 245 +++++++++++++++++ frontend/src/__tests__/passwordReset.spec.ts | 156 +++++++++++ frontend/src/__tests__/registration.spec.ts | 151 +++++++++++ frontend/src/__tests__/router.spec.ts | 26 ++ frontend/src/api/client.ts | 34 ++- frontend/src/api/types.ts | 21 ++ frontend/src/components/AppHeader.vue | 21 ++ frontend/src/components/CodeInput.vue | 109 ++++++++ frontend/src/components/MfaPanel.vue | 266 +++++++++++++++++++ frontend/src/components/RecoveryCodes.vue | 97 +++++++ frontend/src/composables/useAuth.ts | 16 +- frontend/src/locales/fr.json | 130 ++++++++- frontend/src/router/index.ts | 31 +++ frontend/src/styles/main.css | 76 ++++++ frontend/src/views/AccountView.vue | 186 +++++++++++++ frontend/src/views/ForgotPasswordView.vue | 93 +++++++ frontend/src/views/LoginView.vue | 172 ++++++++---- frontend/src/views/RegisterStatusView.vue | 119 +++++++++ frontend/src/views/RegisterView.vue | 196 ++++++++++++++ frontend/src/views/ResetPasswordView.vue | 132 +++++++++ 29 files changed, 2305 insertions(+), 58 deletions(-) create mode 100644 frontend/public/apple-touch-icon.png create mode 100644 frontend/public/favicon-32.png create mode 100644 frontend/public/favicon-57.png delete mode 100644 frontend/public/favicon.ico create mode 100644 frontend/src/__tests__/CodeInput.spec.ts create mode 100644 frontend/src/__tests__/mfa.spec.ts create mode 100644 frontend/src/__tests__/passwordReset.spec.ts create mode 100644 frontend/src/__tests__/registration.spec.ts create mode 100644 frontend/src/components/CodeInput.vue create mode 100644 frontend/src/components/MfaPanel.vue create mode 100644 frontend/src/components/RecoveryCodes.vue create mode 100644 frontend/src/views/AccountView.vue create mode 100644 frontend/src/views/ForgotPasswordView.vue create mode 100644 frontend/src/views/RegisterStatusView.vue create mode 100644 frontend/src/views/RegisterView.vue create mode 100644 frontend/src/views/ResetPasswordView.vue 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 0000000000000000000000000000000000000000..7fbc9c2b478aa88f9467e54cedfd7ad6ae68ec61 GIT binary patch literal 6913 zcmV+c8~)^pP)Po3n7yhMg+amE0+$!6xySp1rLJWrhfhJfIh`T+# zGIM_adG`_eLP{ZlE)?GPb3b>tZSP5TGG)g(pftWZyWZ5j z*g9bd+l2X-^`#M6aHLv}3{Zxo41TRvuoP%FVXX>F_eE8Mk_Dx+BZDc$+CLlX%BvA( zN3<%MbiLPNKczrRR~J*7ygtX@)a1sW5r+I`1Hjl0vWp5jE(6VB%1~NC^YQ-b3I-!g zE9gBjM8`U82U1$mr4}Wdlqo0^l)?us;0+eSw1!4Ay^C}6%Ga^PHt~3U=jE7`2Bp=R zDd|`1mes;EJP6YgN?;ntG+7)`V5EZ?+hV@U???w_urq@l>Ygr=E9wxYC6p*SB{9W< zCZOvY`86Q%mq_qaMW7Tx8Pbsnnj=qLj3!|sOb8UmG+sKABtE@@&zFbY#nC)sa|SX(B=p&1C%BY z&f+|`i7?I3?@iB-L*!_7B(h^XQ@nJHgCo_L0O;5{x{$*b)=~;P0!0^S4(`ttEOmsj zAqbJrUrs<|RA4l4Cb1R;8q2f*V{5B?*g8ws6h^K9rJBJsw(}e;s%r|Sz+nhrNLk{_ znj{ak&8o1aI7!h=pO-vk>7K2pv0`+Ypk$_WI5L!9z9JV!IAH(Kst_pkE}M*_l+8re z#RXAV?En$f|tojemeii|zDm_s5amt&SAXvwrAYZA{11Ui|f+@k7 z%Y;|=g|)VZy~vv-PkDwZ!Optk*fExsv?SfI&)!{8VjX?|_-}^YbT9p4`yT zfMy7ifI}?nJ-=TdK&Ub+Gn+N{{2nv7n?t*g90qzJL=N^ujIveDAESq(z`P zn^J+9>W+u-$j*R5N(diCm8UU}v2yYKGWwJU9f&p!JM zHpEO|jiE7XkRbDr%xZ+ z4lcd)QYoda6(_ZY9 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>>=aS>DaWt^?mmhrfG$>?hvw}WNOj3Ps+%o;OQ*TkFKYs#bK>Ggw@dWsr#iU zPy)0#IHRB~vpxXAT6c`bDtuzyI?gTxqTxv7PUXnN9>Ml>T<@00000NkvXX Hu0mjfS(2t1 literal 0 HcmV?d00001 diff --git a/frontend/public/favicon-32.png b/frontend/public/favicon-32.png new file mode 100644 index 0000000000000000000000000000000000000000..a9a1e89d17d96066da1b318bb66741fcdfad59b2 GIT binary patch literal 1055 zcmV+)1mOFLP)Wac}m#;BP-L-8BUNyu_HHi@nx zm@`0A6e{SDrMs)}zq^bnOv^x5M$yVkq|?hX-NJ@2vzCE}#tpqdUi?j@I~iu8OAsVM zvjBj{$wxba{G_x7Q()tSDegwi0!&T<@Y-;4Ajm)UHGpTKVRTdBB?)C9%d(rBn<$FJ znA&&>;JJ99H7MES1%R$6PYFhL&d$y{oeo9edEUjvW#7JiUw!pe)v8t11_AQ{5{(A| z+!NOi0Lh|R7Yn*0i&iVriK1AqUOih|+aG@TVc4)?t5&T#fByW*lP8ZIJ9h5exq}A} zjvqh1YuB!I>eTt`ufHf=rAn1HZ{Eyt906eLwI~xat_QGz>$Xn%Kol+2@0c&gWCj#P zNk~Yzc=6)!;lqFX?YB=p`NTe5m3066-~ZI`j2Sb=jvbqE>76@wrlzJM9U-078lr%J zX_6$3lsO0Ru3V{5p~9RwbJR9+B4i_4-2no3&0YU&2FT_{{FQhV z>H78SM6`0{$^yqhb}4#4fJBS$H4LvA*|Fu5eEz@e?``YWtwgkI*De%*kcXt~1ni=u zd$UmO^QZTCQ9%J7KYmO^>L*3P2%->v;xzA~ll3XcqM$C6mUl3`e*8br6Ok_`CnqA> zuwg?{BiU@gfIsmmS%0o-*tbfyS^$_$ydv90quU@<*b(7_Jd8#o5%uiZvsiPHBABG8 zK;yaH__>>mR zj3$ZIErJ=@s3VSuJUu;841}B%CQDoAfyk7cVt~7c>8&10r4Y+KWKoAG5v^FU0>wkf zk8whu`1d|Ei57Qha_^KHM-zJ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RGU6gI{v2~|)p}sG5x0U*z<8U;Ij*hB9z?ei z@g6Xq-pDoPl=MANPiR7%172VA%r)kevtV-_5H*QJKFmd;8yA$98zCxBZYXTNZ#QFk2(TX0;Y2dt&WitL#$96|gJY=3xX zpCoi|YNzgO3R`f@IiEeSmKrPSf#h#Qd<$%Ej^RIeeYfsxhPMOG`S`Pz8q``=511zm zAm)MX5AV^5xIWPyEu7u>qYs?pn$I4nL9J!=K=SGlKLXpE<5x+2cDTXq?brj?n6sp= zphe9;_JHf40^9~}9i08r{XM$7HB!`{Ys~TK0kx<}ZQng`UPvH*11|q7&l9?@FQz;8 zx!=3<4seY*%=OlbCbcae?5^V_}*K>Uo6ZWV8mTyE^B=DKy7-sdLYkR5Z?paTgK-zyIkKjIcpyO z{+uIt&YSa_$QnN_@t~L014dyK(fOOo+W*MIxbA6Ndgr=Y!f#Tokqv}n<7-9qfHkc3 z=>a|HWqcX8fzQCT=dqVbogRq!-S>H%yA{1w#2Pn;=e>JiEj7Hl;zdt-2f+j2%DeVD zsW0Ab)ZK@0cIW%W7z}H{&~yGhn~D;aiP4=;m-HCo`BEI+Kd6 z={Xwx{TKxD#iCLfl2vQGDitKtN>z|-AdCN|$jTFDg0m3O`WLD4_s#$S 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() {