Skip to content

Commit 098e264

Browse files
authored
feat: offer ProConnect on the reauthentication page (#1318)
- Require opendatateam/udata#4062 Accounts without password can confirm their identity with ProConnect on `/verify`, then go on to the page they came from.
1 parent e90e64f commit 098e264

6 files changed

Lines changed: 179 additions & 37 deletions

File tree

‎components/ProConnectButton.vue‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<template>
2+
<form :action="`${config.public.apiBase}${ACTION_PATHS[action]}`">
3+
<div class="fr-connect-group flex flex-col items-center">
4+
<button class="fr-connect">
5+
<span class="fr-connect__login">{{ label }}</span>
6+
<span class="fr-connect__brand">ProConnect</span>
7+
</button>
8+
<p>
9+
<CdataLink
10+
:href="config.public.proconnect.homepage"
11+
target="_blank"
12+
rel="noopener"
13+
>
14+
{{ $t(`Qu'est-ce que ProConnect ?`) }}
15+
</CdataLink>
16+
</p>
17+
</div>
18+
</form>
19+
</template>
20+
21+
<script setup lang="ts">
22+
const ACTION_PATHS = {
23+
login: '/api/1/proconnect/login/',
24+
reauth: '/api/1/proconnect/reauth/',
25+
} as const
26+
27+
defineProps<{
28+
label: string
29+
action: keyof typeof ACTION_PATHS
30+
}>()
31+
32+
const config = useRuntimeConfig()
33+
</script>

‎components/SiteHeader/SiteHeader.vue‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,10 @@ onMounted(() => {
624624
change_email_expired: { type: 'error', text: t('Le code de vérification de votre adresse email a expiré, un nouveau mail vous a été envoyé.') },
625625
change_email_invalid: { type: 'error', text: t('Le code de vérification de votre adresse email est incorrect.') },
626626
change_email_already_taken: { type: 'error', text: t('Cette adresse email est déjà utilisée par un autre compte. Votre adresse email n\'a pas été modifiée.') },
627+
proconnect_reauth_success: { type: 'success', text: t('Compte confirmé.') },
628+
proconnect_reauth_failed: { type: 'error', text: t('La confirmation de votre identité avec ProConnect a échoué. Veuillez réessayer.') },
629+
proconnect_reauth_unavailable: { type: 'error', text: t('Votre session n’a pas été ouverte avec ProConnect : confirmez votre identité avec votre mot de passe.') },
630+
proconnect_reauth_identity_mismatch: { type: 'error', text: t('Vous vous êtes identifié sur ProConnect avec une autre adresse email que celle de ce compte ({email}).', { email: me.value?.email ?? '' }) },
627631
}
628632
629633
if (route.query.flash) {

‎components/User/TwoFactorSetupModal.vue‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
size="lg"
66
form
77
@submit.prevent="($el, _close) => submit(_close)"
8-
@open="fetchStatusAndQRCode"
98
>
109
<template #button="{ attrs, listeners }">
1110
<BrandedButton
@@ -89,12 +88,29 @@
8988
<script setup lang="ts">
9089
import { BrandedButton, SimpleBanner, toast } from '@datagouv/components-next'
9190
import { RiShieldCheckLine } from '@remixicon/vue'
91+
import { FetchError } from 'ofetch'
9292
import RequiredExplanation from '~/components/RequiredExplanation/RequiredExplanation.vue'
9393
9494
const { t } = useTranslation()
9595
const me = useMe()
9696
const isConfigured = ref(false)
97-
const isOpen = ref(false)
97+
98+
// The request for the setup lives in the URL, unlike other modals: when the setup requires
99+
// a fresh session, the agent is sent to /verify with this URL as `next`, and comes back to
100+
// the setup itself rather than to a page where they would have to start it again.
101+
const route = useRoute()
102+
const router = useRouter()
103+
const requested = computed(() => route.query.two_factor === 'setup')
104+
const setRequested = (value: boolean) => router.replace({ query: { ...route.query, two_factor: value ? 'setup' : undefined } })
105+
// Shown only once udata accepts the setup, so that it does not flash before /verify.
106+
const shown = ref(false)
107+
const isOpen = computed({
108+
get: () => shown.value,
109+
set: (open) => {
110+
if (!open) shown.value = false
111+
setRequested(open)
112+
},
113+
})
98114
99115
const emit = defineEmits<{
100116
setupComplete: []
@@ -110,15 +126,32 @@ const {
110126
validateCode,
111127
} = useTwoFactorSetup()
112128
129+
const { $api } = useNuxtApp()
113130
const fetchStatusAndQRCode = async () => {
114131
// fetch two factor status. If freshness is required, a 401 is returned with automatic handling and redirection to /verify
115-
const { data: twoFactorData, status } = await useAPI<{ response: { tf_primary_method: string | null, reauth_required: boolean } | null }>('/tf-setup')
116-
if (status.value !== 'error') {
117-
isConfigured.value = !!twoFactorData.value?.response?.tf_primary_method
118-
await fetchQRCode()
132+
try {
133+
const { response } = await $api<{ response: { tf_primary_method: string | null } | null }>('/tf-setup')
134+
isConfigured.value = !!response?.tf_primary_method
135+
}
136+
catch (e) {
137+
// A 401 has already sent the agent to /verify or /login, with this page's URL as
138+
// `next`: rewriting the query now would strip it from the new page. Any other error
139+
// leaves them here, so the request is dropped for the button to ask again.
140+
if (!(e instanceof FetchError) || e.statusCode !== 401) setRequested(false)
141+
return
119142
}
143+
shown.value = true
144+
await fetchQRCode()
120145
}
121146
147+
watch(requested, (value) => {
148+
if (value) fetchStatusAndQRCode()
149+
else shown.value = false
150+
})
151+
onMounted(() => {
152+
if (requested.value) fetchStatusAndQRCode()
153+
})
154+
122155
const submit = async (close: () => void) => {
123156
const success = await validateCode(async () => {
124157
await loadMe(me)

‎pages/login.vue‎

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -83,23 +83,10 @@
8383

8484
<Divider>{{ $t('ou') }}</Divider>
8585

86-
<form :action="proconnectUrl">
87-
<div class="fr-connect-group flex flex-col items-center">
88-
<button class="fr-connect">
89-
<span class="fr-connect__login">{{ $t('Se connecter avec') }}</span>
90-
<span class="fr-connect__brand">ProConnect</span>
91-
</button>
92-
<p>
93-
<CdataLink
94-
:href="config.public.proconnect.homepage"
95-
target="_blank"
96-
rel="noopener"
97-
>
98-
{{ $t(`Qu'est-ce que ProConnect ?`) }}
99-
</CdataLink>
100-
</p>
101-
</div>
102-
</form>
86+
<ProConnectButton
87+
:label="$t('Se connecter avec')"
88+
action="login"
89+
/>
10390
</div>
10491
</div>
10592
<div class="container bg-white max-w-xl p-6 border border-gray-lower flex flex-col sm:items-center">
@@ -184,6 +171,4 @@ const connect = async () => {
184171
loading.value = false
185172
}
186173
}
187-
188-
const proconnectUrl = computed(() => `${config.public.apiBase}/api/1/proconnect/login/`)
189174
</script>

‎pages/verify.vue‎

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,20 @@
22
<div class="bg-gray-some py-6 space-y-6">
33
<div class="container bg-white max-w-xl p-6 border border-gray-lower">
44
<h1 class="text-center text-gray-title font-extrabold text-2xl">
5-
{{ $t('Confirmer votre mot de passe') }}
5+
{{ $t('Confirmer votre identité') }}
66
</h1>
77

8-
<div class="space-y-6">
8+
<!-- Back from a successful ProConnect reauthentication: only leaving remains. -->
9+
<div
10+
v-if="proconnectSucceeded"
11+
class="flex justify-center py-6"
12+
>
13+
<AnimatedLoader />
14+
</div>
15+
<div
16+
v-else
17+
class="space-y-6"
18+
>
919
<SimpleBanner
1020
v-if="getAllErrorsInErrorFields(errors, '')"
1121
type="danger"
@@ -39,13 +49,20 @@
3949
</BrandedButton>
4050
</div>
4151
</form>
52+
53+
<Divider>{{ $t('ou') }}</Divider>
54+
55+
<ProConnectButton
56+
:label="$t('S’identifier avec')"
57+
action="reauth"
58+
/>
4259
</div>
4360
</div>
4461
</div>
4562
</template>
4663

4764
<script setup lang="ts">
48-
import { BrandedButton, SimpleBanner, toast } from '@datagouv/components-next'
65+
import { AnimatedLoader, BrandedButton, SimpleBanner, toast } from '@datagouv/components-next'
4966
import type { FieldsErrors } from '~/types/form'
5067
import { usePostApiWithCsrf } from '~/utils/api'
5168
@@ -63,11 +80,22 @@ const errors = ref<FieldsErrors>({})
6380
const me = useMe()
6481
6582
const route = useRoute()
83+
// Read before the site header consumes the flash and strips it from the URL.
84+
const proconnectSucceeded = route.query.flash === 'proconnect_reauth_success'
6685
67-
onMounted(() => {
86+
// Replace: going back to /verify?flash=proconnect_reauth_success would bounce the agent
87+
// forward again, the site header's own replace that strips the flash being cancelled by
88+
// this navigation.
89+
const goToNext = () => navigateTo(sessionStorage.getItem('next') || '/', { replace: true })
90+
91+
onMounted(async () => {
6892
if (route.query.next) {
6993
sessionStorage.setItem('next', route.query.next as string)
7094
}
95+
// Back from ProConnect: udata redirects here, the destination stayed in `sessionStorage`.
96+
if (proconnectSucceeded) {
97+
await goToNext()
98+
}
7199
})
72100
73101
const postApiWithCsrf = usePostApiWithCsrf()
@@ -82,14 +110,7 @@ const connect = async () => {
82110
83111
toast.success(t('Compte confirmé.'))
84112
await loadMe(me)
85-
86-
const next = sessionStorage.getItem('next')
87-
if (next) {
88-
navigateTo(next)
89-
}
90-
else {
91-
await navigateTo('/')
92-
}
113+
await goToNext()
93114
}
94115
catch (e) {
95116
// eslint-disable-next-line @typescript-eslint/no-explicit-any

‎tests/auth/verify.spec.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { test, expect } from '../base'
2+
import { gotoHydrated } from '../helpers'
3+
4+
// udata lands the agent back on /verify after the ProConnect round-trip: the destination
5+
// was remembered when the page was first opened, before leaving for ProConnect.
6+
test('a successful ProConnect reauthentication goes on to the remembered destination', async ({ page }) => {
7+
await gotoHydrated(page, '/verify?next=/admin/me/profile')
8+
9+
await page.goto('/verify?flash=proconnect_reauth_success')
10+
11+
await expect(page).toHaveURL(/\/admin\/me\/profile/)
12+
await expect(page.getByText('Compte confirmé.')).toBeVisible()
13+
})
14+
15+
test('going back after a successful ProConnect reauthentication does not bounce forward', async ({ page }) => {
16+
await gotoHydrated(page, '/verify?next=/admin/me/profile')
17+
await page.goto('/verify?flash=proconnect_reauth_success')
18+
await expect(page).toHaveURL(/\/admin\/me\/profile/)
19+
20+
await page.goBack()
21+
22+
await expect(page).toHaveURL(/\/verify\?next=/)
23+
})
24+
25+
test.describe('when the two-factor setup requires a fresh session', () => {
26+
// The 401 below is the point of the test: the browser logs it.
27+
test.use({ allowedConsoleMessages: ['the server responded with a status of 401'] })
28+
29+
test('the reauthentication goes back to the setup', async ({ page }) => {
30+
// udata asks for a fresh session until the identity is confirmed.
31+
await page.route('**/tf-setup?*', route => route.fulfill({ status: 401, json: { response: { reauth_required: true } } }))
32+
await gotoHydrated(page, '/admin/me/profile')
33+
await page.getByRole('button', { name: 'Configurer l\'authentification deux facteurs' }).click()
34+
await expect(page.getByRole('heading', { level: 1, name: 'Confirmer votre identité' })).toBeVisible()
35+
36+
await page.unroute('**/tf-setup?*')
37+
await page.goto('/verify?flash=proconnect_reauth_success')
38+
39+
await expect(page.getByRole('dialog', { name: 'Authentification deux facteurs' })).toBeVisible()
40+
await expect(page.getByTestId('totp-key')).not.toBeEmpty()
41+
})
42+
})
43+
44+
test('the ProConnect button asks udata for a reauthentication, not a login', async ({ page }) => {
45+
let requested: URL | undefined
46+
// Stop at udata: the round-trip itself goes through ProConnect.
47+
await page.route('**/api/1/proconnect/**', (route) => {
48+
requested = new URL(route.request().url())
49+
return route.abort()
50+
})
51+
await page.goto('/verify')
52+
53+
await page.getByRole('button', { name: 'S’identifier avec ProConnect' }).click()
54+
55+
await expect.poll(() => requested?.pathname).toBe('/api/1/proconnect/reauth/')
56+
})
57+
58+
test('a failed ProConnect reauthentication stays on the page and says so', async ({ page }) => {
59+
await page.goto('/verify?next=/admin/me/profile')
60+
await expect(page.getByRole('heading', { level: 1, name: 'Confirmer votre identité' })).toBeVisible()
61+
62+
await page.goto('/verify?flash=proconnect_reauth_failed')
63+
64+
await expect(page.getByText('La confirmation de votre identité avec ProConnect a échoué. Veuillez réessayer.')).toBeVisible()
65+
await expect(page).toHaveURL(/\/verify/)
66+
})

0 commit comments

Comments
 (0)