-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAddNewFactorModal.tsx
More file actions
268 lines (246 loc) · 8.29 KB
/
Copy pathAddNewFactorModal.tsx
File metadata and controls
268 lines (246 loc) · 8.29 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import { zodResolver } from '@hookform/resolvers/zod'
import { useQueryClient } from '@tanstack/react-query'
import { LOCAL_STORAGE_KEYS } from 'common'
import InformationBox from 'components/ui/InformationBox'
import { organizationKeys } from 'data/organizations/keys'
import { useMfaChallengeAndVerifyMutation } from 'data/profile/mfa-challenge-and-verify-mutation'
import { useMfaEnrollMutation } from 'data/profile/mfa-enroll-mutation'
import { useMfaUnenrollMutation } from 'data/profile/mfa-unenroll-mutation'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useEffect, useState } from 'react'
import { useForm, type SubmitHandler } from 'react-hook-form'
import { toast } from 'sonner'
import { Form_Shadcn_, FormControl_Shadcn_, FormField_Shadcn_, Input, Input_Shadcn_ } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { z } from 'zod'
type TOTP = { qr_code: string; secret: string; uri: string }
interface AddNewFactorModalProps {
visible: boolean
onClose: () => void
}
export const AddNewFactorModal = ({ visible, onClose }: AddNewFactorModalProps) => {
const { data, mutate: enroll, isPending: isEnrolling, reset } = useMfaEnrollMutation()
useEffect(() => {
if (!visible) reset()
}, [reset, visible])
return (
<>
<FirstStep
visible={visible && !Boolean(data)}
isEnrolling={isEnrolling}
enroll={enroll}
reset={reset}
onClose={onClose}
/>
<SecondStep
visible={visible && Boolean(data)}
factorName={data?.friendly_name ?? ''}
factor={data as Extract<typeof data, { type: 'totp' }>}
isLoading={isEnrolling}
onClose={onClose}
/>
</>
)
}
interface FirstStepProps {
visible: boolean
isEnrolling: boolean
reset: () => void
enroll: (params: { factorType: 'totp'; friendlyName?: string }) => void
onClose: () => void
}
const FirstStep = ({ visible, isEnrolling, reset, enroll, onClose }: FirstStepProps) => {
const FormSchema = z.object({
name: z.string().min(1, 'Please provide a name to identify this app'),
})
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: { name: '' },
mode: 'onChange',
})
const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (values) => {
enroll({ factorType: 'totp', friendlyName: values.name })
}
useEffect(() => {
if (!visible) {
// Generate a name with a number between 0 and 1000
form.reset({ name: `App ${Math.floor(Math.random() * 1000)}` })
}
}, [form, visible])
return (
<ConfirmationModal
size="medium"
visible={visible}
title="Add a new authenticator app as a factor"
confirmLabel="Generate QR"
confirmLabelLoading="Generating QR"
loading={isEnrolling}
onCancel={onClose}
onConfirm={form.handleSubmit(onSubmit)}
>
<Form_Shadcn_ {...form}>
<form
id="verify-otp-form"
className="flex flex-col gap-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField_Shadcn_
key="name"
name="name"
control={form.control}
render={({ field }) => (
<FormItemLayout
name="name"
label="Provide a name to identify this app"
description="A string will be randomly generated if a name is not provided"
>
<FormControl_Shadcn_>
<Input_Shadcn_ id="name" {...field} />
</FormControl_Shadcn_>
</FormItemLayout>
)}
/>
</form>
</Form_Shadcn_>
</ConfirmationModal>
)
}
interface SecondStepProps {
visible: boolean
factorName: string
factor?: {
id: string
type: 'totp'
totp: TOTP
}
isLoading: boolean
onClose: () => void
}
const SecondStep = ({
visible,
factorName,
factor: outerFactor,
isLoading,
onClose,
}: SecondStepProps) => {
const queryClient = useQueryClient()
const [lastVisitedOrganization] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.LAST_VISITED_ORGANIZATION,
''
)
const FormSchema = z.object({
code: z.string().min(1, 'Please provide a code from your authenticator app'),
})
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: { code: '' },
mode: 'onChange',
})
const [factor, setFactor] = useState<{ id: string; type: 'totp'; totp: TOTP } | null>(null)
const { mutate: unenroll } = useMfaUnenrollMutation({ onSuccess: () => onClose() })
const { mutate: challengeAndVerify, isPending: isVerifying } = useMfaChallengeAndVerifyMutation({
onError: (error) => {
toast.error(`Failed to add a second factor authentication: ${error?.message}`)
},
onSuccess: async () => {
if (lastVisitedOrganization) {
await queryClient.invalidateQueries({
queryKey: organizationKeys.members(lastVisitedOrganization),
})
}
toast.success(`Successfully added a second factor authentication`)
onClose()
},
})
const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (values) => {
if (!factor) return toast.error('Factor required')
challengeAndVerify({ factorId: factor.id, code: values.code })
}
// this useEffect is to keep the factor until a new one comes. This is a fix to an issue which
// happens when closing the modal, the outer factor is reset to null too soon and the modal
// removes a big div mid transition.
useEffect(() => {
if (outerFactor && factor?.id !== outerFactor.id) {
setFactor(outerFactor)
form.reset({ code: '' })
}
}, [outerFactor])
return (
<ConfirmationModal
size="medium"
visible={visible}
className="py-5"
title={`Verify new factor ${factorName}`}
confirmLabel="Confirm"
confirmLabelLoading="Confirming"
loading={isVerifying}
onCancel={() => {
// If a factor has been created (but not verified), unenroll it. This will be run as a
// side effect so that it's not confusing to the user why the modal stays open while
// unenrolling.
if (factor) unenroll({ factorId: factor.id })
}}
onConfirm={form.handleSubmit(onSubmit)}
>
<p className="text-sm">
Use an authenticator app to scan the following QR code, and provide the code from the app to
complete the enrolment.
</p>
{isLoading && (
<div className="pb-4 px-4">
<GenericSkeletonLoader />
</div>
)}
{factor && (
<div className="flex flex-col gap-y-4">
<div className="flex justify-center py-6">
<div className="h-48 w-48 bg-white rounded">
<img width={190} height={190} src={factor.totp.qr_code} alt={factor.totp.uri} />
</div>
</div>
<InformationBox
title="Unable to scan?"
description={
<Input
copy
disabled
id="ref"
size="small"
label="You can also enter this secret key into your authenticator app"
value={factor.totp.secret}
/>
}
/>
<Form_Shadcn_ {...form}>
<form
id="verify-otp-form"
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="Authentication code">
<FormControl_Shadcn_>
<Input_Shadcn_
id="code"
autoFocus
{...field}
placeholder="XXXXXX"
className="font-mono"
/>
</FormControl_Shadcn_>
</FormItemLayout>
)}
/>
</form>
</Form_Shadcn_>
</div>
)}
</ConfirmationModal>
)
}