| 16 | import { handleError, useTRPC } from '@/integrations/trpc/react'; |
| 17 | |
| 18 | export default function SetupTwoFactor() { |
| 19 | const trpc = useTRPC(); |
| 20 | const queryClient = useQueryClient(); |
| 21 | const [step, setStep] = useState<'scan' | 'recovery'>('scan'); |
| 22 | const [code, setCode] = useState(''); |
| 23 | const [setupData, setSetupData] = useState<{ |
| 24 | qrDataUrl: string; |
| 25 | secret: string; |
| 26 | } | null>(null); |
| 27 | const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]); |
| 28 | |
| 29 | const setupMutation = useMutation( |
| 30 | trpc.auth.totpSetup.mutationOptions({ |
| 31 | onSuccess: (data) => { |
| 32 | setSetupData({ qrDataUrl: data.qrDataUrl, secret: data.secret }); |
| 33 | }, |
| 34 | onError: handleError, |
| 35 | }) |
| 36 | ); |
| 37 | |
| 38 | const enableMutation = useMutation( |
| 39 | trpc.auth.totpEnable.mutationOptions({ |
| 40 | onSuccess: (data) => { |
| 41 | setRecoveryCodes(data.recoveryCodes); |
| 42 | setStep('recovery'); |
| 43 | queryClient.invalidateQueries(trpc.auth.totpStatus.pathFilter()); |
| 44 | }, |
| 45 | onError: (error) => { |
| 46 | toast.error(error.message); |
| 47 | setCode(''); |
| 48 | }, |
| 49 | }) |
| 50 | ); |
| 51 | |
| 52 | useEffect(() => { |
| 53 | setupMutation.mutate(); |
| 54 | }, []); |
| 55 | |
| 56 | if (step === 'recovery') { |
| 57 | return ( |
| 58 | <ModalContent> |
| 59 | <ModalHeader |
| 60 | text="Store these somewhere safe. Each can be used once if you lose access to your authenticator. You won't see them again." |
| 61 | title="Save your recovery codes" |
| 62 | /> |
| 63 | <RecoveryCodesBlock codes={recoveryCodes} /> |
| 64 | <DialogFooter> |
| 65 | <Button onClick={() => popModal()}>I've saved my codes</Button> |
| 66 | </DialogFooter> |
| 67 | </ModalContent> |
| 68 | ); |
| 69 | } |
| 70 | |
| 71 | return ( |
| 72 | <ModalContent> |
| 73 | <ModalHeader |
| 74 | text="Scan the QR code with your authenticator app, then enter the 6-digit code to enable." |
| 75 | title="Set up two-factor authentication" |