-
Notifications
You must be signed in to change notification settings - Fork 585
/
Copy pathuse-2fa.ts
59 lines (50 loc) · 1.33 KB
/
use-2fa.ts
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
import {useCallback, useState} from 'react'
import {toast} from '@/components/ui/toast'
import {trpcReact} from '@/trpc/trpc'
import {t} from '@/utils/i18n'
export function use2fa(onEnableChange?: (enabled: boolean) => void) {
const ctx = trpcReact.useContext()
const enableMut = trpcReact.user.enable2fa.useMutation({
onSuccess: () => {
ctx.user.is2faEnabled.invalidate()
setTimeout(() => {
toast.success(t('2fa.enable.success'))
onEnableChange?.(true)
}, 500)
},
})
const disableMut = trpcReact.user.disable2fa.useMutation({
onSuccess: () => {
ctx.user.is2faEnabled.invalidate()
setTimeout(() => {
toast.success(t('2fa.disable.success'))
onEnableChange?.(false)
}, 500)
},
})
const is2faEndabledQ = trpcReact.user.is2faEnabled.useQuery()
// TOTP URI
const [totpUri, setTotpUri] = useState('')
const generateTotpUri = useCallback(() => {
ctx.user.generateTotpUri.fetch().then((res) => setTotpUri(res))
}, [ctx])
const enable = useCallback(
async (totpToken: string) => {
return enableMut.mutateAsync({totpToken, totpUri})
},
[enableMut, totpUri],
)
const disable = useCallback(
async (totpToken: string) => {
return disableMut.mutateAsync({totpToken})
},
[disableMut],
)
return {
isEnabled: is2faEndabledQ.data,
enable,
disable,
totpUri,
generateTotpUri,
}
}