fosrl.pangolin/src/components/LoginForm.tsx

493 lines
19 KiB
TypeScript
Raw Normal View History

"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@app/components/ui/button";
import { Input } from "@app/components/ui/input";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
2024-12-22 14:38:17 -05:00
FormMessage
} from "@app/components/ui/form";
import {
Card,
CardContent,
CardDescription,
CardHeader,
2024-12-22 14:38:17 -05:00
CardTitle
} 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";
2025-04-13 17:57:27 -04:00
import { formatAxiosError } from "@app/lib/api";
import { LockIcon, FingerprintIcon } from "lucide-react";
2025-01-01 21:41:31 -05:00
import { createApiClient } from "@app/lib/api";
2024-12-15 17:47:07 -05:00
import { useEnvContext } from "@app/hooks/useEnvContext";
2024-12-22 14:38:17 -05:00
import {
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot
} from "./ui/input-otp";
2024-12-22 16:59:30 -05:00
import Link from "next/link";
2024-12-22 17:20:24 -05:00
import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
2025-04-13 17:57:27 -04:00
import Image from "next/image";
import { GenerateOidcUrlResponse } from "@server/routers/idp";
2025-04-18 17:45:59 -04:00
import { Separator } from "./ui/separator";
import { useTranslations } from "next-intl";
import { startAuthentication } from "@simplewebauthn/browser";
2025-04-18 17:45:59 -04:00
export type LoginFormIDP = {
idpId: number;
name: string;
};
type LoginFormProps = {
redirect?: string;
onLogin?: () => void | Promise<void>;
2025-04-18 17:45:59 -04:00
idps?: LoginFormIDP[];
};
2025-04-18 17:45:59 -04:00
export default function LoginForm({ redirect, onLogin, idps }: LoginFormProps) {
const router = useRouter();
2024-12-25 15:54:32 -05:00
const { env } = useEnvContext();
const api = createApiClient({ env });
2024-12-15 17:47:07 -05:00
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
2025-07-16 18:09:17 -07:00
const [securityKeyLoading, setSecurityKeyLoading] = useState(false);
2025-04-18 17:45:59 -04:00
const hasIdp = idps && idps.length > 0;
2024-12-22 17:27:09 -05:00
const [mfaRequested, setMfaRequested] = useState(false);
const [showSecurityKeyPrompt, setShowSecurityKeyPrompt] = useState(false);
2024-12-22 14:38:17 -05:00
const t = useTranslations();
const formSchema = z.object({
email: z.string().email({ message: t('emailInvalid') }),
password: z
.string()
.min(8, { message: t('passwordRequirementsChars') })
});
const mfaSchema = z.object({
code: z.string().length(6, { message: t('pincodeInvalid') })
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
2024-12-22 14:38:17 -05:00
password: ""
}
});
2024-12-22 14:38:17 -05:00
const mfaForm = useForm<z.infer<typeof mfaSchema>>({
resolver: zodResolver(mfaSchema),
defaultValues: {
code: ""
}
});
async function initiateSecurityKeyAuth() {
setShowSecurityKeyPrompt(true);
2025-07-16 18:09:17 -07:00
setSecurityKeyLoading(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);
2025-07-16 18:09:17 -07:00
// 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 {
2025-07-16 18:09:17 -07:00
setSecurityKeyLoading(false);
setShowSecurityKeyPrompt(false);
}
}
async function onSubmit(values: any) {
const { email, password } = form.getValues();
const { code } = mfaForm.getValues();
setLoading(true);
setError(null);
setShowSecurityKeyPrompt(false);
try {
const res = await api.post<AxiosResponse<LoginResponse>>("/auth/login", {
email,
password,
code
});
const data = res.data.data;
if (data?.useSecurityKey) {
await initiateSecurityKeyAuth();
return;
}
if (data?.codeRequested) {
setMfaRequested(true);
setLoading(false);
mfaForm.reset();
return;
}
if (data?.emailVerificationRequired) {
if (redirect) {
router.push(`/auth/verify-email?redirect=${redirect}`);
} else {
router.push("/auth/verify-email");
}
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);
}
}
async function loginWithIdp(idpId: number) {
try {
const res = await api.post<AxiosResponse<GenerateOidcUrlResponse>>(
`/auth/idp/${idpId}/oidc/generate-url`,
{
redirectUrl: redirect || "/"
}
);
console.log(res);
if (!res) {
setError(t('loginError'));
return;
}
const data = res.data.data;
window.location.href = data.redirectUrl;
} catch (e) {
console.error(formatAxiosError(e));
}
}
return (
2025-01-03 22:32:24 -05:00
<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>
)}
2024-12-22 14:38:17 -05:00
{!mfaRequested && (
2025-04-13 17:57:27 -04:00
<>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
id="form"
>
2024-12-22 16:59:30 -05:00
<FormField
control={form.control}
2025-04-13 17:57:27 -04:00
name="email"
2024-12-22 16:59:30 -05:00
render={({ field }) => (
<FormItem>
<FormLabel>{t('email')}</FormLabel>
2024-12-22 16:59:30 -05:00
<FormControl>
2025-04-13 17:57:27 -04:00
<Input {...field} />
2024-12-22 16:59:30 -05:00
</FormControl>
<FormMessage />
</FormItem>
)}
/>
2025-04-13 17:57:27 -04:00
<div className="space-y-4">
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>{t('password')}</FormLabel>
2025-04-13 17:57:27 -04:00
<FormControl>
<Input
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="text-center">
<Link
href={`/auth/reset-password${form.getValues().email ? `?email=${form.getValues().email}` : ""}`}
className="text-sm text-muted-foreground"
>
{t('passwordForgot')}
2025-04-13 17:57:27 -04:00
</Link>
</div>
2024-12-22 16:59:30 -05:00
</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>
2025-04-13 17:57:27 -04:00
</form>
</Form>
</>
2024-12-22 14:38:17 -05:00
)}
{mfaRequested && (
<>
<div className="text-center">
<h3 className="text-lg font-medium">
{t('otpAuth')}
</h3>
<p className="text-sm text-muted-foreground">
{t('otpAuthDescription')}
</p>
</div>
<Form {...mfaForm}>
<form
onSubmit={mfaForm.handleSubmit(onSubmit)}
className="space-y-4"
id="form"
>
<FormField
control={mfaForm.control}
name="code"
render={({ field }) => (
<FormItem>
<FormControl>
<div className="flex justify-center">
<InputOTP
maxLength={6}
{...field}
pattern={
REGEXP_ONLY_DIGITS_AND_CHARS
}
onChange={(value: string) => {
field.onChange(value);
if (value.length === 6) {
mfaForm.handleSubmit(onSubmit)();
}
}}
>
<InputOTPGroup>
<InputOTPSlot
index={0}
/>
<InputOTPSlot
index={1}
/>
<InputOTPSlot
index={2}
/>
<InputOTPSlot
index={3}
/>
<InputOTPSlot
index={4}
/>
<InputOTPSlot
index={5}
/>
</InputOTPGroup>
</InputOTP>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</>
)}
2024-12-22 14:38:17 -05:00
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
2024-12-22 14:38:17 -05:00
)}
<div className="space-y-4">
{mfaRequested && (
<Button
type="submit"
form="form"
className="w-full"
loading={loading}
disabled={loading}
>
{t('otpAuthSubmit')}
</Button>
)}
{!mfaRequested && (
2025-04-18 17:45:59 -04:00
<>
<Button
type="button"
variant="outline"
className="w-full"
onClick={initiateSecurityKeyAuth}
2025-07-16 18:09:17 -07:00
loading={securityKeyLoading}
disabled={securityKeyLoading || showSecurityKeyPrompt}
>
<FingerprintIcon className="w-4 h-4 mr-2" />
{t('securityKeyLogin', {
defaultValue: "Sign in with security key"
})}
</Button>
2025-04-18 17:45:59 -04:00
{hasIdp && (
<>
<div className="relative my-4">
<div className="absolute inset-0 flex items-center">
<Separator />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="px-2 bg-card text-muted-foreground">
{t('idpContinue')}
2025-04-18 17:45:59 -04:00
</span>
</div>
</div>
{idps.map((idp) => (
<Button
key={idp.idpId}
type="button"
variant="outline"
className="w-full"
onClick={() => {
loginWithIdp(idp.idpId);
}}
>
{idp.name}
</Button>
))}
</>
)}
</>
)}
{mfaRequested && (
<Button
type="button"
className="w-full"
variant="outline"
onClick={() => {
setMfaRequested(false);
mfaForm.reset();
}}
>
{t('otpAuthBack')}
</Button>
)}
</div>
2024-12-22 14:38:17 -05:00
</div>
);
}