fosrl.pangolin/src/components/LoginForm.tsx

302 lines
11 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 "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
2024-12-22 14:38:17 -05:00
FormMessage
} from "@/components/ui/form";
import {
Card,
CardContent,
CardDescription,
CardHeader,
2024-12-22 14:38:17 -05:00
CardTitle
} from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { LoginResponse } from "@server/routers/auth";
import { useRouter } from "next/navigation";
import { AxiosResponse } from "axios";
2025-01-01 21:41:31 -05:00
import { formatAxiosError } from "@app/lib/api";;
import { LockIcon } 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-01-04 20:22:01 -05:00
import Image from 'next/image'
type LoginFormProps = {
redirect?: string;
onLogin?: () => void;
};
const formSchema = z.object({
email: z.string().email({ message: "Invalid email address" }),
password: z
.string()
2024-12-22 14:38:17 -05:00
.min(8, { message: "Password must be at least 8 characters" })
});
const mfaSchema = z.object({
code: z.string().length(6, { message: "Invalid code" })
});
export default function LoginForm({ redirect, onLogin }: 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);
2024-12-22 17:27:09 -05:00
const [mfaRequested, setMfaRequested] = useState(false);
2024-12-22 14:38:17 -05:00
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: ""
}
});
2024-12-22 14:38:17 -05:00
async function onSubmit(values: any) {
const { email, password } = form.getValues();
2024-12-22 16:59:30 -05:00
const { code } = mfaForm.getValues();
2024-12-15 17:47:07 -05:00
setLoading(true);
const res = await api
.post<AxiosResponse<LoginResponse>>("/auth/login", {
email,
password,
2024-12-22 14:38:17 -05:00
code
})
.catch((e) => {
console.error(e);
setError(
2024-12-22 14:38:17 -05:00
formatAxiosError(e, "An error occurred while logging in")
);
});
2024-12-22 14:38:17 -05:00
if (res) {
setError(null);
2024-12-22 14:38:17 -05:00
const data = res.data.data;
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;
}
2024-11-28 00:11:13 -05:00
if (onLogin) {
await onLogin();
}
}
setLoading(false);
}
return (
2025-01-03 22:32:24 -05:00
<div className="space-y-4">
2024-12-22 14:38:17 -05:00
{!mfaRequested && (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
2024-12-22 17:09:22 -05:00
className="space-y-4"
id="form"
2024-12-22 14:38:17 -05:00
>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
placeholder="Enter your email"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
2024-12-22 16:59:30 -05:00
<div className="space-y-4">
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input
type="password"
placeholder="Enter your 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"
>
2025-01-03 22:32:24 -05:00
Forgot your password?
2024-12-22 16:59:30 -05:00
</Link>
</div>
</div>
2024-12-22 14:38:17 -05:00
</form>
</Form>
)}
{mfaRequested && (
<>
<div className="text-center">
<h3 className="text-lg font-medium">
Two-Factor Authentication
</h3>
<p className="text-sm text-muted-foreground">
Enter the code from your authenticator app.
</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
}
>
<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}
>
Submit Code
</Button>
)}
{!mfaRequested && (
<Button
type="submit"
form="form"
className="w-full"
loading={loading}
disabled={loading}
>
<LockIcon className="w-4 h-4 mr-2" />
2025-01-03 22:32:24 -05:00
Log In
</Button>
)}
{mfaRequested && (
<Button
type="button"
className="w-full"
variant="outline"
onClick={() => {
setMfaRequested(false);
mfaForm.reset();
}}
>
2025-01-03 22:32:24 -05:00
Back to Log In
</Button>
)}
</div>
2024-12-22 14:38:17 -05:00
</div>
);
}