'use client'; import {ChangeEvent, Dispatch, SetStateAction, useContext, useState} from 'react'; import {Check, KeyRound, Smartphone, QrCode} from 'lucide-react'; import {apiPost} from "@/lib/api/client"; import {AlertContext, AlertContextProps} from "@/context/AlertContext"; import {FormResponse} from "@/shared/interface"; import {SessionContext} from "@/context/SessionContext"; import TextInput from "@/components/form/TextInput"; import InputField from "@/components/form/InputField"; import Button from "@/components/ui/Button"; const AppleIcon = () => ( ); const GooglePlayIcon = () => ( ); export default function TwoFactorSetup({setShowSetup}: { setShowSetup: Dispatch> }) { const {session} = useContext(SessionContext); const alert: AlertContextProps = useContext(AlertContext); const [step, setStep] = useState(1); const [token, setToken] = useState('') const [qrCode, setQrCode] = useState(null); const [loadingQRCode, setLoadingQRCode] = useState(false); async function getQRCode() { try { const response: { qrCode: string } = await apiPost('twofactor/setup', { email: session?.user?.email, }, session?.accessToken ?? ''); setQrCode(response.qrCode); } catch (e: unknown) { if (e instanceof Error) alert.errorMessage(e.message); } } async function handleNextStep() { if (step === 3) { await validateToken(); } else if (step === 1) { if (qrCode === null) { getQRCode(); } setStep((prev: number) => Math.min(prev + 1, 3)); } else { setStep((prev: number) => Math.min(prev + 1, 3)); } } async function validateToken() { try { const response: FormResponse = await apiPost('twofactor/activate', { email: session?.user?.email, token: token }, session?.accessToken ?? ''); if (response.valid) { alert.successMessage(response.message ?? ''); setShowSetup(false); } } catch (e: unknown) { if (e instanceof Error) alert.errorMessage(e.message); } } function handlePrevStep() { setStep((prev) => Math.max(prev - 1, 1)); } function getProgressClass(currentStep: number) { return `flex-grow h-2.5 rounded-full transition-all duration-300 ${ step >= currentStep ? 'bg-primary shadow-sm' : 'bg-secondary/50' }`; } return (

Setup Two-Factor Authentication

{step === 1 && (

Follow these steps to enable two-factor authentication for your account:

  1. Download a two-factor authentication app like Google Authenticator or Authy.
  2. Open the app and select the option to scan a QR code.
  3. Proceed to the next step to scan the QR code provided.
)} {step === 2 && (

Scan the QR code below with your authentication app to link your account.

{loadingQRCode ? (
Loading QR Code...
) : qrCode ? ( QR Code ) : (
Failed to load QR Code.
)}

Having trouble? Make sure your app supports QR code scanning.

)} {step === 3 && (

Enter the 6-digit code generated by your authentication app to verify the setup.

) => setToken(e.target.value)} placeholder="Enter 6-digit code" /> } />
)}
); }