refactor: split dialogs into components

This commit is contained in:
Nicolas Meienberger 2026-01-08 20:50:58 +01:00
parent c397908441
commit 1fd4b3c64e
8 changed files with 640 additions and 530 deletions

View file

@ -1,75 +1,66 @@
import * as React from "react"
import { OTPInput, OTPInputContext } from "input-otp"
import { MinusIcon } from "lucide-react"
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { MinusIcon } from "lucide-react";
import { cn } from "~/client/lib/utils"
import { cn } from "~/client/lib/utils";
function InputOTP({
className,
containerClassName,
...props
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string
containerClassName?: string;
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn(
"flex items-center gap-2 has-disabled:opacity-50",
containerClassName
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
)
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn("flex items-center gap-2 has-disabled:opacity-50", containerClassName)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
);
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-otp-group"
className={cn("flex items-center", className)}
{...props}
/>
)
return <div data-slot="input-otp-group" className={cn("flex items-center", className)} {...props} />;
}
function InputOTPSlot({
index,
className,
...props
index,
className,
...props
}: React.ComponentProps<"div"> & {
index: number
index: number;
}) {
const inputOTPContext = React.useContext(OTPInputContext)
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {};
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
)
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
className,
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
)
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
);
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };

View file

@ -10,10 +10,10 @@ import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "
import { Input } from "~/client/components/ui/input";
import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot } from "~/client/components/ui/input-otp";
import { Label } from "~/client/components/ui/label";
import { authMiddleware } from "~/middleware/auth";
import type { Route } from "./+types/login";
import { ResetPasswordDialog } from "../components/reset-password-dialog";
import { authClient } from "~/client/lib/auth-client";
import { authMiddleware } from "~/middleware/auth";
import { ResetPasswordDialog } from "../components/reset-password-dialog";
import type { Route } from "./+types/login";
export const clientMiddleware = [authMiddleware];

View file

@ -0,0 +1,135 @@
import { useState } from "react";
import { toast } from "sonner";
import { Copy, RefreshCw } from "lucide-react";
import { Button } from "~/client/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "~/client/components/ui/dialog";
import { Input } from "~/client/components/ui/input";
import { Label } from "~/client/components/ui/label";
import { authClient } from "~/client/lib/auth-client";
import { copyToClipboard } from "~/utils/clipboard";
type BackupCodesDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
};
export const BackupCodesDialog = ({ open, onOpenChange }: BackupCodesDialogProps) => {
const [password, setPassword] = useState("");
const [backupCodes, setBackupCodes] = useState<string[]>([]);
const [isGenerating, setIsGenerating] = useState(false);
const handleGenerate = async (e: React.FormEvent) => {
e.preventDefault();
if (!password) {
toast.error("Password is required");
return;
}
const { data, error } = await authClient.twoFactor.generateBackupCodes({
password,
fetchOptions: {
onRequest: () => {
setIsGenerating(true);
},
onResponse: () => {
setIsGenerating(false);
},
},
});
if (error) {
console.error(error);
toast.error("Failed to generate backup codes", { description: error.message });
return;
}
setBackupCodes(data.backupCodes);
setPassword("");
toast.success("New backup codes generated successfully");
};
const handleClose = () => {
onOpenChange(false);
setTimeout(() => {
setBackupCodes([]);
setPassword("");
}, 200);
};
const copyAllBackupCodes = () => {
const text = backupCodes.join("\n");
void copyToClipboard(text);
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent>
<DialogHeader>
<DialogTitle>Backup Codes</DialogTitle>
<DialogDescription>
Use these codes to access your account if you lose access to your authenticator app. Each code can only be
used once.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{backupCodes.length > 0 ? (
<>
<div className="p-3 bg-muted rounded-md space-y-1 max-h-48 overflow-y-auto">
{backupCodes.map((code) => (
<div key={code} className="text-sm font-mono flex items-center justify-between">
<span>{code}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => copyToClipboard(code)}
className="h-8 w-8 p-0"
>
<Copy className="h-4 w-4" />
</Button>
</div>
))}
</div>
<Button type="button" variant="outline" onClick={copyAllBackupCodes} className="w-full">
<Copy className="h-4 w-4 mr-2" />
Copy all
</Button>
</>
) : (
<form onSubmit={handleGenerate} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="backup-codes-password">Your password</Label>
<Input
id="backup-codes-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
required
autoFocus
/>
</div>
<Button type="submit" loading={isGenerating} className="w-full">
<RefreshCw className="h-4 w-4 mr-2" />
Generate new codes
</Button>
</form>
)}
</div>
<DialogFooter>
<Button type="button" onClick={handleClose}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};

