Merge branch 'dev' into clients-pops-dev

This commit is contained in:
Owen
2025-07-14 16:59:00 -07:00
55 changed files with 5261 additions and 4194 deletions

View File

@@ -262,7 +262,19 @@ export default function ReverseProxyTargets(props: {
// make sure that the target IP is within the site subnet
const targetIp = data.ip;
const subnet = site.subnet;
if (!isIPInSubnet(targetIp, subnet)) {
try {
if (!isIPInSubnet(targetIp, subnet)) {
toast({
variant: "destructive",
title: t("targetWireGuardErrorInvalidIp"),
description: t(
"targetWireGuardErrorInvalidIpDescription"
)
});
return;
}
} catch (error) {
console.error(error);
toast({
variant: "destructive",
title: t("targetWireGuardErrorInvalidIp"),
@@ -885,10 +897,8 @@ function isIPInSubnet(subnet: string, ip: string): boolean {
const [subnetIP, maskBits] = subnet.split("/");
const mask = parseInt(maskBits);
const t = useTranslations();
if (mask < 0 || mask > 32) {
throw new Error(t("subnetMaskErrorInvalid"));
throw new Error("subnetMaskErrorInvalid");
}
// Convert IP addresses to binary numbers
@@ -905,17 +915,16 @@ function isIPInSubnet(subnet: string, ip: string): boolean {
function ipToNumber(ip: string): number {
// Validate IP address format
const parts = ip.split(".");
const t = useTranslations();
if (parts.length !== 4) {
throw new Error(t("ipAddressErrorInvalidFormat"));
throw new Error("ipAddressErrorInvalidFormat");
}
// Convert IP octets to 32-bit number
return parts.reduce((num, octet) => {
const oct = parseInt(octet);
if (isNaN(oct) || oct < 0 || oct > 255) {
throw new Error(t("ipAddressErrorInvalidOctet"));
throw new Error("ipAddressErrorInvalidOctet");
}
return (num << 8) + oct;
}, 0);

View File

@@ -3,7 +3,7 @@
import { ColumnDef } from "@tanstack/react-table";
import { UsersDataTable } from "./AdminUsersDataTable";
import { Button } from "@app/components/ui/button";
import { ArrowRight, ArrowUpDown } from "lucide-react";
import { ArrowRight, ArrowUpDown, MoreHorizontal } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
@@ -12,6 +12,12 @@ import { formatAxiosError } from "@app/lib/api";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { useTranslations } from "next-intl";
import {
DropdownMenu,
DropdownMenuItem,
DropdownMenuContent,
DropdownMenuTrigger
} from "@app/components/ui/dropdown-menu";
export type GlobalUserRow = {
id: string;
@@ -22,6 +28,8 @@ export type GlobalUserRow = {
idpId: number | null;
idpName: string;
dateCreated: string;
twoFactorEnabled: boolean | null;
twoFactorSetupRequested: boolean | null;
};
type Props = {
@@ -138,23 +146,79 @@ export default function UsersTable({ users }: Props) {
);
}
},
{
accessorKey: "twoFactorEnabled",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() =>
column.toggleSorting(column.getIsSorted() === "asc")
}
>
{t("twoFactor")}
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
const userRow = row.original;
return (
<div className="flex flex-row items-center gap-2">
<span>
{userRow.twoFactorEnabled ||
userRow.twoFactorSetupRequested ? (
<span className="text-green-500">
{t("enabled")}
</span>
) : (
<span>{t("disabled")}</span>
)}
</span>
</div>
);
}
},
{
id: "actions",
cell: ({ row }) => {
const r = row.original;
return (
<>
<div className="flex items-center justify-end">
<div className="flex items-center justify-end gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="h-8 w-8 p-0"
>
<span className="sr-only">
Open menu
</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => {
setSelected(r);
setIsDeleteModalOpen(true);
}}
>
{t("delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button
variant={"secondary"}
size="sm"
className="ml-2"
onClick={() => {
setSelected(r);
setIsDeleteModalOpen(true);
router.push(`/admin/users/${r.id}`);
}}
>
{t("delete")}
{t("edit")}
<ArrowRight className="ml-2 w-4 h-4" />
</Button>
</div>
</>

View File

@@ -0,0 +1,134 @@
"use client";
import { useEffect, useState } from "react";
import { SwitchInput } from "@app/components/SwitchInput";
import { Button } from "@app/components/ui/button";
import { toast } from "@app/hooks/useToast";
import { formatAxiosError } from "@app/lib/api";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { useTranslations } from "next-intl";
import { useParams } from "next/navigation";
import {
SettingsContainer,
SettingsSection,
SettingsSectionHeader,
SettingsSectionTitle,
SettingsSectionDescription,
SettingsSectionBody,
SettingsSectionForm
} from "@app/components/Settings";
import { UserType } from "@server/types/UserTypes";
export default function GeneralPage() {
const { userId } = useParams();
const api = createApiClient(useEnvContext());
const t = useTranslations();
const [loadingData, setLoadingData] = useState(true);
const [loading, setLoading] = useState(false);
const [twoFactorEnabled, setTwoFactorEnabled] = useState(false);
const [userType, setUserType] = useState<UserType | null>(null);
useEffect(() => {
// Fetch current user 2FA status
const fetchUserData = async () => {
setLoadingData(true);
try {
const response = await api.get(`/user/${userId}`);
if (response.status === 200) {
const userData = response.data.data;
setTwoFactorEnabled(
userData.twoFactorEnabled ||
userData.twoFactorSetupRequested
);
setUserType(userData.type);
}
} catch (error) {
console.error("Failed to fetch user data:", error);
toast({
variant: "destructive",
title: t("userErrorDelete"),
description: formatAxiosError(error, t("userErrorDelete"))
});
}
setLoadingData(false);
};
fetchUserData();
}, [userId]);
const handleTwoFactorToggle = (enabled: boolean) => {
setTwoFactorEnabled(enabled);
};
const handleSaveSettings = async () => {
setLoading(true);
try {
console.log("twoFactorEnabled", twoFactorEnabled);
await api.post(`/user/${userId}/2fa`, {
twoFactorSetupRequested: twoFactorEnabled
});
setTwoFactorEnabled(twoFactorEnabled);
} catch (error) {
toast({
variant: "destructive",
title: t("otpErrorEnable"),
description: formatAxiosError(
error,
t("otpErrorEnableDescription")
)
});
} finally {
setLoading(false);
}
};
if (loadingData) {
return null;
}
return (
<>
<SettingsContainer>
<SettingsSection>
<SettingsSectionHeader>
<SettingsSectionTitle>
{t("general")}
</SettingsSectionTitle>
<SettingsSectionDescription>
{t("userDescription2")}
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsSectionBody>
<SettingsSectionForm>
<div className="space-y-6">
<SwitchInput
id="two-factor-auth"
label={t("otpAuth")}
checked={twoFactorEnabled}
disabled={userType !== UserType.Internal}
onCheckedChange={handleTwoFactorToggle}
/>
</div>
</SettingsSectionForm>
</SettingsSectionBody>
</SettingsSection>
</SettingsContainer>
<div className="flex justify-end mt-6">
<Button
type="button"
loading={loading}
disabled={loading}
onClick={handleSaveSettings}
>
{t("targetTlsSubmit")}
</Button>
</div>
</>
);
}

View File

@@ -0,0 +1,55 @@
import { internal } from "@app/lib/api";
import { AxiosResponse } from "axios";
import { redirect } from "next/navigation";
import { authCookieHeader } from "@app/lib/api/cookies";
import { AdminGetUserResponse } from "@server/routers/user/adminGetUser";
import { HorizontalTabs } from "@app/components/HorizontalTabs";
import { cache } from "react";
import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
import { getTranslations } from 'next-intl/server';
interface UserLayoutProps {
children: React.ReactNode;
params: Promise<{ userId: string }>;
}
export default async function UserLayoutProps(props: UserLayoutProps) {
const params = await props.params;
const { children } = props;
const t = await getTranslations();
let user = null;
try {
const getUser = cache(async () =>
internal.get<AxiosResponse<AdminGetUserResponse>>(
`/user/${params.userId}`,
await authCookieHeader()
)
);
const res = await getUser();
user = res.data.data;
} catch {
redirect(`/admin/users`);
}
const navItems = [
{
title: t('general'),
href: "/admin/users/{userId}/general"
}
];
return (
<>
<SettingsSectionTitle
title={`${user?.email || user?.name || user?.username}`}
description={t('userDescription2')}
/>
<HorizontalTabs items={navItems}>
{children}
</HorizontalTabs>
</>
);
}

View File

@@ -0,0 +1,8 @@
import { redirect } from "next/navigation";
export default async function UserPage(props: {
params: Promise<{ userId: string }>;
}) {
const { userId } = await props.params;
redirect(`/admin/users/${userId}/general`);
}

View File

@@ -38,7 +38,9 @@ export default async function UsersPage(props: PageProps) {
idpId: row.idpId,
idpName: row.idpName || t('idpNameInternal'),
dateCreated: row.dateCreated,
serverAdmin: row.serverAdmin
serverAdmin: row.serverAdmin,
twoFactorEnabled: row.twoFactorEnabled,
twoFactorSetupRequested: row.twoFactorSetupRequested
};
});

View File

@@ -0,0 +1,62 @@
"use client";
import { useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle
} from "@/components/ui/card";
import TwoFactorSetupForm from "@app/components/TwoFactorSetupForm";
import { useTranslations } from "next-intl";
import { cleanRedirect } from "@app/lib/cleanRedirect";
export default function Setup2FAPage() {
const router = useRouter();
const searchParams = useSearchParams();
const redirect = searchParams?.get("redirect");
const email = searchParams?.get("email");
const t = useTranslations();
// Redirect to login if no email is provided
useEffect(() => {
if (!email) {
router.push("/auth/login");
}
}, [email, router]);
const handleComplete = () => {
console.log("2FA setup complete", redirect, email);
if (redirect) {
const cleanUrl = cleanRedirect(redirect);
console.log("Redirecting to:", cleanUrl);
router.push(cleanUrl);
} else {
router.push("/");
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>{t("otpSetup")}</CardTitle>
<CardDescription>
{t("adminEnabled2FaOnYourAccount", { email: email || "your account" })}
</CardDescription>
</CardHeader>
<CardContent>
<TwoFactorSetupForm
email={email || undefined}
onComplete={handleComplete}
submitButtonText="Continue"
showCancelButton={false}
/>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,89 @@
"use client";
import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import {
Credenza,
CredenzaBody,
CredenzaClose,
CredenzaContent,
CredenzaDescription,
CredenzaFooter,
CredenzaHeader,
CredenzaTitle
} from "@app/components/Credenza";
import TwoFactorSetupForm from "./TwoFactorSetupForm";
import { useTranslations } from "next-intl";
import { useUserContext } from "@app/hooks/useUserContext";
type Enable2FaDialogProps = {
open: boolean;
setOpen: (val: boolean) => void;
};
export default function Enable2FaDialog({ open, setOpen }: Enable2FaDialogProps) {
const t = useTranslations();
const [currentStep, setCurrentStep] = useState(1);
const [loading, setLoading] = useState(false);
const formRef = useRef<{ handleSubmit: () => void }>(null);
const { user, updateUser } = useUserContext();
function reset() {
setCurrentStep(1);
setLoading(false);
}
const handleSubmit = () => {
if (formRef.current) {
formRef.current.handleSubmit();
}
};
return (
<Credenza
open={open}
onOpenChange={(val) => {
setOpen(val);
reset();
}}
>
<CredenzaContent>
<CredenzaHeader>
<CredenzaTitle>
{t('otpSetup')}
</CredenzaTitle>
<CredenzaDescription>
{t('otpSetupDescription')}
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
<TwoFactorSetupForm
ref={formRef}
isDialog={true}
submitButtonText={t('submit')}
cancelButtonText="Close"
showCancelButton={false}
onComplete={() => {setOpen(false); updateUser({ twoFactorEnabled: true });}}
onStepChange={setCurrentStep}
onLoadingChange={setLoading}
/>
</CredenzaBody>
<CredenzaFooter>
<CredenzaClose asChild>
<Button variant="outline">Close</Button>
</CredenzaClose>
{(currentStep === 1 || currentStep === 2) && (
<Button
type="button"
loading={loading}
disabled={loading}
onClick={handleSubmit}
>
{t('submit')}
</Button>
)}
</CredenzaFooter>
</CredenzaContent>
</Credenza>
);
}

View File

@@ -1,46 +1,7 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { AlertCircle, CheckCircle2 } from "lucide-react";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { AxiosResponse } from "axios";
import {
RequestTotpSecretBody,
RequestTotpSecretResponse,
VerifyTotpBody,
VerifyTotpResponse
} from "@server/routers/auth";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage
} from "@app/components/ui/form";
import {
Credenza,
CredenzaBody,
CredenzaClose,
CredenzaContent,
CredenzaDescription,
CredenzaFooter,
CredenzaHeader,
CredenzaTitle
} from "@app/components/Credenza";
import { toast } from "@app/hooks/useToast";
import { formatAxiosError } from "@app/lib/api";
import CopyTextBox from "@app/components/CopyTextBox";
import { QRCodeCanvas, QRCodeSVG } from "qrcode.react";
import { useUserContext } from "@app/hooks/useUserContext";
import { useTranslations } from "next-intl";
import Enable2FaDialog from "./Enable2FaDialog";
type Enable2FaProps = {
open: boolean;
@@ -48,261 +9,5 @@ type Enable2FaProps = {
};
export default function Enable2FaForm({ open, setOpen }: Enable2FaProps) {
const [step, setStep] = useState(1);
const [secretKey, setSecretKey] = useState("");
const [secretUri, setSecretUri] = useState("");
const [verificationCode, setVerificationCode] = useState("");
const [error, setError] = useState("");
const [success, setSuccess] = useState(false);
const [loading, setLoading] = useState(false);
const [backupCodes, setBackupCodes] = useState<string[]>([]);
const { user, updateUser } = useUserContext();
const api = createApiClient(useEnvContext());
const t = useTranslations();
const enableSchema = z.object({
password: z.string().min(1, { message: t('passwordRequired') })
});
const confirmSchema = z.object({
code: z.string().length(6, { message: t('pincodeInvalid') })
});
const enableForm = useForm<z.infer<typeof enableSchema>>({
resolver: zodResolver(enableSchema),
defaultValues: {
password: ""
}
});
const confirmForm = useForm<z.infer<typeof confirmSchema>>({
resolver: zodResolver(confirmSchema),
defaultValues: {
code: ""
}
});
const request2fa = async (values: z.infer<typeof enableSchema>) => {
setLoading(true);
const res = await api
.post<AxiosResponse<RequestTotpSecretResponse>>(
`/auth/2fa/request`,
{
password: values.password
} as RequestTotpSecretBody
)
.catch((e) => {
toast({
title: t('otpErrorEnable'),
description: formatAxiosError(
e,
t('otpErrorEnableDescription')
),
variant: "destructive"
});
});
if (res && res.data.data.secret) {
setSecretKey(res.data.data.secret);
setSecretUri(res.data.data.uri);
setStep(2);
}
setLoading(false);
};
const confirm2fa = async (values: z.infer<typeof confirmSchema>) => {
setLoading(true);
const res = await api
.post<AxiosResponse<VerifyTotpResponse>>(`/auth/2fa/enable`, {
code: values.code
} as VerifyTotpBody)
.catch((e) => {
toast({
title: t('otpErrorEnable'),
description: formatAxiosError(
e,
t('otpErrorEnableDescription')
),
variant: "destructive"
});
});
if (res && res.data.data.valid) {
setBackupCodes(res.data.data.backupCodes || []);
updateUser({ twoFactorEnabled: true });
setStep(3);
}
setLoading(false);
};
const handleVerify = () => {
if (verificationCode.length !== 6) {
setError(t('otpSetupCheckCode'));
return;
}
if (verificationCode === "123456") {
setSuccess(true);
setStep(3);
} else {
setError(t('otpSetupCheckCodeRetry'));
}
};
function reset() {
setLoading(false);
setStep(1);
setSecretKey("");
setSecretUri("");
setVerificationCode("");
setError("");
setSuccess(false);
setBackupCodes([]);
enableForm.reset();
confirmForm.reset();
}
return (
<Credenza
open={open}
onOpenChange={(val) => {
setOpen(val);
reset();
}}
>
<CredenzaContent>
<CredenzaHeader>
<CredenzaTitle>
{t('otpSetup')}
</CredenzaTitle>
<CredenzaDescription>
{t('otpSetupDescription')}
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
{step === 1 && (
<Form {...enableForm}>
<form
onSubmit={enableForm.handleSubmit(request2fa)}
className="space-y-4"
id="form"
>
<div className="space-y-4">
<FormField
control={enableForm.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>{t('password')}</FormLabel>
<FormControl>
<Input
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</form>
</Form>
)}
{step === 2 && (
<div className="space-y-4">
<p>
{t('otpSetupScanQr')}
</p>
<div className="h-[250px] mx-auto flex items-center justify-center">
<QRCodeCanvas value={secretUri} size={200} />
</div>
<div className="max-w-md mx-auto">
<CopyTextBox
text={secretUri}
wrapText={false}
/>
</div>
<Form {...confirmForm}>
<form
onSubmit={confirmForm.handleSubmit(
confirm2fa
)}
className="space-y-4"
id="form"
>
<div className="space-y-4">
<FormField
control={confirmForm.control}
name="code"
render={({ field }) => (
<FormItem>
<FormLabel>
{t('otpSetupSecretCode')}
</FormLabel>
<FormControl>
<Input
type="code"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</form>
</Form>
</div>
)}
{step === 3 && (
<div className="space-y-4 text-center">
<CheckCircle2
className="mx-auto text-green-500"
size={48}
/>
<p className="font-semibold text-lg">
{t('otpSetupSuccess')}
</p>
<p>
{t('otpSetupSuccessStoreBackupCodes')}
</p>
<div className="max-w-md mx-auto">
<CopyTextBox text={backupCodes.join("\n")} />
</div>
</div>
)}
</CredenzaBody>
<CredenzaFooter>
<CredenzaClose asChild>
<Button variant="outline">Close</Button>
</CredenzaClose>
{(step === 1 || step === 2) && (
<Button
type="button"
loading={loading}
disabled={loading}
onClick={() => {
if (step === 1) {
enableForm.handleSubmit(request2fa)();
} else {
confirmForm.handleSubmit(confirm2fa)();
}
}}
>
{t('submit')}
</Button>
)}
</CredenzaFooter>
</CredenzaContent>
</Credenza>
);
return <Enable2FaDialog open={open} setOpen={setOpen} />;
}

View File

@@ -48,6 +48,10 @@ export default function LocaleSwitcher() {
{
value: "zh-CN",
label: "简体中文"
},
{
value: "ko-KR",
label: "한국어"
}
]}
/>

View File

@@ -4,8 +4,8 @@ import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Button } from "@app/components/ui/button";
import { Input } from "@app/components/ui/input";
import {
Form,
FormControl,
@@ -13,20 +13,20 @@ import {
FormItem,
FormLabel,
FormMessage
} from "@/components/ui/form";
} from "@app/components/ui/form";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle
} from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
} from "@app/components/ui/card";
import { Alert, AlertDescription } from "@app/components/ui/alert";
import { LoginResponse } from "@server/routers/auth";
import { useRouter } from "next/navigation";
import { AxiosResponse } from "axios";
import { formatAxiosError } from "@app/lib/api";
import { LockIcon } from "lucide-react";
import { LockIcon, FingerprintIcon } from "lucide-react";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import {
@@ -41,6 +41,7 @@ import Image from "next/image";
import { GenerateOidcUrlResponse } from "@server/routers/idp";
import { Separator } from "./ui/separator";
import { useTranslations } from "next-intl";
import { startAuthentication } from "@simplewebauthn/browser";
export type LoginFormIDP = {
idpId: number;
@@ -65,6 +66,7 @@ export default function LoginForm({ redirect, onLogin, idps }: LoginFormProps) {
const hasIdp = idps && idps.length > 0;
const [mfaRequested, setMfaRequested] = useState(false);
const [showSecurityKeyPrompt, setShowSecurityKeyPrompt] = useState(false);
const t = useTranslations();
@@ -94,30 +96,104 @@ export default function LoginForm({ redirect, onLogin, idps }: LoginFormProps) {
}
});
async function initiateSecurityKeyAuth() {
setShowSecurityKeyPrompt(true);
setLoading(true);
setError(null);
try {
// Start WebAuthn authentication without email
const startRes = await api.post("/auth/security-key/authenticate/start", {});
if (!startRes) {
setError(t('securityKeyAuthError', {
defaultValue: "Failed to start security key authentication"
}));
return;
}
const { tempSessionId, ...options } = startRes.data.data;
// Perform WebAuthn authentication
try {
const credential = await startAuthentication(options);
// Verify authentication
const verifyRes = await api.post(
"/auth/security-key/authenticate/verify",
{ credential },
{
headers: {
'X-Temp-Session-Id': tempSessionId
}
}
);
if (verifyRes) {
if (onLogin) {
await onLogin();
}
}
} catch (error: any) {
if (error.name === 'NotAllowedError') {
if (error.message.includes('denied permission')) {
setError(t('securityKeyPermissionDenied', {
defaultValue: "Please allow access to your security key to continue signing in."
}));
} else {
setError(t('securityKeyRemovedTooQuickly', {
defaultValue: "Please keep your security key connected until the sign-in process completes."
}));
}
} else if (error.name === 'NotSupportedError') {
setError(t('securityKeyNotSupported', {
defaultValue: "Your security key may not be compatible. Please try a different security key."
}));
} else {
setError(t('securityKeyUnknownError', {
defaultValue: "There was a problem using your security key. Please try again."
}));
}
}
} catch (e: any) {
if (e.isAxiosError) {
setError(formatAxiosError(e, t('securityKeyAuthError', {
defaultValue: "Failed to authenticate with security key"
})));
} else {
console.error(e);
setError(e.message || t('securityKeyAuthError', {
defaultValue: "Failed to authenticate with security key"
}));
}
} finally {
setLoading(false);
setShowSecurityKeyPrompt(false);
}
}
async function onSubmit(values: any) {
const { email, password } = form.getValues();
const { code } = mfaForm.getValues();
setLoading(true);
setError(null);
setShowSecurityKeyPrompt(false);
const res = await api
.post<AxiosResponse<LoginResponse>>("/auth/login", {
try {
const res = await api.post<AxiosResponse<LoginResponse>>("/auth/login", {
email,
password,
code
})
.catch((e) => {
console.error(e);
setError(
formatAxiosError(e, t('loginError'))
);
});
if (res) {
setError(null);
const data = res.data.data;
if (data?.useSecurityKey) {
await initiateSecurityKeyAuth();
return;
}
if (data?.codeRequested) {
setMfaRequested(true);
setLoading(false);
@@ -134,12 +210,32 @@ export default function LoginForm({ redirect, onLogin, idps }: LoginFormProps) {
return;
}
if (data?.twoFactorSetupRequired) {
const setupUrl = `/auth/2fa/setup?email=${encodeURIComponent(email)}${redirect ? `&redirect=${encodeURIComponent(redirect)}` : ''}`;
router.push(setupUrl);
return;
}
if (onLogin) {
await onLogin();
}
} catch (e: any) {
if (e.isAxiosError) {
const errorMessage = formatAxiosError(e, t('loginError', {
defaultValue: "Failed to log in"
}));
setError(errorMessage);
return;
} else {
console.error(e);
setError(e.message || t('loginError', {
defaultValue: "Failed to log in"
}));
return;
}
} finally {
setLoading(false);
}
setLoading(false);
}
async function loginWithIdp(idpId: number) {
@@ -167,6 +263,17 @@ export default function LoginForm({ redirect, onLogin, idps }: LoginFormProps) {
return (
<div className="space-y-4">
{showSecurityKeyPrompt && (
<Alert>
<FingerprintIcon className="w-5 h-5 mr-2" />
<AlertDescription>
{t('securityKeyPrompt', {
defaultValue: "Please verify your identity using your security key. Make sure your security key is connected and ready."
})}
</AlertDescription>
</Alert>
)}
{!mfaRequested && (
<>
<Form {...form}>
@@ -216,6 +323,16 @@ export default function LoginForm({ redirect, onLogin, idps }: LoginFormProps) {
</Link>
</div>
</div>
<div className="flex flex-col space-y-2">
<Button type="submit" disabled={loading}>
{loading ? t('idpConnectingToProcess', {
defaultValue: "Connecting..."
}) : t('login', {
defaultValue: "Log in"
})}
</Button>
</div>
</form>
</Form>
</>
@@ -250,9 +367,9 @@ export default function LoginForm({ redirect, onLogin, idps }: LoginFormProps) {
pattern={
REGEXP_ONLY_DIGITS_AND_CHARS
}
onChange={(e) => {
field.onChange(e);
if (e.length === 6) {
onChange={(value: string) => {
field.onChange(value);
if (value.length === 6) {
mfaForm.handleSubmit(onSubmit)();
}
}}
@@ -311,14 +428,17 @@ export default function LoginForm({ redirect, onLogin, idps }: LoginFormProps) {
{!mfaRequested && (
<>
<Button
type="submit"
form="form"
type="button"
variant="outline"
className="w-full"
onClick={initiateSecurityKeyAuth}
loading={loading}
disabled={loading}
disabled={loading || showSecurityKeyPrompt}
>
<LockIcon className="w-4 h-4 mr-2" />
{t('login')}
<FingerprintIcon className="w-4 h-4 mr-2" />
{t('securityKeyLogin', {
defaultValue: "Sign in with security key"
})}
</Button>
{hasIdp && (

View File

@@ -23,7 +23,10 @@ function getActionsCategories(root: boolean) {
[t('actionGetOrg')]: "getOrg",
[t('actionUpdateOrg')]: "updateOrg",
[t('actionGetOrgUser')]: "getOrgUser",
[t('actionListOrgDomains')]: "listOrgDomains",
[t('actionInviteUser')]: "inviteUser",
[t('actionRemoveUser')]: "removeUser",
[t('actionListUsers')]: "listUsers",
[t('actionListOrgDomains')]: "listOrgDomains"
},
Site: {
@@ -65,16 +68,9 @@ function getActionsCategories(root: boolean) {
[t('actionGetRole')]: "getRole",
[t('actionListRole')]: "listRoles",
[t('actionUpdateRole')]: "updateRole",
[t('actionListAllowedRoleResources')]: "listRoleResources"
},
User: {
[t('actionInviteUser')]: "inviteUser",
[t('actionRemoveUser')]: "removeUser",
[t('actionListUsers')]: "listUsers",
[t('actionListAllowedRoleResources')]: "listRoleResources",
[t('actionAddUserRole')]: "addUserRole"
},
"Access Token": {
[t('actionGenerateAccessToken')]: "generateAccessToken",
[t('actionDeleteAccessToken')]: "deleteAcessToken",
@@ -114,6 +110,11 @@ function getActionsCategories(root: boolean) {
[t('actionListIdpOrgs')]: "listIdpOrgs",
[t('actionUpdateIdpOrg')]: "updateIdpOrg"
};
actionsByCategory["User"] = {
[t('actionUpdateUser')]: "updateUser",
[t('actionGetUser')]: "getUser"
};
}
return actionsByCategory;

View File

@@ -20,7 +20,8 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import { useUserContext } from "@app/hooks/useUserContext";
import Disable2FaForm from "./Disable2FaForm";
import Enable2FaForm from "./Enable2FaForm";
import SecurityKeyForm from "./SecurityKeyForm";
import Enable2FaDialog from "./Enable2FaDialog";
import SupporterStatus from "./SupporterStatus";
import { UserType } from "@server/types/UserTypes";
import LocaleSwitcher from "@app/components/LocaleSwitcher";
@@ -39,6 +40,7 @@ export default function ProfileIcon() {
const [openEnable2fa, setOpenEnable2fa] = useState(false);
const [openDisable2fa, setOpenDisable2fa] = useState(false);
const [openSecurityKey, setOpenSecurityKey] = useState(false);
const t = useTranslations();
@@ -70,8 +72,12 @@ export default function ProfileIcon() {
return (
<>
<Enable2FaForm open={openEnable2fa} setOpen={setOpenEnable2fa} />
<Enable2FaDialog open={openEnable2fa} setOpen={setOpenEnable2fa} />
<Disable2FaForm open={openDisable2fa} setOpen={setOpenDisable2fa} />
<SecurityKeyForm
open={openSecurityKey}
setOpen={setOpenSecurityKey}
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -105,6 +111,31 @@ export default function ProfileIcon() {
)}
</DropdownMenuLabel>
<DropdownMenuSeparator />
{user?.type === UserType.Internal && (
<>
{!user.twoFactorEnabled && (
<DropdownMenuItem
onClick={() => setOpenEnable2fa(true)}
>
<span>{t("otpEnable")}</span>
</DropdownMenuItem>
)}
{user.twoFactorEnabled && (
<DropdownMenuItem
onClick={() => setOpenDisable2fa(true)}
>
<span>{t("otpDisable")}</span>
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={() => setOpenSecurityKey(true)}
>
<span>{t("securityKeyManage")}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
<DropdownMenuSeparator />
{user?.type === UserType.Internal && (
<>
{!user.twoFactorEnabled && (

View File

@@ -0,0 +1,859 @@
"use client";
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createApiClient } from "@app/lib/api";
import { formatAxiosError } from "@app/lib/api";
import { toast } from "@app/hooks/useToast";
import { Button } from "@app/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage
} from "@app/components/ui/form";
import { Input } from "@app/components/ui/input";
import { Alert, AlertDescription } from "@app/components/ui/alert";
import {
Credenza,
CredenzaBody,
CredenzaClose,
CredenzaContent,
CredenzaDescription,
CredenzaFooter,
CredenzaHeader,
CredenzaTitle
} from "@app/components/Credenza";
import { startRegistration } from "@simplewebauthn/browser";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { Card, CardContent } from "@app/components/ui/card";
import { Badge } from "@app/components/ui/badge";
import { Loader2, KeyRound, Trash2, Plus, Shield, Info } from "lucide-react";
import { cn } from "@app/lib/cn";
type SecurityKeyFormProps = {
open: boolean;
setOpen: (open: boolean) => void;
};
type SecurityKey = {
credentialId: string;
name: string;
lastUsed: string;
};
type DeleteSecurityKeyData = {
credentialId: string;
name: string;
};
type RegisterFormValues = {
name: string;
password: string;
code?: string;
};
type DeleteFormValues = {
password: string;
code?: string;
};
type FieldProps = {
field: {
value: string;
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
onBlur: () => void;
name: string;
ref: React.Ref<HTMLInputElement>;
};
};
export default function SecurityKeyForm({
open,
setOpen
}: SecurityKeyFormProps) {
const t = useTranslations();
const { env } = useEnvContext();
const api = createApiClient({ env });
const [securityKeys, setSecurityKeys] = useState<SecurityKey[]>([]);
const [isRegistering, setIsRegistering] = useState(false);
const [dialogState, setDialogState] = useState<
"list" | "register" | "register2fa" | "delete" | "delete2fa"
>("list");
const [selectedSecurityKey, setSelectedSecurityKey] =
useState<DeleteSecurityKeyData | null>(null);
const [deleteInProgress, setDeleteInProgress] = useState(false);
const [pendingDeleteCredentialId, setPendingDeleteCredentialId] = useState<
string | null
>(null);
const [pendingDeletePassword, setPendingDeletePassword] = useState<
string | null
>(null);
const [pendingRegisterData, setPendingRegisterData] = useState<{
name: string;
password: string;
} | null>(null);
const [register2FAForm, setRegister2FAForm] = useState<{ code: string }>({
code: ""
});
useEffect(() => {
loadSecurityKeys();
}, []);
const registerSchema = z.object({
name: z.string().min(1, { message: t("securityKeyNameRequired") }),
password: z.string().min(1, { message: t("passwordRequired") }),
code: z.string().optional()
});
const deleteSchema = z.object({
password: z.string().min(1, { message: t("passwordRequired") }),
code: z.string().optional()
});
const registerForm = useForm<RegisterFormValues>({
resolver: zodResolver(registerSchema),
defaultValues: {
name: "",
password: "",
code: ""
}
});
const deleteForm = useForm<DeleteFormValues>({
resolver: zodResolver(deleteSchema),
defaultValues: {
password: "",
code: ""
}
});
const loadSecurityKeys = async () => {
try {
const response = await api.get("/auth/security-key/list");
setSecurityKeys(response.data.data);
} catch (error) {
toast({
variant: "destructive",
description: formatAxiosError(error, t("securityKeyLoadError"))
});
}
};
const handleRegisterSecurityKey = async (values: RegisterFormValues) => {
try {
// Check browser compatibility first
if (!window.PublicKeyCredential) {
toast({
variant: "destructive",
description: t("securityKeyBrowserNotSupported", {
defaultValue:
"Your browser doesn't support security keys. Please use a modern browser like Chrome, Firefox, or Safari."
})
});
return;
}
setIsRegistering(true);
const startRes = await api.post(
"/auth/security-key/register/start",
{
name: values.name,
password: values.password,
code: values.code
}
);
// If 2FA is required
if (startRes.status === 202 && startRes.data.data?.codeRequested) {
setPendingRegisterData({
name: values.name,
password: values.password
});
setDialogState("register2fa");
setIsRegistering(false);
return;
}
const options = startRes.data.data;
try {
const credential = await startRegistration(options);
await api.post("/auth/security-key/register/verify", {
credential
});
toast({
description: t("securityKeyRegisterSuccess", {
defaultValue: "Security key registered successfully"
})
});
registerForm.reset();
setDialogState("list");
await loadSecurityKeys();
} catch (error: any) {
if (error.name === "NotAllowedError") {
if (error.message.includes("denied permission")) {
toast({
variant: "destructive",
description: t("securityKeyPermissionDenied", {
defaultValue:
"Please allow access to your security key to continue registration."
})
});
} else {
toast({
variant: "destructive",
description: t("securityKeyRemovedTooQuickly", {
defaultValue:
"Please keep your security key connected until the registration process completes."
})
});
}
} else if (error.name === "NotSupportedError") {
toast({
variant: "destructive",
description: t("securityKeyNotSupported", {
defaultValue:
"Your security key may not be compatible. Please try a different security key."
})
});
} else {
toast({
variant: "destructive",
description: t("securityKeyUnknownError", {
defaultValue:
"There was a problem registering your security key. Please try again."
})
});
}
throw error; // Re-throw to be caught by outer catch
}
} catch (error) {
console.error("Security key registration error:", error);
toast({
variant: "destructive",
description: formatAxiosError(
error,
t("securityKeyRegisterError", {
defaultValue: "Failed to register security key"
})
)
});
} finally {
setIsRegistering(false);
}
};
const handleDeleteSecurityKey = async (values: DeleteFormValues) => {
if (!selectedSecurityKey) return;
try {
setDeleteInProgress(true);
const encodedCredentialId = encodeURIComponent(
selectedSecurityKey.credentialId
);
const response = await api.delete(
`/auth/security-key/${encodedCredentialId}`,
{
data: {
password: values.password,
code: values.code
}
}
);
// If 2FA is required
if (response.status === 202 && response.data.data.codeRequested) {
setPendingDeleteCredentialId(encodedCredentialId);
setPendingDeletePassword(values.password);
setDialogState("delete2fa");
return;
}
toast({
description: t("securityKeyRemoveSuccess")
});
deleteForm.reset();
setSelectedSecurityKey(null);
setDialogState("list");
await loadSecurityKeys();
} catch (error) {
toast({
variant: "destructive",
description: formatAxiosError(
error,
t("securityKeyRemoveError")
)
});
} finally {
setDeleteInProgress(false);
}
};
const handle2FASubmit = async (values: DeleteFormValues) => {
if (!pendingDeleteCredentialId || !pendingDeletePassword) return;
try {
setDeleteInProgress(true);
await api.delete(
`/auth/security-key/${pendingDeleteCredentialId}`,
{
data: {
password: pendingDeletePassword,
code: values.code
}
}
);
toast({
description: t("securityKeyRemoveSuccess")
});
deleteForm.reset();
setSelectedSecurityKey(null);
setDialogState("list");
setPendingDeleteCredentialId(null);
setPendingDeletePassword(null);
await loadSecurityKeys();
} catch (error) {
toast({
variant: "destructive",
description: formatAxiosError(
error,
t("securityKeyRemoveError")
)
});
} finally {
setDeleteInProgress(false);
}
};
const handleRegister2FASubmit = async (values: { code: string }) => {
if (!pendingRegisterData) return;
try {
setIsRegistering(true);
const startRes = await api.post(
"/auth/security-key/register/start",
{
name: pendingRegisterData.name,
password: pendingRegisterData.password,
code: values.code
}
);
const options = startRes.data.data;
try {
const credential = await startRegistration(options);
await api.post("/auth/security-key/register/verify", {
credential
});
toast({
description: t("securityKeyRegisterSuccess", {
defaultValue: "Security key registered successfully"
})
});
registerForm.reset();
setDialogState("list");
setPendingRegisterData(null);
setRegister2FAForm({ code: "" });
await loadSecurityKeys();
} catch (error: any) {
if (error.name === "NotAllowedError") {
if (error.message.includes("denied permission")) {
toast({
variant: "destructive",
description: t("securityKeyPermissionDenied", {
defaultValue:
"Please allow access to your security key to continue registration."
})
});
} else {
toast({
variant: "destructive",
description: t("securityKeyRemovedTooQuickly", {
defaultValue:
"Please keep your security key connected until the registration process completes."
})
});
}
} else if (error.name === "NotSupportedError") {
toast({
variant: "destructive",
description: t("securityKeyNotSupported", {
defaultValue:
"Your security key may not be compatible. Please try a different security key."
})
});
} else {
toast({
variant: "destructive",
description: t("securityKeyUnknownError", {
defaultValue:
"There was a problem registering your security key. Please try again."
})
});
}
throw error; // Re-throw to be caught by outer catch
}
} catch (error) {
console.error("Security key registration error:", error);
toast({
variant: "destructive",
description: formatAxiosError(
error,
t("securityKeyRegisterError", {
defaultValue: "Failed to register security key"
})
)
});
setRegister2FAForm({ code: "" });
} finally {
setIsRegistering(false);
}
};
const onOpenChange = (open: boolean) => {
if (open) {
loadSecurityKeys();
} else {
registerForm.reset();
deleteForm.reset();
setSelectedSecurityKey(null);
setDialogState("list");
setPendingRegisterData(null);
setRegister2FAForm({ code: "" });
}
setOpen(open);
};
return (
<>
<Credenza open={open} onOpenChange={onOpenChange}>
<CredenzaContent>
{dialogState === "list" && (
<>
<CredenzaHeader>
<CredenzaTitle className="flex items-center gap-2">
{t("securityKeyManage")}
</CredenzaTitle>
<CredenzaDescription>
{t("securityKeyDescription")}
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-muted-foreground">
{t("securityKeyList")}
</h3>
<Button
onClick={() =>
setDialogState("register")
}
className="gap-2"
>
<Plus className="h-4 w-4" />
{t("securityKeyAdd")}
</Button>
</div>
{securityKeys.length > 0 ? (
<div className="space-y-2">
{securityKeys.map((securityKey) => (
<Card
key={
securityKey.credentialId
}
>
<CardContent className="flex items-center justify-between p-4">
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-secondary">
<KeyRound className="h-4 w-4 text-secondary-foreground" />
</div>
<div>
<p className="font-medium">
{
securityKey.name
}
</p>
<p className="text-xs text-muted-foreground">
{t(
"securityKeyLastUsed",
{
date: new Date(
securityKey.lastUsed
).toLocaleDateString()
}
)}
</p>
</div>
</div>
<Button
className="h-8 w-8 p-0 text-white hover:text-white/80"
onClick={() => {
setSelectedSecurityKey(
{
credentialId:
securityKey.credentialId,
name: securityKey.name
}
);
setDialogState(
"delete"
);
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</CardContent>
</Card>
))}
</div>
) : (
<div className="flex flex-col items-center justify-center py-8 text-center">
<Shield className="mb-2 h-12 w-12 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
{t("securityKeyNoKeysRegistered")}
</p>
<p className="text-xs text-muted-foreground">
{t("securityKeyNoKeysDescription")}
</p>
</div>
)}
{securityKeys.length === 1 && (
<Alert variant="default">
<Info className="h-4 w-4" />
<AlertDescription>
{t("securityKeyRecommendation")}
</AlertDescription>
</Alert>
)}
</div>
</CredenzaBody>
</>
)}
{dialogState === "register" && (
<>
<CredenzaHeader>
<CredenzaTitle>
{t("securityKeyRegisterTitle")}
</CredenzaTitle>
<CredenzaDescription>
{t("securityKeyRegisterDescription")}
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
<Form {...registerForm}>
<form
onSubmit={registerForm.handleSubmit(
handleRegisterSecurityKey
)}
className="space-y-4"
id="form"
>
<FormField
control={registerForm.control}
name="name"
render={({ field }: FieldProps) => (
<FormItem>
<FormLabel>
{t(
"securityKeyNameLabel"
)}
</FormLabel>
<FormControl>
<Input
{...field}
placeholder={t(
"securityKeyNamePlaceholder"
)}
disabled={
isRegistering
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={registerForm.control}
name="password"
render={({ field }: FieldProps) => (
<FormItem>
<FormLabel>
{t("password")}
</FormLabel>
<FormControl>
<Input
{...field}
type="password"
disabled={
isRegistering
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</CredenzaBody>
<CredenzaFooter>
<CredenzaClose asChild>
<Button
variant="outline"
onClick={() => {
registerForm.reset();
setDialogState("list");
}}
disabled={isRegistering}
>
{t("cancel")}
</Button>
</CredenzaClose>
<Button
type="submit"
form="form"
disabled={isRegistering}
className={cn(
"min-w-[100px]",
isRegistering &&
"cursor-not-allowed opacity-50"
)}
loading={isRegistering}
>
{t("securityKeyRegister")}
</Button>
</CredenzaFooter>
</>
)}
{dialogState === "register2fa" && (
<>
<CredenzaHeader>
<CredenzaTitle>
{t("securityKeyTwoFactorRequired")}
</CredenzaTitle>
<CredenzaDescription>
{t("securityKeyTwoFactorDescription")}
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
<div className="space-y-4">
<div>
<label className="text-sm font-medium">
{t("securityKeyTwoFactorCode")}
</label>
<Input
type="text"
value={register2FAForm.code}
onChange={(e) =>
setRegister2FAForm({
code: e.target.value
})
}
maxLength={6}
disabled={isRegistering}
/>
</div>
</div>
</CredenzaBody>
<CredenzaFooter>
<CredenzaClose asChild>
<Button
variant="outline"
onClick={() => {
setRegister2FAForm({ code: "" });
setDialogState("list");
setPendingRegisterData(null);
}}
disabled={isRegistering}
>
{t("cancel")}
</Button>
</CredenzaClose>
<Button
type="button"
className="min-w-[100px]"
disabled={
isRegistering ||
register2FAForm.code.length !== 6
}
loading={isRegistering}
onClick={() =>
handleRegister2FASubmit({
code: register2FAForm.code
})
}
>
{t("securityKeyRegister")}
</Button>
</CredenzaFooter>
</>
)}
{dialogState === "delete" && (
<>
<CredenzaHeader>
<CredenzaTitle className="flex items-center gap-2">
{t("securityKeyRemoveTitle")}
</CredenzaTitle>
<CredenzaDescription>
{t("securityKeyRemoveDescription", { name: selectedSecurityKey!.name! })}
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
<Form {...deleteForm}>
<form
onSubmit={deleteForm.handleSubmit(
handleDeleteSecurityKey
)}
className="space-y-4"
id="delete-form"
>
<FormField
control={deleteForm.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("password")}
</FormLabel>
<FormControl>
<Input
{...field}
type="password"
disabled={
deleteInProgress
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</CredenzaBody>
<CredenzaFooter>
<CredenzaClose asChild>
<Button
variant="outline"
onClick={() => {
deleteForm.reset();
setSelectedSecurityKey(null);
setDialogState("list");
}}
disabled={deleteInProgress}
>
{t("cancel")}
</Button>
</CredenzaClose>
<Button
type="submit"
form="delete-form"
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={deleteInProgress}
loading={deleteInProgress}
>
{t("securityKeyRemove")}
</Button>
</CredenzaFooter>
</>
)}
{dialogState === "delete2fa" && (
<>
<CredenzaHeader>
<CredenzaTitle>
{t("securityKeyTwoFactorRequired")}
</CredenzaTitle>
<CredenzaDescription>
{t("securityKeyTwoFactorRemoveDescription")}
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
<Form {...deleteForm}>
<form
onSubmit={deleteForm.handleSubmit(
handle2FASubmit
)}
className="space-y-4"
id="delete2fa-form"
>
<FormField
control={deleteForm.control}
name="code"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("securityKeyTwoFactorCode")}
</FormLabel>
<FormControl>
<Input
{...field}
type="text"
maxLength={6}
disabled={
deleteInProgress
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</CredenzaBody>
<CredenzaFooter>
<CredenzaClose asChild>
<Button
variant="outline"
onClick={() => {
deleteForm.reset();
setDialogState("list");
setPendingDeleteCredentialId(null);
setPendingDeletePassword(null);
}}
disabled={deleteInProgress}
>
{t("cancel")}
</Button>
</CredenzaClose>
<Button
type="submit"
form="delete2fa-form"
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={deleteInProgress}
loading={deleteInProgress}
>
{t("securityKeyRemove")}
</Button>
</CredenzaFooter>
</>
)}
</CredenzaContent>
</Credenza>
</>
);
}

View File

@@ -6,6 +6,7 @@ interface SwitchComponentProps {
id: string;
label?: string;
description?: string;
checked?: boolean;
defaultChecked?: boolean;
disabled?: boolean;
onCheckedChange: (checked: boolean) => void;
@@ -16,6 +17,7 @@ export function SwitchInput({
label,
description,
disabled,
checked,
defaultChecked = false,
onCheckedChange
}: SwitchComponentProps) {
@@ -24,6 +26,7 @@ export function SwitchInput({
<div className="flex items-center space-x-2 mb-2">
<Switch
id={id}
checked={checked}
defaultChecked={defaultChecked}
onCheckedChange={onCheckedChange}
disabled={disabled}

View File

@@ -0,0 +1,327 @@
"use client";
import { useState, forwardRef, useImperativeHandle, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { CheckCircle2 } from "lucide-react";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { AxiosResponse } from "axios";
import {
LoginResponse,
RequestTotpSecretBody,
RequestTotpSecretResponse,
VerifyTotpBody,
VerifyTotpResponse
} from "@server/routers/auth";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage
} from "@app/components/ui/form";
import { toast } from "@app/hooks/useToast";
import { formatAxiosError } from "@app/lib/api";
import CopyTextBox from "@app/components/CopyTextBox";
import { QRCodeCanvas } from "qrcode.react";
import { useUserContext } from "@app/hooks/useUserContext";
import { useTranslations } from "next-intl";
type TwoFactorSetupFormProps = {
onComplete?: (email: string, password: string) => void;
onCancel?: () => void;
isDialog?: boolean;
email?: string;
password?: string;
submitButtonText?: string;
cancelButtonText?: string;
showCancelButton?: boolean;
onStepChange?: (step: number) => void;
onLoadingChange?: (loading: boolean) => void;
};
const TwoFactorSetupForm = forwardRef<
{ handleSubmit: () => void },
TwoFactorSetupFormProps
>(
(
{
onComplete,
onCancel,
isDialog = false,
email,
password: initialPassword,
submitButtonText,
cancelButtonText,
showCancelButton = false,
onStepChange,
onLoadingChange
},
ref
) => {
const [step, setStep] = useState(1);
const [secretKey, setSecretKey] = useState("");
const [secretUri, setSecretUri] = useState("");
const [loading, setLoading] = useState(false);
const [backupCodes, setBackupCodes] = useState<string[]>([]);
const api = createApiClient(useEnvContext());
const t = useTranslations();
// Notify parent of step and loading changes
useEffect(() => {
onStepChange?.(step);
}, [step, onStepChange]);
useEffect(() => {
onLoadingChange?.(loading);
}, [loading, onLoadingChange]);
const enableSchema = z.object({
password: z.string().min(1, { message: t("passwordRequired") })
});
const confirmSchema = z.object({
code: z.string().length(6, { message: t("pincodeInvalid") })
});
const enableForm = useForm<z.infer<typeof enableSchema>>({
resolver: zodResolver(enableSchema),
defaultValues: {
password: initialPassword || ""
}
});
const confirmForm = useForm<z.infer<typeof confirmSchema>>({
resolver: zodResolver(confirmSchema),
defaultValues: {
code: ""
}
});
const request2fa = async (values: z.infer<typeof enableSchema>) => {
setLoading(true);
const endpoint = `/auth/2fa/request`;
const payload = { email, password: values.password };
const res = await api
.post<
AxiosResponse<RequestTotpSecretResponse>
>(endpoint, payload)
.catch((e) => {
toast({
title: t("otpErrorEnable"),
description: formatAxiosError(
e,
t("otpErrorEnableDescription")
),
variant: "destructive"
});
});
if (res && res.data.data.secret) {
setSecretKey(res.data.data.secret);
setSecretUri(res.data.data.uri);
setStep(2);
}
setLoading(false);
};
const confirm2fa = async (values: z.infer<typeof confirmSchema>) => {
setLoading(true);
const endpoint = `/auth/2fa/enable`;
const payload = {
email,
password: enableForm.getValues().password,
code: values.code
};
const res = await api
.post<AxiosResponse<VerifyTotpResponse>>(endpoint, payload)
.catch((e) => {
toast({
title: t("otpErrorEnable"),
description: formatAxiosError(
e,
t("otpErrorEnableDescription")
),
variant: "destructive"
});
});
if (res && res.data.data.valid) {
setBackupCodes(res.data.data.backupCodes || []);
await api
.post<AxiosResponse<LoginResponse>>("/auth/login", {
email,
password: enableForm.getValues().password,
code: values.code
})
.catch((e) => {
console.error(e);
});
setStep(3);
}
setLoading(false);
};
const handleSubmit = () => {
if (step === 1) {
enableForm.handleSubmit(request2fa)();
} else if (step === 2) {
confirmForm.handleSubmit(confirm2fa)();
}
};
const handleComplete = (email: string, password: string) => {
if (onComplete) {
onComplete(email, password);
}
};
useImperativeHandle(ref, () => ({
handleSubmit
}));
return (
<div className="space-y-4">
{step === 1 && (
<Form {...enableForm}>
<form
onSubmit={enableForm.handleSubmit(request2fa)}
className="space-y-4"
id="form"
>
<div className="space-y-4">
<FormField
control={enableForm.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("password")}
</FormLabel>
<FormControl>
<Input
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</form>
</Form>
)}
{step === 2 && (
<div className="space-y-4">
<p>{t("otpSetupScanQr")}</p>
<div className="h-[250px] mx-auto flex items-center justify-center">
<QRCodeCanvas value={secretUri} size={200} />
</div>
<div className="max-w-md mx-auto">
<CopyTextBox text={secretUri} wrapText={false} />
</div>
<Form {...confirmForm}>
<form
onSubmit={confirmForm.handleSubmit(confirm2fa)}
className="space-y-4"
id="form"
>
<FormField
control={confirmForm.control}
name="code"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("otpSetupSecretCode")}
</FormLabel>
<FormControl>
<Input type="code" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</div>
)}
{step === 3 && (
<div className="space-y-4 text-center">
<CheckCircle2
className="mx-auto text-green-500"
size={48}
/>
<p className="font-semibold text-lg">
{t("otpSetupSuccess")}
</p>
<p>{t("otpSetupSuccessStoreBackupCodes")}</p>
{backupCodes.length > 0 && (
<div className="max-w-md mx-auto">
<CopyTextBox text={backupCodes.join("\n")} />
</div>
)}
</div>
)}
{/* Action buttons - only show when not in dialog */}
{!isDialog && (
<div className="flex gap-2 justify-end">
{showCancelButton && onCancel && (
<Button
variant="outline"
onClick={onCancel}
disabled={loading}
>
{cancelButtonText || "Cancel"}
</Button>
)}
{(step === 1 || step === 2) && (
<Button
type="button"
loading={loading}
disabled={loading}
onClick={handleSubmit}
className="w-full"
>
{submitButtonText || t("submit")}
</Button>
)}
{step === 3 && (
<Button
onClick={() =>
handleComplete(
email!,
enableForm.getValues().password
)
}
className="w-full"
>
{t("continueToApplication")}
</Button>
)}
</div>
)}
</div>
);
}
);
export default TwoFactorSetupForm;

View File

@@ -1,4 +1,4 @@
export type Locale = (typeof locales)[number];
export const locales = ['en-US', 'es-ES', 'fr-FR', 'de-DE', 'nl-NL', 'it-IT', 'pl-PL', 'pt-PT', 'tr-TR', 'zh-CN'] as const;
export const locales = ['en-US', 'es-ES', 'fr-FR', 'de-DE', 'nl-NL', 'it-IT', 'pl-PL', 'pt-PT', 'tr-TR', 'zh-CN', 'ko-KR'] as const;
export const defaultLocale: Locale = 'en-US';