-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSignInMfaForm.tsx
More file actions
226 lines (206 loc) · 7.23 KB
/
Copy pathSignInMfaForm.tsx
File metadata and controls
226 lines (206 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import { zodResolver } from '@hookform/resolvers/zod'
import { SupportCategories } from '@supabase/shared-types/out/constants'
import type { Factor } from '@supabase/supabase-js'
import { useQueryClient } from '@tanstack/react-query'
import { useAuthError } from 'common'
import AlertError from 'components/ui/AlertError'
import { useMfaChallengeAndVerifyMutation } from 'data/profile/mfa-challenge-and-verify-mutation'
import { useMfaListFactorsQuery } from 'data/profile/mfa-list-factors-query'
import { useSignOut } from 'lib/auth'
import { getReturnToPath } from 'lib/gotrue'
import { Lock } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useRef, useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
import { Button, Form_Shadcn_, FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_ } from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import z from 'zod'
import { SupportLink } from '../Support/SupportLink'
const schema = z.object({
code: z.string().min(1, 'MFA Code is required'),
})
const formId = 'sign-in-mfa-form'
interface SignInMfaFormProps {
context?: 'forgot-password' | 'sign-in'
}
export const SignInMfaForm = ({ context = 'sign-in' }: SignInMfaFormProps) => {
const router = useRouter()
const signOut = useSignOut()
const queryClient = useQueryClient()
const [selectedFactor, setSelectedFactor] = useState<Factor | null>(null)
const form = useForm<z.infer<typeof schema>>({
resolver: zodResolver(schema),
defaultValues: { code: '' },
})
const { code } = form.watch()
const {
data: factors,
error: factorsError,
isError: isErrorFactors,
isSuccess: isSuccessFactors,
isPending: isLoadingFactors,
} = useMfaListFactorsQuery()
const {
mutate: mfaChallengeAndVerify,
isPending: isVerifying,
isSuccess,
} = useMfaChallengeAndVerifyMutation({
onSuccess: async () => {
await queryClient.resetQueries()
if (context === 'forgot-password') {
router.push({
pathname: '/reset-password',
query: router.query,
})
} else {
router.push(getReturnToPath())
}
},
})
const onClickLogout = async () => {
await signOut()
await router.replace('/sign-in')
}
const onSubmit: SubmitHandler<z.infer<typeof schema>> = async ({ code }) => {
if (selectedFactor) {
mfaChallengeAndVerify({ factorId: selectedFactor.id, code, refreshFactors: false })
}
}
useEffect(() => {
if (isSuccessFactors) {
// if the user wanders into this page and he has no MFA setup, send the user to the next screen
if (factors.totp.length === 0) {
queryClient.resetQueries().then(() => router.push(getReturnToPath()))
}
if (factors.totp.length > 0) {
setSelectedFactor(factors.totp[0])
}
}
}, [factors?.totp, isSuccessFactors, router, queryClient])
useEffect(() => {
if (code.length === 6) form.handleSubmit(onSubmit)()
}, [code])
const error = useAuthError()
if (error) {
return (
<AlertError
error={error}
subject="Error while signing in"
additionalActions={
<Button asChild type="default">
<Link href="/sign-in">Back to sign in</Link>
</Button>
}
/>
)
}
return (
<>
{isLoadingFactors && <GenericSkeletonLoader />}
{isErrorFactors && <AlertError error={factorsError} subject="Failed to retrieve factors" />}
{isSuccessFactors && (
<Form_Shadcn_ {...form}>
<form id={formId} className="flex flex-col gap-4" onSubmit={form.handleSubmit(onSubmit)}>
<FormField_Shadcn_
key="code"
name="code"
control={form.control}
render={({ field }) => (
<FormItemLayout
name="code"
label={
selectedFactor && factors?.totp.length === 2
? `Code generated by ${selectedFactor.friendly_name}`
: null
}
>
<FormControl_Shadcn_>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-foreground-light [&_svg]:stroke-[1.5] [&_svg]:h-[20px] [&_svg]:w-[20px]">
<Lock />
</div>
<Input_Shadcn_
id="code"
className="pl-10 font-mono"
{...field}
autoFocus
autoComplete="off"
autoCorrect="off"
autoCapitalize="none"
spellCheck="false"
placeholder="XXXXXX"
disabled={isVerifying}
/>
</div>
</FormControl_Shadcn_>
</FormItemLayout>
)}
/>
<div className="flex items-center justify-between gap-x-2">
<Button
block
type="outline"
size="large"
disabled={isVerifying || isSuccess}
onClick={onClickLogout}
className="opacity-80 hover:opacity-100 transition"
>
Cancel
</Button>
<Button
block
form={formId}
htmlType="submit"
size="large"
disabled={isVerifying || isSuccess}
loading={isVerifying || isSuccess}
>
{isVerifying ? 'Verifying' : isSuccess ? 'Signing in' : 'Verify'}
</Button>
</div>
</form>
</Form_Shadcn_>
)}
<div className="my-8">
<div className="text-sm">
<span className="text-foreground-light">Unable to sign in?</span>{' '}
</div>
<ul className="list-disc pl-6">
{factors?.totp.length === 2 && (
<li>
<a
className="text-sm text-foreground-light hover:text-foreground cursor-pointer"
onClick={() =>
setSelectedFactor(factors.totp.find((f) => f.id !== selectedFactor?.id)!)
}
>{`Authenticate using ${
factors.totp.find((f) => f.id !== selectedFactor?.id)?.friendly_name
}?`}</a>
</li>
)}
<li>
<Link
href="/logout"
className="text-sm transition text-foreground-light hover:text-foreground"
>
Force sign out and clear cookies
</Link>
</li>
<li>
<SupportLink
className="text-sm transition text-foreground-light hover:text-foreground"
queryParams={{
subject: 'Unable to sign in via MFA',
category: SupportCategories.LOGIN_ISSUES,
}}
>
Reach out to us via support
</SupportLink>
</li>
</ul>
</div>
</>
)
}