View file

@ -0,0 +1,98 @@
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "~/client/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "~/client/components/ui/dialog";
import { Input } from "~/client/components/ui/input";
import { Label } from "~/client/components/ui/label";
import { authClient } from "~/client/lib/auth-client";
type TwoFactorDisableDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
};
export const TwoFactorDisableDialog = ({ open, onOpenChange, onSuccess }: TwoFactorDisableDialogProps) => {
const [password, setPassword] = useState("");
const [isDisabling, setIsDisabling] = useState(false);
const handleDisable = async (e: React.FormEvent) => {
e.preventDefault();
if (!password) {
toast.error("Password is required");
return;
}
const { error } = await authClient.twoFactor.disable({
password,
fetchOptions: {
onRequest: () => {
setIsDisabling(true);
},
onResponse: () => {
setIsDisabling(false);
},
},
});
if (error) {
console.error(error);
toast.error("Failed to disable 2FA", { description: error.message });
return;
}
toast.success("Two-factor authentication disabled successfully");
handleClose();
onSuccess();
};
const handleClose = () => {
onOpenChange(false);
setPassword("");
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent>
<form onSubmit={handleDisable}>
<DialogHeader>
<DialogTitle>Disable Two-Factor Authentication</DialogTitle>
<DialogDescription>
Are you sure you want to disable 2FA? Your account will be less secure. Enter your password to confirm.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="disable-password">Your password</Label>
<Input
id="disable-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
required
autoFocus
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button type="submit" variant="destructive" loading={isDisabling}>
Disable 2FA
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
};

View file

@ -0,0 +1,71 @@
import { useState } from "react";
import { Shield } from "lucide-react";
import { Button } from "~/client/components/ui/button";
import { CardContent, CardDescription, CardTitle } from "~/client/components/ui/card";
import { TwoFactorSetupDialog } from "./two-factor-setup-dialog";
import { TwoFactorDisableDialog } from "./two-factor-disable-dialog";
import { BackupCodesDialog } from "./backup-codes-dialog";
type TwoFactorSectionProps = {
twoFactorEnabled?: boolean | null;
};
export const TwoFactorSection = ({ twoFactorEnabled }: TwoFactorSectionProps) => {
const [setupDialogOpen, setSetupDialogOpen] = useState(false);
const [disableDialogOpen, setDisableDialogOpen] = useState(false);
const [backupCodesDialogOpen, setBackupCodesDialogOpen] = useState(false);
const handleSuccess = async () => {
window.location.reload();
};
return (
<>
<div className="border-t border-border/50 bg-card-header p-6">
<CardTitle className="flex items-center gap-2">
<Shield className="size-5" />
Two-Factor Authentication
</CardTitle>
<CardDescription className="mt-1.5">Add an extra layer of security to your account</CardDescription>
</div>
<CardContent className="p-6 space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-1">
<p className="text-sm font-medium">
Status:&nbsp;
{twoFactorEnabled ? (
<span className="text-green-500">Enabled</span>
) : (
<span className="text-muted-foreground">Disabled</span>
)}
</p>
<p className="text-xs text-muted-foreground max-w-xl">
Two-factor authentication adds an extra layer of security by requiring a code from your authenticator app
in addition to your password.
</p>
</div>
<div className="flex gap-2">
{!twoFactorEnabled ? (
<Button onClick={() => setSetupDialogOpen(true)}>Enable 2FA</Button>
) : (
<div className="ml-2 flex flex-col @xl:flex-row gap-2">
<Button variant="outline" onClick={() => setBackupCodesDialogOpen(true)}>
Backup Codes
</Button>
<Button variant="destructive" onClick={() => setDisableDialogOpen(true)}>
Disable 2FA
</Button>
</div>
)}
</div>
</div>
</CardContent>
<TwoFactorSetupDialog open={setupDialogOpen} onOpenChange={setSetupDialogOpen} onSuccess={handleSuccess} />
<TwoFactorDisableDialog open={disableDialogOpen} onOpenChange={setDisableDialogOpen} onSuccess={handleSuccess} />
<BackupCodesDialog open={backupCodesDialogOpen} onOpenChange={setBackupCodesDialogOpen} />
</>
);
};

View file

@ -0,0 +1,266 @@
import { useState } from "react";
import { toast } from "sonner";
import { Copy } from "lucide-react";
import { QRCodeCanvas } from "qrcode.react";
import { Button } from "~/client/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "~/client/components/ui/dialog";
import { Input } from "~/client/components/ui/input";
import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot } from "~/client/components/ui/input-otp";
import { Label } from "~/client/components/ui/label";
import { authClient } from "~/client/lib/auth-client";
import { copyToClipboard } from "~/utils/clipboard";
type TwoFactorSetupDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
};
export const TwoFactorSetupDialog = ({ open, onOpenChange, onSuccess }: TwoFactorSetupDialogProps) => {
const [setupStep, setSetupStep] = useState<"password" | "qr" | "verify">("password");
const [password, setPassword] = useState("");
const [totpUri, setTotpUri] = useState<string | null>(null);
const [verificationCode, setVerificationCode] = useState("");
const [backupCodes, setBackupCodes] = useState<string[]>([]);
const [isEnabling2FA, setIsEnabling2FA] = useState(false);
const [isVerifying2FA, setIsVerifying2FA] = useState(false);
const handleEnable2FA = async (e: React.FormEvent) => {
e.preventDefault();
if (!password) {
toast.error("Password is required");
return;
}
const { data, error } = await authClient.twoFactor.enable({
password,
issuer: "Zerobyte",
fetchOptions: {
onRequest: () => {
setIsEnabling2FA(true);
},
onResponse: () => {
setIsEnabling2FA(false);
},
},
});
if (error) {
console.error(error);
toast.error("Failed to enable 2FA", { description: error.message });
return;
}
setTotpUri(data.totpURI);
setBackupCodes(data.backupCodes);
setSetupStep("qr");
};
const handleVerify2FA = async () => {
if (verificationCode.length !== 6) {
toast.error("Please enter a 6-digit code");
return;
}
const { data, error } = await authClient.twoFactor.verifyTotp({
code: verificationCode,
fetchOptions: {
onRequest: () => {
setIsVerifying2FA(true);
},
onResponse: () => {
setIsVerifying2FA(false);
},
},
});
if (error) {
console.error(error);
toast.error("Verification failed", { description: error.message });
setVerificationCode("");
return;
}
if (data) {
toast.success("Two-factor authentication enabled successfully");
handleClose();
onSuccess();
}
};
const handleClose = () => {
onOpenChange(false);
setTimeout(() => {
setPassword("");
setTotpUri(null);
setVerificationCode("");
setBackupCodes([]);
setSetupStep("password");
}, 200);
};
const copyAllBackupCodes = () => {
const text = backupCodes.join("\n");
void copyToClipboard(text);
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-md">
{setupStep === "password" && (
<form onSubmit={handleEnable2FA}>
<DialogHeader>
<DialogTitle>Enable Two-Factor Authentication</DialogTitle>
<DialogDescription>
Enter your password to generate a QR code for your authenticator app
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="setup-password">Your password</Label>
<Input
id="setup-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
required
autoFocus
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button type="submit" loading={isEnabling2FA}>
Continue
</Button>
</DialogFooter>
</form>
)}
{setupStep === "qr" && totpUri && (
<>
<DialogHeader>
<DialogTitle>Scan QR Code</DialogTitle>
<DialogDescription>
Scan this QR code with your authenticator app (Google Authenticator, Authy, etc.)
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="flex justify-center p-4 bg-white rounded-lg">
<QRCodeCanvas value={totpUri} size={200} />
</div>
<div className="space-y-2">
<Label className="text-xs">Manual entry code</Label>
<div className="flex items-center gap-2">
<Input
value={totpUri.split("secret=")[1]?.split("&")[0] || ""}
readOnly
className="text-xs font-mono"
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => copyToClipboard(totpUri.split("secret=")[1]?.split("&")[0] || "")}
>
<Copy className="h-4 w-4" />
</Button>
</div>
</div>
{backupCodes.length > 0 && (
<div className="space-y-2">
<Label className="text-xs">Backup codes (save these securely)</Label>
<div className="p-3 bg-muted rounded-md space-y-1 max-h-32 overflow-y-auto">
{backupCodes.map((code) => (
<div key={code} className="text-xs font-mono flex items-center justify-between">
<span>{code}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => copyToClipboard(code)}
className="h-6 w-6 p-0"
>
<Copy className="h-3 w-3" />
</Button>
</div>
))}
</div>
<Button type="button" variant="outline" size="sm" onClick={copyAllBackupCodes} className="w-full">
<Copy className="h-4 w-4 mr-2" />
Copy all
</Button>
</div>
)}
</div>
<DialogFooter>
<Button type="button" onClick={() => setSetupStep("verify")}>
Continue
</Button>
</DialogFooter>
</>
)}
{setupStep === "verify" && (
<>
<DialogHeader>
<DialogTitle>Verify setup</DialogTitle>
<DialogDescription>
Enter the 6-digit code from your authenticator app to complete setup
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2 flex flex-col items-center">
<div className="flex justify-center">
<InputOTP
maxLength={6}
value={verificationCode}
onChange={setVerificationCode}
onComplete={handleVerify2FA}
disabled={isVerifying2FA}
>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
</div>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setSetupStep("qr")}>
Back
</Button>
<Button
type="button"
onClick={handleVerify2FA}
loading={isVerifying2FA}
disabled={verificationCode.length !== 6}
>
Verify
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
);
};

