forgot-password-mfa.tsx87 lines · main
1import * as Sentry from '@sentry/nextjs'
2import { useQueryClient } from '@tanstack/react-query'
3import { getAccessToken } from 'common'
4import { useRouter } from 'next/router'
5import { useEffect, useState } from 'react'
6import { toast } from 'sonner'
7import { LogoLoader } from 'ui'
8
9import { SignInMfaForm } from '@/components/interfaces/SignIn/SignInMfaForm'
10import ForgotPasswordLayout from '@/components/layouts/SignInLayout/ForgotPasswordLayout'
11import { auth, buildPathWithParams, getReturnToPath } from '@/lib/gotrue'
12import type { NextPageWithLayout } from '@/types'
13
14const ForgotPasswordMfa: NextPageWithLayout = () => {
15 const router = useRouter()
16 const queryClient = useQueryClient()
17
18 const [loading, setLoading] = useState(true)
19
20 // This useEffect redirects the user to MFA if they're already halfway signed in
21 useEffect(() => {
22 auth
23 .initialize()
24 .then(async ({ error }) => {
25 if (error) {
26 // if there was a problem signing in via the url, don't redirect
27 setLoading(false)
28 return
29 }
30
31 const token = await getAccessToken()
32
33 if (token) {
34 const { data, error } = await auth.mfa.getAuthenticatorAssuranceLevel()
35 if (error) {
36 // if there was a problem signing in via the url, don't redirect
37 toast.error(
38 `Failed to retrieve assurance level: ${error.message}. Please try signing in again`
39 )
40 setLoading(false)
41 return router.push({ pathname: '/sign-in', query: router.query })
42 }
43
44 if (data.currentLevel === data.nextLevel) {
45 await queryClient.resetQueries()
46 router.push(getReturnToPath())
47 return
48 } else {
49 // Show the MFA form
50 setLoading(false)
51 return
52 }
53 } else {
54 // if the user doesn't have a token, he needs to go back to the sign-in page
55 const redirectTo = buildPathWithParams('/sign-in')
56 router.replace(redirectTo)
57 return
58 }
59 })
60 .catch((error) => {
61 Sentry.captureException(error)
62 console.error('Auth initialization error:', error)
63 toast.error('Failed to initialize authentication. Please try again.')
64 setLoading(false)
65 router.push({ pathname: '/sign-in', query: router.query })
66 })
67 }, [])
68
69 if (loading) {
70 return (
71 <div className="flex flex-col flex-1 bg-alternative h-screen items-center justify-center">
72 <LogoLoader />
73 </div>
74 )
75 }
76
77 return (
78 <ForgotPasswordLayout
79 heading="Complete two-factor authentication"
80 subheading="Enter the authentication code from your two-factor authentication app before changing your password"
81 >
82 <SignInMfaForm context="forgot-password" />
83 </ForgotPasswordLayout>
84 )
85}
86
87export default ForgotPasswordMfa