Ajoute les pages de compte au front et le favicon de la SSMG

- 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 <noreply@anthropic.com>
This commit is contained in:
boris.waaubandClaude Opus 5.5 committed 2026-11-24 13:27:34 +01:00
1 parent d2da878dbd
commit 0617fa8dc4
29 files changed
+2305 -58

No files matched your search

+8 -2
View File
@@ -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 pytest # tests (HTTP mocké avec respx)
docker compose exec web sh -c 'ruff check . && ruff format --check .' 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 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`. 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) : 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/`) ## Architecture (`backend/`)
- `config/` : settings (tout par variables d'environnement via django-environ). URL et couches des sources externes dans `PRISM_SOURCES`. - `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). - `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/` : - `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. - `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/`) ## 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). É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).
+1 -1
View File
@@ -70,7 +70,7 @@ Tests et qualité : `docker compose exec web pytest`, `docker compose exec web r
## État du projet ## État du projet
- Spécifications et maquettes : en cours de validation. - 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. - Échéance de la Phase 1 : livraison avant le 31 décembre 2026.
## Licence ## Licence
+4 -1
View File
@@ -2,7 +2,10 @@
<html lang="fr"> <html lang="fr">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<link rel="icon" href="/favicon.ico"> <!-- Favicon de la SSMG (ssmg.be) -->
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
<link rel="icon" type="image/png" sizes="57x57" href="/favicon-57.png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PRISM – Environnement et santé</title> <title>PRISM – Environnement et santé</title>
</head> </head>
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

+68
View File
@@ -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: '<CodeInput v-model="code" label="Code" @complete="completed.push($event)" />',
})
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()
})
})
+1
View File
@@ -13,6 +13,7 @@ export const USER: User = {
last_name: 'Dupont', last_name: 'Dupont',
roles: ['Médecin'], roles: ['Médecin'],
is_staff: false, is_staff: false,
mfa_enabled: false,
} }
export function factor(overrides: Partial<FactorResult> = {}): FactorResult { export function factor(overrides: Partial<FactorResult> = {}): FactorResult {
+245
View File
@@ -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<typeof mountWithPlugins>, 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.')
})
})
@@ -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é')
})
})
+151
View File
@@ -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<typeof mountWithPlugins>, 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<string, unknown>) {
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)
})
})
+26
View File
@@ -36,6 +36,32 @@ describe('garde de navigation', () => {
expect(route.name).toBe('not-found') 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 () => { it('laisse la page 403 publique', async () => {
mockFetch(jsonResponse(403, {})) mockFetch(jsonResponse(403, {}))
expect((await navigate('/403')).name).toBe('forbidden') expect((await navigate('/403')).name).toBe('forbidden')
+32 -2
View File
@@ -5,7 +5,7 @@
* pour toutes les requêtes qui modifient l'état. * 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' const BASE = '/api/v1'
@@ -22,6 +22,15 @@ export class ApiError extends Error {
get code(): string | undefined { get code(): string | undefined {
return typeof this.body.code === 'string' ? this.body.code : undefined return typeof this.body.code === 'string' ? this.body.code : undefined
} }
/** Messages de validation par champ (réponse 400 de DRF). */
fieldErrors(): Record<string, string> {
const errors: Record<string, string> = {}
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 { export function csrfToken(): string {
@@ -56,7 +65,28 @@ async function request<T>(method: string, path: string, body?: unknown): Promise
export const api = { export const api = {
me: () => request<User>('GET', '/auth/me/'), me: () => request<User>('GET', '/auth/me/'),
login: (email: string, password: string) => login: (email: string, password: string) =>
request<{ mfa_required: boolean; user: User }>('POST', '/auth/login/', { email, password }), request<LoginResult>('POST', '/auth/login/', { email, password }),
verifyMfa: (code: string) => request<LoginResult>('POST', '/auth/2fa/verify/', { code }),
logout: () => request<void>('POST', '/auth/logout/'), logout: () => request<void>('POST', '/auth/logout/'),
register: (payload: RegisterPayload) => request<void>('POST', '/auth/register/', payload),
verifyEmail: (token: string) =>
request<{ status: string }>('POST', '/auth/verify-email/', { token }),
resendVerification: (target: { email?: string; token?: string }) =>
request<void>('POST', '/auth/verify-email/resend/', target),
changePassword: (current_password: string, new_password: string) =>
request<void>('POST', '/auth/password/change/', { current_password, new_password }),
requestPasswordReset: (email: string) =>
request<void>('POST', '/auth/password-reset/', { email }),
validateResetToken: (token: string) =>
request<void>('POST', '/auth/password-reset/validate/', { token }),
resetPassword: (token: string, new_password: string) =>
request<void>('POST', '/auth/password-reset/confirm/', { token, new_password }),
setupTotp: () => request<TotpSetup>('POST', '/auth/2fa/setup/'),
enableTotp: (code: string) =>
request<{ recovery_codes: string[] }>('POST', '/auth/2fa/enable/', { code }),
disableTotp: (password: string, code: string) =>
request<void>('POST', '/auth/2fa/disable/', { password, code }),
regenerateRecoveryCodes: (code: string) =>
request<{ recovery_codes: string[] }>('POST', '/auth/2fa/recovery-codes/', { code }),
assess: (address: string) => request<Assessment>('POST', '/assessments/', { address }), assess: (address: string) => request<Assessment>('POST', '/assessments/', { address }),
} }
+21
View File
@@ -8,6 +8,27 @@ export interface User {
last_name: string last_name: string
roles: string[] roles: string[]
is_staff: boolean 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 { export interface Detail {
+21
View File
@@ -30,6 +30,9 @@ async function onLogout() {
<template v-if="user"> <template v-if="user">
<nav class="d-none d-md-flex align-items-center gap-4"> <nav class="d-none d-md-flex align-items-center gap-4">
<span class="text-muted-prism">{{ $t('nav.doctor', { name: user.last_name }) }}</span> <span class="text-muted-prism">{{ $t('nav.doctor', { name: user.last_name }) }}</span>
<RouterLink :to="{ name: 'account' }" class="nav-account">{{
$t('nav.account')
}}</RouterLink>
<button type="button" class="btn btn-link nav-logout p-0" @click="onLogout"> <button type="button" class="btn btn-link nav-logout p-0" @click="onLogout">
{{ $t('nav.logout') }} {{ $t('nav.logout') }}
</button> </button>
@@ -47,6 +50,13 @@ async function onLogout() {
</button> </button>
<div v-if="menuOpen" class="menu-overlay prism-card"> <div v-if="menuOpen" class="menu-overlay prism-card">
<p class="mb-2 text-muted-prism">{{ $t('nav.doctor', { name: user.last_name }) }}</p> <p class="mb-2 text-muted-prism">{{ $t('nav.doctor', { name: user.last_name }) }}</p>
<RouterLink
:to="{ name: 'account' }"
class="nav-account d-block mb-2"
@click="menuOpen = false"
>
{{ $t('nav.account') }}
</RouterLink>
<button type="button" class="btn btn-link nav-logout p-0" @click="onLogout"> <button type="button" class="btn btn-link nav-logout p-0" @click="onLogout">
{{ $t('nav.logout') }} {{ $t('nav.logout') }}
</button> </button>
@@ -118,6 +128,17 @@ async function onLogout() {
color: var(--prism-text); color: var(--prism-text);
} }
.nav-account {
color: var(--prism-navy);
font-weight: 500;
text-decoration: none;
}
.nav-account:hover,
.nav-account.router-link-active {
text-decoration: underline;
}
.nav-logout { .nav-logout {
color: var(--prism-orange); color: var(--prism-orange);
font-weight: 500; font-weight: 500;
+109
View File
@@ -0,0 +1,109 @@
<script setup lang="ts">
import { nextTick, ref } from 'vue'
/** Saisie d'un code à 6 chiffres en 6 cases (maquettes 13 et 14). Accepte le collage. */
const props = withDefaults(defineProps<{ length?: number; label: string; autofocus?: boolean }>(), {
length: 6,
autofocus: false,
})
const emit = defineEmits<{ complete: [code: string] }>()
const model = defineModel<string>({ default: '' })
const inputs = ref<HTMLInputElement[]>([])
const digits = ref<string[]>(Array.from({ length: props.length }, (_, i) => model.value[i] ?? ''))
function sync() {
// On teste la chaîne locale : `model.value` n'est mis à jour qu'au rendu du parent.
const code = digits.value.join('')
model.value = code
if (code.length === props.length) emit('complete', code)
}
function focus(index: number) {
void nextTick(() => inputs.value[Math.max(0, Math.min(index, props.length - 1))]?.focus())
}
function onInput(index: number, event: Event) {
const value = (event.target as HTMLInputElement).value.replace(/\D/g, '')
if (value.length > 1) {
fill(index, value)
return
}
digits.value[index] = value
sync()
if (value) focus(index + 1)
}
function fill(start: number, value: string) {
for (const [offset, char] of [...value].entries()) {
if (start + offset < props.length) digits.value[start + offset] = char
}
sync()
focus(start + value.length)
}
function onPaste(index: number, event: ClipboardEvent) {
const text = event.clipboardData?.getData('text').replace(/\D/g, '') ?? ''
if (!text) return
event.preventDefault()
fill(index, text)
}
function onKeydown(index: number, event: KeyboardEvent) {
if (event.key === 'Backspace' && !digits.value[index]) focus(index - 1)
if (event.key === 'ArrowLeft') focus(index - 1)
if (event.key === 'ArrowRight') focus(index + 1)
}
function clear() {
digits.value = digits.value.map(() => '')
sync()
focus(0)
}
defineExpose({ clear })
</script>
<template>
<div class="code-input" role="group" :aria-label="label">
<input
v-for="(_, index) in digits"
:key="index"
ref="inputs"
v-model="digits[index]"
type="text"
inputmode="numeric"
maxlength="6"
:autocomplete="index === 0 ? 'one-time-code' : 'off'"
:autofocus="autofocus && index === 0"
:aria-label="`${label} – chiffre ${index + 1}`"
class="form-control digit"
@input="onInput(index, $event)"
@paste="onPaste(index, $event)"
@keydown="onKeydown(index, $event)"
/>
</div>
</template>
<style scoped>
.code-input {
display: flex;
gap: 10px;
}
.digit {
width: 52px;
height: 60px;
padding: 0;
text-align: center;
font-size: 1.5rem;
font-weight: 500;
}
@media (max-width: 400px) {
.digit {
width: 42px;
height: 52px;
}
}
</style>
+266
View File
@@ -0,0 +1,266 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { api, ApiError } from '@/api/client'
import type { TotpSetup } from '@/api/types'
import { useAuth } from '@/composables/useAuth'
import AlertBanner from './AlertBanner.vue'
import CodeInput from './CodeInput.vue'
import RecoveryCodes from './RecoveryCodes.vue'
type Mode = 'idle' | 'setup' | 'codes' | 'disable' | 'regenerate'
const { user, load } = useAuth()
const { t } = useI18n()
const mode = ref<Mode>('idle')
const setup = ref<TotpSetup | null>(null)
const codes = ref<string[]>([])
const code = ref('')
const password = ref('')
const error = ref('')
const loading = ref(false)
const done = ref('')
function reset(next: Mode = 'idle') {
mode.value = next
code.value = ''
password.value = ''
error.value = ''
}
function message(e: unknown) {
if (e instanceof ApiError && e.status === 400) return e.message
if (e instanceof ApiError && e.status === 429) return t('login.throttled')
return t('account.error')
}
async function run(action: () => Promise<void>) {
error.value = ''
loading.value = true
try {
await action()
} catch (e) {
error.value = message(e)
} finally {
loading.value = false
}
}
const start = () =>
run(async () => {
done.value = ''
setup.value = await api.setupTotp()
reset('setup')
})
const enable = () =>
run(async () => {
codes.value = (await api.enableTotp(code.value)).recovery_codes
setup.value = null
reset('codes')
})
const disable = () =>
run(async () => {
await api.disableTotp(password.value, code.value)
await load(true)
reset()
done.value = t('account.mfa.disabled')
})
const regenerate = () =>
run(async () => {
codes.value = (await api.regenerateRecoveryCodes(code.value)).recovery_codes
reset('codes')
})
async function finish() {
codes.value = []
await load(true)
reset()
done.value = t('account.mfa.enabledDone')
}
</script>
<template>
<section class="prism-card panel" aria-labelledby="mfa-heading">
<!-- Étape 1 et 2 de l'activation (maquette 14) -->
<template v-if="mode === 'setup' && setup">
<h2 id="mfa-heading" class="card-title">{{ $t('account.mfa.setupTitle') }}</h2>
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
<div class="row g-4">
<div class="col-12">
<h3 class="step">{{ $t('account.mfa.step1') }}</h3>
<p class="small-text">{{ $t('account.mfa.step1Text') }}</p>
<img :src="setup.qr_code" :alt="$t('account.mfa.qrAlt')" class="qr" />
<p class="secret">
{{ $t('account.mfa.secret') }} <span class="font-monospace">{{ setup.secret }}</span>
</p>
</div>
<div class="col-12">
<h3 class="step">{{ $t('account.mfa.step2') }}</h3>
<p class="small-text">{{ $t('account.mfa.step2Text') }}</p>
<form @submit.prevent="enable">
<CodeInput v-model="code" class="mb-3" :label="$t('mfa.codeLabel')" />
<button
type="submit"
class="btn btn-primary action"
:disabled="loading || code.length !== 6"
>
{{ $t('account.mfa.activate') }}
</button>
</form>
<button type="button" class="btn btn-link link-strong px-0 mt-2" @click="reset()">
{{ $t('account.cancel') }}
</button>
</div>
</div>
</template>
<!-- Codes de secours (maquette 15) -->
<RecoveryCodes v-else-if="mode === 'codes'" :codes="codes" @done="finish" />
<template v-else>
<div class="d-flex align-items-start justify-content-between gap-3 mb-3">
<h2 id="mfa-heading" class="card-title mb-0">{{ $t('account.mfa.title') }}</h2>
<span class="status" :class="{ on: user?.mfa_enabled }">
{{ user?.mfa_enabled ? $t('account.mfa.on') : $t('account.mfa.off') }}
</span>
</div>
<AlertBanner v-if="done" variant="info" class="mb-3">{{ done }}</AlertBanner>
<AlertBanner v-if="user?.is_staff && !user.mfa_enabled" variant="error" class="mb-3">
{{ $t('account.mfa.mandatory') }}
</AlertBanner>
<template v-if="!user?.mfa_enabled">
<p>{{ $t('account.mfa.explain') }}</p>
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
<button type="button" class="btn btn-outline-primary" :disabled="loading" @click="start">
{{ $t('account.mfa.enable') }}
</button>
</template>
<template v-else>
<p>{{ $t('account.mfa.enabledText') }}</p>
<form
v-if="mode === 'regenerate' || mode === 'disable'"
class="mt-3"
@submit.prevent="mode === 'disable' ? disable() : regenerate()"
>
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
<div v-if="mode === 'disable'" class="mb-3">
<label for="mfa-password" class="form-label">{{ $t('account.currentPassword') }}</label>
<input
id="mfa-password"
v-model="password"
type="password"
class="form-control"
autocomplete="current-password"
/>
</div>
<label for="mfa-code" class="form-label">
{{ mode === 'disable' ? $t('account.mfa.codeOrRecovery') : $t('mfa.codeLabel') }}
</label>
<input
id="mfa-code"
v-model.trim="code"
class="form-control mb-3"
autocomplete="one-time-code"
:inputmode="mode === 'disable' ? 'text' : 'numeric'"
/>
<div class="d-flex flex-wrap gap-3 align-items-center">
<button
type="submit"
class="btn"
:class="mode === 'disable' ? 'btn-danger' : 'btn-primary'"
:disabled="loading || !code || (mode === 'disable' && !password)"
>
{{ mode === 'disable' ? $t('account.mfa.disable') : $t('account.mfa.regenerate') }}
</button>
<button type="button" class="btn btn-link link-strong px-0" @click="reset()">
{{ $t('account.cancel') }}
</button>
</div>
</form>
<div v-else class="d-flex flex-wrap gap-3">
<button type="button" class="btn btn-outline-primary" @click="reset('regenerate')">
{{ $t('account.mfa.regenerate') }}
</button>
<button
v-if="!user.is_staff"
type="button"
class="btn btn-link link-strong px-0"
@click="reset('disable')"
>
{{ $t('account.mfa.disable') }}
</button>
</div>
</template>
</template>
</section>
</template>
<style scoped>
.panel {
padding: 24px 28px;
}
.card-title {
font-size: 1.25rem;
margin-bottom: 1.25rem;
}
.step {
font-size: 1rem;
margin-bottom: 0.75rem;
}
.small-text {
font-size: 0.8125rem;
}
.qr {
width: 200px;
height: 200px;
padding: 10px;
border: 1px solid var(--prism-border);
border-radius: 8px;
background: #fff;
}
.secret {
margin-top: 1rem;
font-size: 0.8125rem;
font-weight: 500;
color: var(--prism-navy);
}
.action {
min-width: 160px;
}
.status {
display: inline-flex;
align-items: center;
height: 28px;
padding: 0 14px;
border-radius: 14px;
border: 1px solid var(--prism-border);
background: var(--prism-bg);
font-size: 0.8125rem;
font-weight: 500;
white-space: nowrap;
}
.status.on {
background: var(--prism-level-1);
border-color: var(--prism-level-1);
color: #fff;
}
</style>
+97
View File
@@ -0,0 +1,97 @@
<script setup lang="ts">
import { ref } from 'vue'
const props = defineProps<{ codes: string[] }>()
const emit = defineEmits<{ done: [] }>()
const saved = ref(false)
const copied = ref(false)
async function copy() {
await navigator.clipboard.writeText(props.codes.join('\n'))
copied.value = true
}
function download() {
const blob = new Blob([`Codes de secours PRISM\n\n${props.codes.join('\n')}\n`], {
type: 'text/plain',
})
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = 'prism-codes-de-secours.txt'
link.click()
URL.revokeObjectURL(url)
}
</script>
<template>
<div>
<h2 class="card-title">{{ $t('account.mfa.codesTitle') }}</h2>
<p>{{ $t('account.mfa.codesText', { count: codes.length }) }}</p>
<div class="codes-warning" role="status">{{ $t('account.mfa.codesWarning') }}</div>
<ul class="codes list-unstyled">
<li v-for="code in codes" :key="code" class="font-monospace">{{ code }}</li>
</ul>
<div class="d-flex flex-wrap gap-3 mb-4">
<button type="button" class="btn btn-outline-primary action" @click="copy">
{{ copied ? $t('account.mfa.copied') : $t('account.mfa.copy') }}
</button>
<button type="button" class="btn btn-outline-primary action" @click="download">
{{ $t('account.mfa.download') }}
</button>
</div>
<hr />
<div class="form-check mb-3">
<input id="codes-saved" v-model="saved" class="form-check-input" type="checkbox" />
<label for="codes-saved" class="form-check-label">{{ $t('account.mfa.saved') }}</label>
</div>
<button type="button" class="btn btn-primary action" :disabled="!saved" @click="emit('done')">
{{ $t('account.mfa.finish') }}
</button>
</div>
</template>
<style scoped>
.card-title {
font-size: 1.25rem;
margin-bottom: 1.25rem;
}
.codes-warning {
background: #fdf0e6;
color: #7a3b0e;
font-weight: 500;
border-radius: 6px;
padding: 0.6rem 0.875rem;
margin-bottom: 1.25rem;
}
.codes {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
margin-bottom: 1.25rem;
}
.codes li {
background: var(--prism-bg);
border: 1px solid var(--prism-border);
border-radius: 6px;
padding: 0.7rem 0.875rem;
font-size: 1rem;
color: var(--prism-navy);
}
.action {
min-width: 160px;
}
.form-check-input:checked {
background-color: var(--prism-orange);
border-color: var(--prism-orange);
}
</style>
+12 -4
View File
@@ -26,12 +26,19 @@ export function useAuth() {
return user.value return user.value
} }
async function login(email: string, password: string): Promise<User> { /** Étape 1. Renvoie `true` si un second facteur est demandé. */
async function login(email: string, password: string): Promise<boolean> {
const result = await api.login(email, password) const result = await api.login(email, password)
user.value = result.user if (result.mfa_required) return true
// Django renouvelle le jeton CSRF à la connexion : on le recharge. // Django renouvelle le jeton CSRF à la connexion : on recharge l'utilisateur (et le jeton).
await load(true)
return false
}
/** Étape 2 : code TOTP ou code de secours. */
async function verifyMfa(code: string): Promise<void> {
await api.verifyMfa(code)
await load(true) await load(true)
return result.user
} }
async function logout(): Promise<void> { async function logout(): Promise<void> {
@@ -48,6 +55,7 @@ export function useAuth() {
isAuthenticated: computed(() => user.value !== null), isAuthenticated: computed(() => user.value !== null),
load, load,
login, login,
verifyMfa,
logout, logout,
} }
} }
+128 -2
View File
@@ -9,7 +9,8 @@
"nav": { "nav": {
"doctor": "Dr {name}", "doctor": "Dr {name}",
"logout": "Déconnexion", "logout": "Déconnexion",
"menu": "Menu" "menu": "Menu",
"account": "Mon compte"
}, },
"login": { "login": {
"title": "Connexion", "title": "Connexion",
@@ -19,7 +20,11 @@
"password": "Mot de passe", "password": "Mot de passe",
"submit": "Se connecter", "submit": "Se connecter",
"submitting": "Connexion…", "submitting": "Connexion…",
"error": "Connexion impossible. Réessayez dans un instant." "error": "Connexion impossible. Réessayez dans un instant.",
"noAccount": "Pas encore de compte ?",
"createAccount": "Créer un compte",
"throttled": "Trop de tentatives. Réessayez dans une minute.",
"forgot": "Mot de passe oublié ?"
}, },
"assessment": { "assessment": {
"addressLabel": "Adresse du patient", "addressLabel": "Adresse du patient",
@@ -81,5 +86,126 @@
"text": "Vous n'avez pas les droits nécessaires pour accéder à cette page." "text": "Vous n'avez pas les droits nécessaires pour accéder à cette page."
}, },
"back": "Retour à l'évaluation" "back": "Retour à l'évaluation"
},
"mfa": {
"title": "Vérification en deux étapes",
"intro": "Saisissez le code à 6 chiffres affiché par votre application d'authentification.",
"recoveryIntro": "Saisissez l'un de vos codes de secours. Chaque code ne fonctionne qu'une fois.",
"codeLabel": "Code de vérification",
"recoveryLabel": "Code de secours",
"submit": "Valider",
"useRecovery": "Utiliser un code de secours",
"useApp": "Utiliser l'application d'authentification",
"back": "Retour à la connexion"
},
"register": {
"title": "Créer un compte",
"intro": "Réservé aux médecins généralistes. Votre demande sera validée par la cellule Environnement de la SSMG.",
"firstName": "Prénom",
"lastName": "Nom",
"inami": "Numéro INAMI (facultatif)",
"passwordRules": "12 caractères minimum. Évitez les mots de passe courants ou proches de votre nom.",
"confirm": "Confirmer le mot de passe",
"mismatch": "Les deux mots de passe ne correspondent pas.",
"terms": "J'accepte les conditions d'utilisation et la politique de confidentialité.",
"submit": "Créer mon compte",
"submitting": "Envoi…",
"haveAccount": "Déjà un compte ? Se connecter",
"fixErrors": "Corrigez les champs signalés.",
"throttled": "Trop de demandes depuis cette connexion. Réessayez plus tard.",
"error": "La demande n'a pas pu être envoyée. Réessayez dans un instant."
},
"registerStatus": {
"loading": "Vérification du lien…",
"sent": {
"title": "Vérifiez votre boîte mail",
"textTo": "Un lien de confirmation a été envoyé à {email}.",
"text": "Un lien de confirmation vient de vous être envoyé.",
"hint": "Le lien est valable 24 heures. Pensez à vérifier vos courriers indésirables."
},
"confirmed": {
"title": "Adresse confirmée",
"text": "Votre demande est en attente de validation par la cellule Environnement de la SSMG. Vous recevrez un e-mail dès qu'elle sera traitée."
},
"expired": {
"title": "Lien expiré",
"text": "Ce lien de confirmation n'est plus valable. Demandez un nouvel e-mail."
},
"invalid": {
"title": "Lien invalide",
"text": "Ce lien de confirmation n'est pas valide. Vérifiez que vous l'avez copié en entier."
},
"resend": "Renvoyer l'e-mail",
"resent": "Si une demande est en attente pour cette adresse, un nouvel e-mail vient d'être envoyé.",
"toLogin": "Aller à la connexion",
"restart": "Créer un compte"
},
"account": {
"title": "Mon compte",
"passwordTitle": "Changer le mot de passe",
"currentPassword": "Mot de passe actuel",
"newPassword": "Nouveau mot de passe",
"confirmPassword": "Confirmer le nouveau mot de passe",
"save": "Enregistrer",
"passwordSaved": "Mot de passe modifié. Un e-mail de confirmation vous a été envoyé.",
"cancel": "Annuler",
"error": "L'opération a échoué. Réessayez dans un instant.",
"mfa": {
"title": "Double authentification",
"on": "Activée",
"off": "Désactivée",
"explain": "Ajoutez une seconde étape de vérification à la connexion avec une application d'authentification. Elle protège l'accès aux données de vos patients.",
"enabledText": "Un code de votre application d'authentification est demandé à chaque connexion.",
"mandatory": "La double authentification est obligatoire pour votre compte : activez-la pour accéder à l'espace d'administration.",
"enable": "Activer la double authentification",
"setupTitle": "Activer la double authentification",
"step1": "1. Scannez le QR code",
"step1Text": "Avec une application d'authentification (Google Authenticator, Microsoft Authenticator, Authy, 1Password…).",
"qrAlt": "QR code à scanner avec l'application d'authentification",
"secret": "Ou saisissez la clé :",
"step2": "2. Saisissez le code",
"step2Text": "Entrez le code à 6 chiffres affiché dans l'application pour confirmer.",
"activate": "Activer",
"codesTitle": "Codes de secours",
"codesText": "Conservez ces {count} codes dans un endroit sûr. Chacun ne fonctionne qu'une seule fois et ne sera plus affiché.",
"codesWarning": "Enregistrez vos codes avant de continuer : ils permettent de vous connecter si vous perdez votre téléphone.",
"copy": "Copier",
"copied": "Copié",
"download": "Télécharger",
"saved": "J'ai enregistré mes codes de secours.",
"finish": "Terminer",
"enabledDone": "La double authentification est activée.",
"regenerate": "Régénérer les codes de secours",
"disable": "Désactiver",
"disabled": "La double authentification est désactivée.",
"codeOrRecovery": "Code de l'application ou code de secours"
}
},
"forgot": {
"title": "Mot de passe oublié",
"intro": "Saisissez l'adresse e-mail de votre compte. Si elle existe, nous vous enverrons un lien de réinitialisation valable 1 heure.",
"submit": "Envoyer le lien",
"submitting": "Envoi…",
"sentTitle": "Vérifiez votre boîte mail",
"sentText": "Si un compte existe pour {email}, un e-mail vient d'être envoyé. Le lien est valable 1 heure.",
"resend": "Renvoyer l'e-mail",
"resent": "Un nouvel e-mail a été demandé.",
"back": "Retour à la connexion",
"throttled": "Trop de demandes depuis cette connexion. Réessayez plus tard.",
"error": "La demande n'a pas pu être envoyée. Réessayez dans un instant."
},
"reset": {
"title": "Nouveau mot de passe",
"intro": "Choisissez un mot de passe d'au moins 12 caractères.",
"password": "Nouveau mot de passe",
"confirm": "Confirmer le mot de passe",
"submit": "Enregistrer le mot de passe",
"submitting": "Enregistrement…",
"checking": "Vérification du lien…",
"invalidTitle": "Lien invalide ou expiré",
"invalidText": "Ce lien de réinitialisation n'est plus valable. Demandez-en un nouveau.",
"newLink": "Demander un nouveau lien",
"done": "Votre mot de passe a été modifié. Connectez-vous avec le nouveau mot de passe.",
"error": "Le mot de passe n'a pas pu être enregistré. Réessayez dans un instant."
} }
} }
+31
View File
@@ -24,6 +24,36 @@ export const routes: RouteRecordRaw[] = [
component: () => import('@/views/LoginView.vue'), component: () => import('@/views/LoginView.vue'),
meta: { guestOnly: true }, meta: { guestOnly: true },
}, },
{
path: '/inscription',
name: 'register',
component: () => import('@/views/RegisterView.vue'),
meta: { guestOnly: true },
},
{
// Ouverte depuis l'e-mail de confirmation : accessible connecté ou non.
path: '/inscription/statut',
name: 'register-status',
component: () => import('@/views/RegisterStatusView.vue'),
},
{
path: '/mot-de-passe-oublie',
name: 'forgot-password',
component: () => import('@/views/ForgotPasswordView.vue'),
meta: { guestOnly: true },
},
{
// Ouverte depuis l'e-mail ; le jeton est retiré de l'URL dès l'arrivée sur la page.
path: '/reinitialisation/:jeton?',
name: 'reset-password',
component: () => import('@/views/ResetPasswordView.vue'),
},
{
path: '/compte',
name: 'account',
component: () => import('@/views/AccountView.vue'),
meta: { requiresAuth: true },
},
{ {
path: '/403', path: '/403',
name: 'forbidden', name: 'forbidden',
@@ -42,6 +72,7 @@ export function createAppRouter() {
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
routes, routes,
scrollBehavior: (_to, _from, saved) => saved ?? { top: 0 },
}) })
router.beforeEach(async (to) => { router.beforeEach(async (to) => {
+76
View File
@@ -137,3 +137,79 @@ h3 {
background: var(--level-color); background: var(--level-color);
flex-shrink: 0; flex-shrink: 0;
} }
/* Pages d'accès (connexion, inscription…) ---------------------------------- */
.auth-page {
display: flex;
justify-content: center;
padding: 100px 16px;
}
.auth-card {
width: 100%;
max-width: 460px;
padding: 40px 39px;
}
.auth-card.wide {
max-width: 560px;
}
.auth-card h1 {
font-size: 1.75rem;
margin-bottom: 1.25rem;
}
.auth-card .intro {
margin-bottom: 1.5rem;
}
.auth-links {
text-align: center;
margin-top: 1.25rem;
}
.link-strong {
color: var(--prism-orange);
font-weight: 500;
text-decoration: none;
}
.link-strong:hover {
text-decoration: underline;
}
.icon-circle {
display: flex;
align-items: center;
justify-content: center;
width: 72px;
height: 72px;
margin: 0 auto 1.5rem;
border-radius: 50%;
background: var(--prism-info-bg);
color: var(--prism-navy);
font-size: 1.25rem;
font-weight: 700;
}
.icon-circle.warning {
background: #fdf0e6;
color: var(--prism-level-3);
font-size: 1.75rem;
}
.form-text {
color: var(--prism-muted);
font-size: 0.75rem;
}
@media (max-width: 575.98px) {
.auth-page {
padding: 32px 16px;
}
.auth-card {
padding: 28px 20px;
}
}
+186
View File
@@ -0,0 +1,186 @@
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { api, ApiError } from '@/api/client'
import AlertBanner from '@/components/AlertBanner.vue'
import MfaPanel from '@/components/MfaPanel.vue'
import { useAuth } from '@/composables/useAuth'
const { user } = useAuth()
const { t } = useI18n()
const initials = computed(() =>
`${user.value?.first_name[0] ?? ''}${user.value?.last_name[0] ?? ''}`.toUpperCase(),
)
const form = reactive({ current: '', next: '', confirm: '' })
const errors = ref<Record<string, string>>({})
const saved = ref(false)
const loading = ref(false)
const mismatch = computed(() => form.confirm !== '' && form.confirm !== form.next)
async function changePassword() {
errors.value = {}
saved.value = false
loading.value = true
try {
await api.changePassword(form.current, form.next)
Object.assign(form, { current: '', next: '', confirm: '' })
saved.value = true
} catch (e) {
errors.value =
e instanceof ApiError && e.status === 400
? e.fieldErrors()
: { new_password: t('account.error') }
} finally {
loading.value = false
}
}
</script>
<template>
<div v-if="user" class="account container-xxl">
<h1>{{ $t('account.title') }}</h1>
<section class="prism-card profile">
<span class="avatar" aria-hidden="true">{{ initials }}</span>
<div>
<p class="name">{{ $t('nav.doctor', { name: `${user.first_name} ${user.last_name}` }) }}</p>
<p class="meta">
{{ user.email
}}<template v-if="user.roles.length"> · {{ user.roles.join(', ') }}</template>
</p>
</div>
</section>
<div class="row g-4">
<div class="col-lg-6">
<section class="prism-card panel" aria-labelledby="password-heading">
<h2 id="password-heading" class="card-title">{{ $t('account.passwordTitle') }}</h2>
<AlertBanner v-if="saved" variant="info" class="mb-3">
{{ $t('account.passwordSaved') }}
</AlertBanner>
<form novalidate @submit.prevent="changePassword">
<div class="mb-3">
<label for="current" class="form-label">{{ $t('account.currentPassword') }}</label>
<input
id="current"
v-model="form.current"
type="password"
class="form-control"
:class="{ 'is-invalid': errors.current_password }"
autocomplete="current-password"
/>
<div class="invalid-feedback">{{ errors.current_password }}</div>
</div>
<div class="mb-3">
<label for="next" class="form-label">{{ $t('account.newPassword') }}</label>
<input
id="next"
v-model="form.next"
type="password"
class="form-control"
:class="{ 'is-invalid': errors.new_password }"
autocomplete="new-password"
aria-describedby="new-password-rules"
/>
<div class="invalid-feedback">{{ errors.new_password }}</div>
<div id="new-password-rules" class="form-text">
{{ $t('register.passwordRules') }}
</div>
</div>
<div class="mb-4">
<label for="confirm" class="form-label">{{ $t('account.confirmPassword') }}</label>
<input
id="confirm"
v-model="form.confirm"
type="password"
class="form-control"
:class="{ 'is-invalid': mismatch }"
autocomplete="new-password"
/>
<div class="invalid-feedback">{{ $t('register.mismatch') }}</div>
</div>
<button
type="submit"
class="btn btn-primary save"
:disabled="
loading || !form.current || form.next.length < 12 || form.next !== form.confirm
"
>
{{ $t('account.save') }}
</button>
</form>
</section>
</div>
<div class="col-lg-6">
<MfaPanel />
</div>
</div>
</div>
</template>
<style scoped>
.account {
max-width: 1440px;
padding: 40px 48px;
}
@media (max-width: 767.98px) {
.account {
padding: 24px 16px;
}
}
h1 {
font-size: 1.875rem;
margin-bottom: 1.5rem;
}
.profile {
display: flex;
align-items: center;
gap: 20px;
padding: 20px 28px;
margin-bottom: 24px;
}
.avatar {
display: flex;
align-items: center;
justify-content: center;
width: 56px;
height: 56px;
border-radius: 50%;
background: var(--prism-navy);
color: #fff;
font-size: 1.125rem;
font-weight: 700;
flex-shrink: 0;
}
.name {
margin: 0;
color: var(--prism-navy);
font-size: 1.125rem;
font-weight: 700;
}
.meta {
margin: 0;
}
.panel {
padding: 24px 28px;
}
.card-title {
font-size: 1.25rem;
margin-bottom: 1.25rem;
}
.save {
min-width: 160px;
}
</style>
+93
View File
@@ -0,0 +1,93 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { api, ApiError } from '@/api/client'
import AlertBanner from '@/components/AlertBanner.vue'
const { t } = useI18n()
const email = ref('')
const sent = ref(false)
const resent = ref(false)
const error = ref('')
const loading = ref(false)
async function send() {
error.value = ''
loading.value = true
try {
await api.requestPasswordReset(email.value)
resent.value = sent.value
sent.value = true
} catch (e) {
error.value =
e instanceof ApiError && e.status === 429
? t('forgot.throttled')
: e instanceof ApiError && e.status === 400
? (e.fieldErrors().email ?? t('forgot.error'))
: t('forgot.error')
} finally {
loading.value = false
}
}
</script>
<template>
<div class="auth-page">
<!-- Maquette 9 -->
<section v-if="!sent" class="auth-card wide prism-card" aria-labelledby="forgot-title">
<h1 id="forgot-title">{{ $t('forgot.title') }}</h1>
<p class="intro">{{ $t('forgot.intro') }}</p>
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
<form novalidate @submit.prevent="send">
<div class="mb-3">
<label for="email" class="form-label">{{ $t('login.email') }}</label>
<input
id="email"
v-model.trim="email"
type="email"
class="form-control"
autocomplete="username"
required
:placeholder="$t('login.emailPlaceholder')"
/>
</div>
<button type="submit" class="btn btn-primary w-100" :disabled="loading || !email">
{{ loading ? $t('forgot.submitting') : $t('forgot.submit') }}
</button>
</form>
<p class="auth-links mb-0">
<RouterLink :to="{ name: 'login' }" class="link-strong">{{ $t('forgot.back') }}</RouterLink>
</p>
</section>
<!-- Maquette 10 -->
<section
v-else
class="auth-card wide prism-card text-center"
aria-labelledby="sent-title"
aria-live="polite"
>
<div class="icon-circle" aria-hidden="true">@</div>
<h1 id="sent-title">{{ $t('forgot.sentTitle') }}</h1>
<p>{{ $t('forgot.sentText', { email }) }}</p>
<AlertBanner v-if="error" variant="error" class="mb-3 text-start">{{ error }}</AlertBanner>
<button
type="button"
class="btn btn-outline-primary w-100"
:disabled="loading || resent"
@click="send"
>
{{ $t('forgot.resend') }}
</button>
<p v-if="resent" class="text-success mt-2 mb-0" role="status">{{ $t('forgot.resent') }}</p>
<p class="auth-links mb-0">
<RouterLink :to="{ name: 'login' }" class="link-strong">{{ $t('forgot.back') }}</RouterLink>
</p>
</section>
</div>
</template>
+126 -46
View File
@@ -1,46 +1,100 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { ApiError } from '@/api/client' import { ApiError } from '@/api/client'
import AlertBanner from '@/components/AlertBanner.vue' import AlertBanner from '@/components/AlertBanner.vue'
import CodeInput from '@/components/CodeInput.vue'
import { useAuth } from '@/composables/useAuth' import { useAuth } from '@/composables/useAuth'
const { login } = useAuth() const { login, verifyMfa } = useAuth()
const router = useRouter() const router = useRouter()
const route = useRoute() const route = useRoute()
const { t } = useI18n()
const step = ref<'password' | 'code'>('password')
const useRecovery = ref(false)
const email = ref('') const email = ref('')
const password = ref('') const password = ref('')
const code = ref('')
const error = ref('') const error = ref('')
const loading = ref(false) const loading = ref(false)
// Message transmis par la page de réinitialisation (état de navigation, pas l'URL).
const notice = ref<string>(history.state?.notice === 'password-reset' ? t('reset.done') : '')
const codeInput = ref<InstanceType<typeof CodeInput>>()
async function onSubmit() { function message(e: unknown): string {
if (e instanceof ApiError && e.status === 429) return t('login.throttled')
if (e instanceof ApiError && e.status === 400) return e.message
return t('login.error')
}
async function done() {
const next = route.query.next
await router.push(
typeof next === 'string' && next.startsWith('/') && !next.startsWith('//')
? next
: { name: 'assessment' },
)
}
async function submitPassword() {
error.value = '' error.value = ''
loading.value = true loading.value = true
try { try {
await login(email.value, password.value) if (await login(email.value, password.value)) {
const next = typeof route.query.next === 'string' && route.query.next.startsWith('/') password.value = ''
await router.push(next ? (route.query.next as string) : { name: 'assessment' }) step.value = 'code'
} else {
await done()
}
} catch (e) { } catch (e) {
error.value = e instanceof ApiError && e.status === 400 ? e.message : 'login.error' error.value = message(e)
} finally { } finally {
loading.value = false loading.value = false
} }
} }
async function submitCode() {
if (!code.value) return
error.value = ''
loading.value = true
try {
await verifyMfa(code.value)
await done()
} catch (e) {
error.value = message(e)
if (e instanceof ApiError && e.code === 'mfa_expired') backToPassword()
else if (!useRecovery.value) codeInput.value?.clear()
} finally {
loading.value = false
}
}
function backToPassword() {
step.value = 'password'
code.value = ''
useRecovery.value = false
}
function toggleRecovery() {
useRecovery.value = !useRecovery.value
code.value = ''
error.value = ''
}
</script> </script>
<template> <template>
<div class="auth-page"> <div class="auth-page">
<section class="auth-card prism-card" aria-labelledby="login-title"> <section v-if="step === 'password'" class="auth-card prism-card" aria-labelledby="login-title">
<h1 id="login-title">{{ $t('login.title') }}</h1> <h1 id="login-title">{{ $t('login.title') }}</h1>
<p class="intro">{{ $t('login.intro') }}</p> <p class="intro">{{ $t('login.intro') }}</p>
<AlertBanner v-if="error" variant="error" class="mb-3"> <AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
{{ error === 'login.error' ? $t('login.error') : error }} <AlertBanner v-else-if="notice" variant="info" class="mb-3">{{ notice }}</AlertBanner>
</AlertBanner>
<form novalidate @submit.prevent="onSubmit"> <form novalidate @submit.prevent="submitPassword">
<div class="mb-3"> <div class="mb-3">
<label for="email" class="form-label">{{ $t('login.email') }}</label> <label for="email" class="form-label">{{ $t('login.email') }}</label>
<input <input
@@ -72,41 +126,67 @@ async function onSubmit() {
{{ loading ? $t('login.submitting') : $t('login.submit') }} {{ loading ? $t('login.submitting') : $t('login.submit') }}
</button> </button>
</form> </form>
<p class="auth-links mb-0">
<RouterLink :to="{ name: 'forgot-password' }" class="link-strong">
{{ $t('login.forgot') }}
</RouterLink>
</p>
<hr class="my-4" />
<p class="text-center mb-3">{{ $t('login.noAccount') }}</p>
<RouterLink :to="{ name: 'register' }" class="btn btn-outline-primary w-100">
{{ $t('login.createAccount') }}
</RouterLink>
</section>
<section v-else class="auth-card wide prism-card text-center" aria-labelledby="mfa-title">
<div class="icon-circle" aria-hidden="true">2FA</div>
<h1 id="mfa-title">{{ $t('mfa.title') }}</h1>
<p class="intro">
{{ useRecovery ? $t('mfa.recoveryIntro') : $t('mfa.intro') }}
</p>
<AlertBanner v-if="error" variant="error" class="mb-3 text-start">{{ error }}</AlertBanner>
<form novalidate @submit.prevent="submitCode">
<div v-if="useRecovery" class="mb-4 text-start">
<label for="recovery" class="form-label">{{ $t('mfa.recoveryLabel') }}</label>
<input
id="recovery"
v-model="code"
type="text"
class="form-control font-monospace"
autocomplete="off"
placeholder="ABCD-EFGH"
/>
</div>
<CodeInput
v-else
ref="codeInput"
v-model="code"
class="justify-content-center mb-4"
:label="$t('mfa.codeLabel')"
autofocus
@complete="submitCode"
/>
<button type="submit" class="btn btn-primary w-100" :disabled="loading || !code">
{{ $t('mfa.submit') }}
</button>
</form>
<p class="auth-links mb-2">
<button type="button" class="btn btn-link link-strong p-0" @click="toggleRecovery">
{{ useRecovery ? $t('mfa.useApp') : $t('mfa.useRecovery') }}
</button>
</p>
<button
type="button"
class="btn btn-link text-reset text-decoration-none p-0"
@click="backToPassword"
>
{{ $t('mfa.back') }}
</button>
</section> </section>
</div> </div>
</template> </template>
<style scoped>
.auth-page {
display: flex;
justify-content: center;
padding: 100px 16px;
}
@media (max-width: 575.98px) {
.auth-page {
padding: 32px 16px;
}
}
.auth-card {
width: 100%;
max-width: 460px;
padding: 40px 39px;
}
@media (max-width: 575.98px) {
.auth-card {
padding: 28px 20px;
}
}
h1 {
font-size: 1.75rem;
margin-bottom: 1.25rem;
}
.intro {
margin-bottom: 1.5rem;
}
</style>
+119
View File
@@ -0,0 +1,119 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api, ApiError } from '@/api/client'
type State = 'loading' | 'sent' | 'confirmed' | 'expired' | 'invalid' | 'used'
const route = useRoute()
const router = useRouter()
const state = ref<State>('loading')
const email = ref<string>((history.state?.email as string | undefined) ?? '')
const token = ref('')
const resent = ref(false)
const resending = ref(false)
onMounted(async () => {
const jeton = route.query.jeton
if (typeof jeton !== 'string' || !jeton) {
state.value = 'sent'
return
}
token.value = jeton
// Retire le jeton de la barre d'adresse et de l'historique.
await router.replace({ name: 'register-status' })
try {
await api.verifyEmail(jeton)
state.value = 'confirmed'
} catch (e) {
const code = e instanceof ApiError ? e.code : undefined
state.value = code === 'expired_token' ? 'expired' : code === 'used_token' ? 'used' : 'invalid'
}
})
async function resend() {
resending.value = true
try {
await api.resendVerification(token.value ? { token: token.value } : { email: email.value })
resent.value = true
} finally {
resending.value = false
}
}
const ICONS: Record<State, string> = {
loading: 'bi-hourglass-split',
sent: 'bi-envelope',
confirmed: 'bi-check-lg',
expired: 'bi-clock-history',
invalid: 'bi-x-lg',
used: 'bi-check-lg',
}
</script>
<template>
<div class="auth-page">
<section
class="auth-card wide prism-card text-center"
aria-labelledby="status-title"
aria-live="polite"
>
<div class="icon-circle" aria-hidden="true"><i class="bi" :class="ICONS[state]"></i></div>
<template v-if="state === 'loading'">
<h1 id="status-title">{{ $t('registerStatus.loading') }}</h1>
</template>
<template v-else-if="state === 'sent'">
<h1 id="status-title">{{ $t('registerStatus.sent.title') }}</h1>
<p v-if="email">{{ $t('registerStatus.sent.textTo', { email }) }}</p>
<p v-else>{{ $t('registerStatus.sent.text') }}</p>
<p class="form-text">{{ $t('registerStatus.sent.hint') }}</p>
<button
v-if="email"
type="button"
class="btn btn-outline-primary"
:disabled="resending || resent"
@click="resend"
>
{{ $t('registerStatus.resend') }}
</button>
</template>
<template v-else-if="state === 'confirmed' || state === 'used'">
<h1 id="status-title">{{ $t('registerStatus.confirmed.title') }}</h1>
<p>{{ $t('registerStatus.confirmed.text') }}</p>
<RouterLink :to="{ name: 'login' }" class="btn btn-primary">
{{ $t('registerStatus.toLogin') }}
</RouterLink>
</template>
<template v-else-if="state === 'expired'">
<h1 id="status-title">{{ $t('registerStatus.expired.title') }}</h1>
<p>{{ $t('registerStatus.expired.text') }}</p>
<button
type="button"
class="btn btn-primary"
:disabled="resending || resent"
@click="resend"
>
{{ $t('registerStatus.resend') }}
</button>
</template>
<template v-else>
<h1 id="status-title">{{ $t('registerStatus.invalid.title') }}</h1>
<p>{{ $t('registerStatus.invalid.text') }}</p>
<RouterLink :to="{ name: 'register' }" class="btn btn-outline-primary">
{{ $t('registerStatus.restart') }}
</RouterLink>
</template>
<p v-if="resent" class="text-success mt-3 mb-0" role="status">
{{ $t('registerStatus.resent') }}
</p>
</section>
</div>
</template>
+196
View File
@@ -0,0 +1,196 @@
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { api, ApiError } from '@/api/client'
import AlertBanner from '@/components/AlertBanner.vue'
const router = useRouter()
const { t } = useI18n()
const form = reactive({
first_name: '',
last_name: '',
email: '',
inami_number: '',
password: '',
confirm: '',
accept_terms: false,
})
const errors = ref<Record<string, string>>({})
const error = ref('')
const loading = ref(false)
const mismatch = computed(() => form.confirm !== '' && form.confirm !== form.password)
const canSubmit = computed(
() =>
form.first_name &&
form.last_name &&
form.email &&
form.password.length >= 12 &&
form.password === form.confirm &&
form.accept_terms,
)
async function submit() {
errors.value = {}
error.value = ''
loading.value = true
try {
await api.register({
first_name: form.first_name,
last_name: form.last_name,
email: form.email,
inami_number: form.inami_number,
password: form.password,
accept_terms: form.accept_terms,
})
// L'adresse du médecin passe par l'état de navigation, pas par l'URL.
await router.push({ name: 'register-status', state: { email: form.email } })
} catch (e) {
if (e instanceof ApiError && e.status === 400) {
errors.value = e.fieldErrors()
error.value = errors.value.non_field_errors ?? t('register.fixErrors')
} else if (e instanceof ApiError && e.status === 429) {
error.value = t('register.throttled')
} else {
error.value = t('register.error')
}
} finally {
loading.value = false
}
}
</script>
<template>
<div class="auth-page register-page">
<section class="auth-card wide prism-card" aria-labelledby="register-title">
<h1 id="register-title">{{ $t('register.title') }}</h1>
<p class="intro">{{ $t('register.intro') }}</p>
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
<form novalidate @submit.prevent="submit">
<div class="row g-3 mb-3">
<div class="col-sm-6">
<label for="first_name" class="form-label">{{ $t('register.firstName') }}</label>
<input
id="first_name"
v-model.trim="form.first_name"
class="form-control"
:class="{ 'is-invalid': errors.first_name }"
autocomplete="given-name"
placeholder="Jean"
required
/>
<div class="invalid-feedback">{{ errors.first_name }}</div>
</div>
<div class="col-sm-6">
<label for="last_name" class="form-label">{{ $t('register.lastName') }}</label>
<input
id="last_name"
v-model.trim="form.last_name"
class="form-control"
:class="{ 'is-invalid': errors.last_name }"
autocomplete="family-name"
placeholder="Dupont"
required
/>
<div class="invalid-feedback">{{ errors.last_name }}</div>
</div>
</div>
<div class="mb-3">
<label for="email" class="form-label">{{ $t('login.email') }}</label>
<input
id="email"
v-model.trim="form.email"
type="email"
class="form-control"
:class="{ 'is-invalid': errors.email }"
autocomplete="email"
:placeholder="$t('login.emailPlaceholder')"
required
/>
<div class="invalid-feedback">{{ errors.email }}</div>
</div>
<div class="mb-3">
<label for="inami" class="form-label">{{ $t('register.inami') }}</label>
<input
id="inami"
v-model.trim="form.inami_number"
class="form-control"
:class="{ 'is-invalid': errors.inami_number }"
placeholder="1-23456-78-901"
/>
<div class="invalid-feedback">{{ errors.inami_number }}</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">{{ $t('login.password') }}</label>
<input
id="password"
v-model="form.password"
type="password"
class="form-control"
:class="{ 'is-invalid': errors.password }"
autocomplete="new-password"
aria-describedby="password-rules"
required
/>
<div class="invalid-feedback">{{ errors.password }}</div>
<div id="password-rules" class="form-text">{{ $t('register.passwordRules') }}</div>
</div>
<div class="mb-3">
<label for="confirm" class="form-label">{{ $t('register.confirm') }}</label>
<input
id="confirm"
v-model="form.confirm"
type="password"
class="form-control"
:class="{ 'is-invalid': mismatch }"
autocomplete="new-password"
required
/>
<div class="invalid-feedback">{{ $t('register.mismatch') }}</div>
</div>
<div class="form-check mb-4">
<input
id="terms"
v-model="form.accept_terms"
class="form-check-input"
:class="{ 'is-invalid': errors.accept_terms }"
type="checkbox"
/>
<label class="form-check-label" for="terms">{{ $t('register.terms') }}</label>
<div class="invalid-feedback">{{ errors.accept_terms }}</div>
</div>
<button type="submit" class="btn btn-primary w-100" :disabled="loading || !canSubmit">
{{ loading ? $t('register.submitting') : $t('register.submit') }}
</button>
</form>
<p class="auth-links mb-0">
<RouterLink :to="{ name: 'login' }" class="link-strong">
{{ $t('register.haveAccount') }}
</RouterLink>
</p>
</section>
</div>
</template>
<style scoped>
.register-page {
padding-top: 32px;
}
.form-check-input:checked {
background-color: var(--prism-orange);
border-color: var(--prism-orange);
}
</style>
+132
View File
@@ -0,0 +1,132 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { api, ApiError } from '@/api/client'
import AlertBanner from '@/components/AlertBanner.vue'
const route = useRoute()
const router = useRouter()
const { t } = useI18n()
// Le jeton reste en mémoire : il est retiré de la barre d'adresse et de l'historique.
const token = ref('')
const state = ref<'checking' | 'form' | 'invalid'>('checking')
const password = ref('')
const confirm = ref('')
const errors = ref<Record<string, string>>({})
const error = ref('')
const loading = ref(false)
const mismatch = computed(() => confirm.value !== '' && confirm.value !== password.value)
onMounted(async () => {
const jeton = route.params.jeton
if (typeof jeton !== 'string' || !jeton) {
state.value = 'invalid'
return
}
token.value = jeton
await router.replace({ name: 'reset-password' })
try {
await api.validateResetToken(jeton)
state.value = 'form'
} catch {
state.value = 'invalid'
}
})
async function submit() {
errors.value = {}
error.value = ''
loading.value = true
try {
await api.resetPassword(token.value, password.value)
await router.push({ name: 'login', state: { notice: 'password-reset' } })
} catch (e) {
if (e instanceof ApiError && e.code === 'invalid_token') {
state.value = 'invalid'
} else if (e instanceof ApiError && e.status === 400) {
errors.value = e.fieldErrors()
} else {
error.value = t('reset.error')
}
} finally {
loading.value = false
}
}
</script>
<template>
<div class="auth-page">
<section
v-if="state === 'checking'"
class="auth-card wide prism-card text-center"
aria-live="polite"
>
<p class="mb-0">{{ $t('reset.checking') }}</p>
</section>
<!-- Maquette 11 -->
<section
v-else-if="state === 'form'"
class="auth-card wide prism-card"
aria-labelledby="reset-title"
>
<h1 id="reset-title">{{ $t('reset.title') }}</h1>
<p class="intro">{{ $t('reset.intro') }}</p>
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
<form novalidate @submit.prevent="submit">
<div class="mb-3">
<label for="password" class="form-label">{{ $t('reset.password') }}</label>
<input
id="password"
v-model="password"
type="password"
class="form-control"
:class="{ 'is-invalid': errors.new_password }"
autocomplete="new-password"
aria-describedby="password-rules"
/>
<div class="invalid-feedback">{{ errors.new_password }}</div>
<div id="password-rules" class="form-text">{{ $t('register.passwordRules') }}</div>
</div>
<div class="mb-4">
<label for="confirm" class="form-label">{{ $t('reset.confirm') }}</label>
<input
id="confirm"
v-model="confirm"
type="password"
class="form-control"
:class="{ 'is-invalid': mismatch }"
autocomplete="new-password"
/>
<div class="invalid-feedback">{{ $t('register.mismatch') }}</div>
</div>
<button
type="submit"
class="btn btn-primary w-100"
:disabled="loading || password.length < 12 || password !== confirm"
>
{{ loading ? $t('reset.submitting') : $t('reset.submit') }}
</button>
</form>
</section>
<!-- Maquette 12 -->
<section v-else class="auth-card wide prism-card text-center" aria-labelledby="invalid-title">
<div class="icon-circle warning" aria-hidden="true">!</div>
<h1 id="invalid-title">{{ $t('reset.invalidTitle') }}</h1>
<p>{{ $t('reset.invalidText') }}</p>
<RouterLink :to="{ name: 'forgot-password' }" class="btn btn-primary w-100">
{{ $t('reset.newLink') }}
</RouterLink>
<p class="auth-links mb-0">
<RouterLink :to="{ name: 'login' }" class="link-strong">{{ $t('forgot.back') }}</RouterLink>
</p>
</section>
</div>
</template>