Files
PRISM/frontend/src/__tests__/mfa.spec.ts
T
boris.waaubandClaude Opus 5.5 0617fa8dc4 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>
2026-11-24 13:27:34 +01:00

246 lines
9.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.')
})
})