View file

@ -1,9 +1,9 @@
import { useMutation } from "@tanstack/react-query";
import { Download, KeyRound, User, X, Shield, Copy, RefreshCw } from "lucide-react";
import { Download, KeyRound, User, X } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router";
import { toast } from "sonner";
import { QRCodeCanvas } from "qrcode.react";
import { downloadResticPasswordMutation } from "~/client/api-client/@tanstack/react-query.gen";
import { Button } from "~/client/components/ui/button";
import { Card, CardContent, CardDescription, CardTitle } from "~/client/components/ui/card";
import {
@ -16,12 +16,11 @@ import {
DialogTrigger,
} from "~/client/components/ui/dialog";
import { Input } from "~/client/components/ui/input";
import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot } from "~/client/components/ui/input-otp";
import { Label } from "~/client/components/ui/label";
import { appContext } from "~/context";
import type { Route } from "./+types/settings";
import { downloadResticPasswordMutation } from "~/client/api-client/@tanstack/react-query.gen";
import { authClient } from "~/client/lib/auth-client";
import { appContext } from "~/context";
import { TwoFactorSection } from "../components/two-factor-section";
import type { Route } from "./+types/settings";
export const handle = {
breadcrumb: () => [{ label: "Settings" }],
@ -50,22 +49,6 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
const [downloadPassword, setDownloadPassword] = useState("");
const [isChangingPassword, setIsChangingPassword] = useState(false);
// 2FA states
const [setup2FADialogOpen, setSetup2FADialogOpen] = useState(false);
const [disable2FADialogOpen, setDisable2FADialogOpen] = useState(false);
const [backupCodesDialogOpen, setBackupCodesDialogOpen] = useState(false);
const [setup2FAPassword, setSetup2FAPassword] = useState("");
const [disable2FAPassword, setDisable2FAPassword] = useState("");
const [totpUri, setTotpUri] = useState<string | null>(null);
const [verificationCode, setVerificationCode] = useState("");
const [backupCodes, setBackupCodes] = useState<string[]>([]);
const [setupStep, setSetupStep] = useState<"password" | "qr" | "verify">("password");
const [isEnabling2FA, setIsEnabling2FA] = useState(false);
const [isVerifying2FA, setIsVerifying2FA] = useState(false);
const [isDisabling2FA, setIsDisabling2FA] = useState(false);
const [isGeneratingBackupCodes, setIsGeneratingBackupCodes] = useState(false);
const [backupCodesPassword, setBackupCodesPassword] = useState("");
const navigate = useNavigate();
const handleLogout = async () => {
@ -100,7 +83,9 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
setDownloadPassword("");
},
onError: (error) => {
toast.error("Failed to download Restic password", { description: error.message });
toast.error("Failed to download Restic password", {
description: error.message,
});
},
});
@ -129,7 +114,9 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
}, 1500);
},
onError: (error) => {
toast.error("Failed to change password", { description: error.error.message });
toast.error("Failed to change password", {
description: error.error.message,
});
},
onRequest: () => {
setIsChangingPassword(true);
@ -156,151 +143,6 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
});
};
// 2FA handlers
const handleEnable2FA = async (e: React.FormEvent) => {
e.preventDefault();
if (!setup2FAPassword) {
toast.error("Password is required");
return;
}
setIsEnabling2FA(true);
const { data, error } = await authClient.twoFactor.enable({
password: setup2FAPassword,
issuer: "Zerobyte",
});
setIsEnabling2FA(false);
if (error) {
console.error(error);
toast.error("Failed to enable 2FA", { description: error.message });
return;
}
if (data?.totpURI && data?.backupCodes) {
setTotpUri(data.totpURI);
setBackupCodes(data.backupCodes);
setSetupStep("qr");
}
};
const handleVerify2FA = async () => {
if (verificationCode.length !== 6) {
toast.error("Please enter a 6-digit code");
return;
}
setIsVerifying2FA(true);
const { data, error } = await authClient.twoFactor.verifyTotp({
code: verificationCode,
});
setIsVerifying2FA(false);
if (error) {
console.error(error);
toast.error("Verification failed", { description: error.message });
setVerificationCode("");
return;
}
if (data) {
toast.success("Two-factor authentication enabled successfully");
// Refresh the session to get updated user data
await authClient.getSession();
// Reset and close dialog
handleClose2FASetup();
// Reload the page to update the UI
window.location.reload();
}
};
const handleDisable2FA = async (e: React.FormEvent) => {
e.preventDefault();
if (!disable2FAPassword) {
toast.error("Password is required");
return;
}
setIsDisabling2FA(true);
const { data, error } = await authClient.twoFactor.disable({
password: disable2FAPassword,
});
setIsDisabling2FA(false);
if (error) {
console.error(error);
toast.error("Failed to disable 2FA", { description: error.message });
return;
}
if (data) {
toast.success("Two-factor authentication disabled successfully");
setDisable2FADialogOpen(false);
setDisable2FAPassword("");
// Refresh the session to get updated user data
await authClient.getSession();
// Reload the page to update the UI
window.location.reload();
}
};
const handleGenerateBackupCodes = async (e: React.FormEvent) => {
e.preventDefault();
if (!backupCodesPassword) {
toast.error("Password is required");
return;
}
setIsGeneratingBackupCodes(true);
const { data, error } = await authClient.twoFactor.generateBackupCodes({
password: backupCodesPassword,
});
setIsGeneratingBackupCodes(false);
if (error) {
console.error(error);
toast.error("Failed to generate backup codes", { description: error.message });
return;
}
if (data?.backupCodes) {
setBackupCodes(data.backupCodes);
setBackupCodesPassword("");
toast.success("New backup codes generated successfully");
}
};
const handleClose2FASetup = () => {
setSetup2FADialogOpen(false);
setSetup2FAPassword("");
setTotpUri(null);
setVerificationCode("");
setBackupCodes([]);
setSetupStep("password");
};
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
toast.success("Copied to clipboard");
};
const copyAllBackupCodes = () => {
const text = backupCodes.join("\n");
navigator.clipboard.writeText(text);
toast.success("All backup codes copied to clipboard");
};
return (
<Card className="p-0 gap-0">
<div className="border-b border-border/50 bg-card-header p-6">
@ -315,6 +157,10 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
<Label>Username</Label>
<Input value={loaderData.user?.username || ""} disabled className="max-w-md" />
</div>
<div className="space-y-2">
<Label>Email</Label>
<Input value={loaderData.user?.email || ""} disabled className="max-w-md" />
</div>
</CardContent>
<div className="border-t border-border/50 bg-card-header p-6">
@ -433,308 +279,7 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
</Dialog>
</CardContent>
<div className="border-t border-border/50 bg-card-header p-6">
<CardTitle className="flex items-center gap-2">
<Shield className="size-5" />
Two-Factor Authentication
</CardTitle>
<CardDescription className="mt-1.5">Add an extra layer of security to your account</CardDescription>
</div>
<CardContent className="p-6 space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-1">
<p className="text-sm font-medium">
Status:&nbsp;
{loaderData.user?.twoFactorEnabled ? (
<span className="text-green-600 dark:text-green-400">Enabled</span>
) : (
<span className="text-muted-foreground">Disabled</span>
)}
</p>
<p className="text-xs text-muted-foreground max-w-xl">
Two-factor authentication adds an extra layer of security by requiring a code from your authenticator app
in addition to your password.
</p>
</div>
<div className="flex gap-2">
{!loaderData.user?.twoFactorEnabled ? (
<Button onClick={() => setSetup2FADialogOpen(true)}>Enable 2FA</Button>
) : (
<>
<Button variant="outline" onClick={() => setBackupCodesDialogOpen(true)}>
Backup Codes
</Button>
<Button variant="destructive" onClick={() => setDisable2FADialogOpen(true)}>
Disable 2FA
</Button>
</>
)}
</div>
</div>
<Dialog open={setup2FADialogOpen} onOpenChange={handleClose2FASetup}>
<DialogContent className="max-w-md">
{setupStep === "password" && (
<form onSubmit={handleEnable2FA}>
<DialogHeader>
<DialogTitle>Enable Two-Factor Authentication</DialogTitle>
<DialogDescription>
Enter your password to generate a QR code for your authenticator app
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="setup-password">Your Password</Label>
<Input
id="setup-password"
type="password"
value={setup2FAPassword}
onChange={(e) => setSetup2FAPassword(e.target.value)}
placeholder="Enter your password"
required
autoFocus
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={handleClose2FASetup}>
Cancel
</Button>
<Button type="submit" loading={isEnabling2FA}>
Continue
</Button>
</DialogFooter>
</form>
)}
{setupStep === "qr" && totpUri && (
<>
<DialogHeader>
<DialogTitle>Scan QR Code</DialogTitle>
<DialogDescription>
Scan this QR code with your authenticator app (Google Authenticator, Authy, etc.)
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="flex justify-center p-4 bg-white rounded-lg">
<QRCodeCanvas value={totpUri} size={200} />
</div>
<div className="space-y-2">
<Label className="text-xs">Manual Entry Code</Label>
<div className="flex items-center gap-2">
<Input
value={totpUri.split("secret=")[1]?.split("&")[0] || ""}
readOnly
className="text-xs font-mono"
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => copyToClipboard(totpUri.split("secret=")[1]?.split("&")[0] || "")}
>
<Copy className="h-4 w-4" />
</Button>
</div>
</div>
{backupCodes.length > 0 && (
<div className="space-y-2">
<Label className="text-xs">Backup Codes (Save these securely)</Label>
<div className="p-3 bg-muted rounded-md space-y-1 max-h-32 overflow-y-auto">
{backupCodes.map((code) => (
<div key={code} className="text-xs font-mono flex items-center justify-between">
<span>{code}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => copyToClipboard(code)}
className="h-6 w-6 p-0"
>
<Copy className="h-3 w-3" />
</Button>
</div>
))}
</div>
<Button type="button" variant="outline" size="sm" onClick={copyAllBackupCodes} className="w-full">
<Copy className="h-4 w-4 mr-2" />
Copy All Codes
</Button>
</div>
)}
</div>
<DialogFooter>
<Button type="button" onClick={() => setSetupStep("verify")}>
I've Scanned It
</Button>
</DialogFooter>
</>
)}
{setupStep === "verify" && (
<>
<DialogHeader>
<DialogTitle>Verify Setup</DialogTitle>
<DialogDescription>
Enter the 6-digit code from your authenticator app to complete setup
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>Verification Code</Label>
<div className="flex justify-center">
<InputOTP
maxLength={6}
value={verificationCode}
onChange={setVerificationCode}
onComplete={handleVerify2FA}
disabled={isVerifying2FA}
>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
</div>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setSetupStep("qr")}>
Back
</Button>
<Button
type="button"
onClick={handleVerify2FA}
loading={isVerifying2FA}
disabled={verificationCode.length !== 6}
>
Verify & enable
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
<Dialog open={disable2FADialogOpen} onOpenChange={setDisable2FADialogOpen}>
<DialogContent>
<form onSubmit={handleDisable2FA}>
<DialogHeader>
<DialogTitle>Disable Two-Factor Authentication</DialogTitle>
<DialogDescription>
Are you sure you want to disable 2FA? Your account will be less secure. Enter your password to
confirm.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="disable-password">Your Password</Label>
<Input
id="disable-password"
type="password"
value={disable2FAPassword}
onChange={(e) => setDisable2FAPassword(e.target.value)}
placeholder="Enter your password"
required
autoFocus
/>
</div>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => {
setDisable2FADialogOpen(false);
setDisable2FAPassword("");
}}
>
Cancel
</Button>
<Button type="submit" variant="destructive" loading={isDisabling2FA}>
Disable 2FA
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<Dialog open={backupCodesDialogOpen} onOpenChange={setBackupCodesDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Backup Codes</DialogTitle>
<DialogDescription>
Use these codes to access your account if you lose access to your authenticator app. Each code can only
be used once.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{backupCodes.length > 0 ? (
<>
<div className="p-3 bg-muted rounded-md space-y-1 max-h-48 overflow-y-auto">
{backupCodes.map((code) => (
<div key={code} className="text-sm font-mono flex items-center justify-between">
<span>{code}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => copyToClipboard(code)}
className="h-8 w-8 p-0"
>
<Copy className="h-4 w-4" />
</Button>
</div>
))}
</div>
<Button type="button" variant="outline" onClick={copyAllBackupCodes} className="w-full">
<Copy className="h-4 w-4 mr-2" />
Copy All Codes
</Button>
</>
) : (
<form onSubmit={handleGenerateBackupCodes} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="backup-codes-password">Your Password</Label>
<Input
id="backup-codes-password"
type="password"
value={backupCodesPassword}
onChange={(e) => setBackupCodesPassword(e.target.value)}
placeholder="Enter your password"
required
autoFocus
/>
</div>
<Button type="submit" loading={isGeneratingBackupCodes} className="w-full">
<RefreshCw className="h-4 w-4 mr-2" />
Generate New Backup Codes
</Button>
</form>
)}
</div>
<DialogFooter>
<Button
type="button"
onClick={() => {
setBackupCodesDialogOpen(false);
setBackupCodes([]);
setBackupCodesPassword("");
}}
>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</CardContent>
<TwoFactorSection twoFactorEnabled={loaderData.user?.twoFactorEnabled} />
</Card>
);
}

View file

@ -1,7 +1,10 @@
import { toast } from "sonner";
export async function copyToClipboard(textToCopy: string) {
// Navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(textToCopy);
toast.success("Copied to clipboard");
} else {
// Use the 'out of viewport hidden text area' trick
const textArea = document.createElement("textarea");
@ -16,6 +19,7 @@ export async function copyToClipboard(textToCopy: string) {
try {
document.execCommand("copy");
toast.success("Copied to clipboard");
} catch (error) {
console.error(error);
} finally {