feat: add authentication components and forms

This commit is contained in:
javayhu 2025-02-21 01:04:34 +08:00
parent 3eb8ddcbc4
commit 0298d48f8d
11 changed files with 927 additions and 0 deletions

View File

@ -0,0 +1,54 @@
"use client";
import { BottomButton } from "@/components/auth/bottom-button";
import { SocialLoginButton } from "@/components/auth/social-login-button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { siteConfig } from "@/config/site";
import { cn } from "@/lib/utils";
import Link from "next/link";
import { Logo } from "../logo";
interface AuthCardProps {
children: React.ReactNode;
headerLabel: string;
bottomButtonLabel: string;
bottomButtonHref: string;
showSocialLoginButton?: boolean;
className?: string;
}
export const AuthCard = ({
children,
headerLabel,
bottomButtonLabel,
bottomButtonHref,
showSocialLoginButton,
className,
}: AuthCardProps) => {
return (
<Card className={cn("shadow-none sm:w-[400px] max-w-[400px]", className)}>
<CardHeader className="items-center">
<Link href="/" prefetch={false}>
<Logo className="mb-2" />
</Link>
<CardDescription>{headerLabel}</CardDescription>
</CardHeader>
<CardContent>{children}</CardContent>
{showSocialLoginButton && (
<CardFooter>
<SocialLoginButton />
</CardFooter>
)}
<CardFooter>
<BottomButton label={bottomButtonLabel} href={bottomButtonHref} />
</CardFooter>
</Card>
);
};

View File

@ -0,0 +1,123 @@
"use client";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
// NOTICE: we changed the overlay background to be black/80
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",
className,
)}
{...props}
>
{children}
{/* NOTICE: we changed the close button position to the right */}
<DialogPrimitive.Close className="absolute right-36 top-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="size-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className,
)}
{...props}
/>
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className,
)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className,
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};

View File

@ -0,0 +1,22 @@
"use client";
import { Button } from "@/components/ui/button";
import Link from "next/link";
interface BottomButtonProps {
href: string;
label: string;
}
export const BottomButton = ({ href, label }: BottomButtonProps) => {
return (
<Button
variant="link"
className="font-normal w-full text-muted-foreground"
size="sm"
asChild
>
<Link href={href}>{label}</Link>
</Button>
);
};

View File

@ -0,0 +1,18 @@
import { AuthCard } from "@/components/auth/auth-card";
import { TriangleAlertIcon } from "lucide-react";
export const ErrorCard = () => {
return (
<AuthCard
headerLabel="Something went wrong!"
bottomButtonHref="/auth/login"
bottomButtonLabel="Back to login"
className="border-none"
>
<div className="w-full flex justify-center items-center py-4 gap-2">
<TriangleAlertIcon className="text-destructive size-4" />
<p className="font-medium text-destructive">Please try again.</p>
</div>
</AuthCard>
);
};

View File

@ -0,0 +1,69 @@
"use client";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/auth/auth-dialog";
import { LoginForm } from "@/components/auth/login-form";
import { useMediaQuery } from "@/hooks/use-media-query";
// import { authRoutes } from "@/routes";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
interface LoginWrapperProps {
children: React.ReactNode;
mode?: "modal" | "redirect";
asChild?: boolean;
}
export const LoginWrapper = ({
children,
mode = "redirect",
asChild,
}: LoginWrapperProps) => {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [isModalOpen, setIsModalOpen] = useState(false);
const { isTablet, isDesktop } = useMediaQuery();
const handleLogin = () => {
router.push("/auth/login");
};
// Close the modal on route change
// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
useEffect(() => {
setIsModalOpen(false);
}, [pathname, searchParams]);
// don't open the modal if the user is already in the auth pages
// keep isTablet or isDesktop open, if user resizes the window
// TODO: add auth routes
// const isAuthRoute = authRoutes.includes(pathname);
if (mode === "modal" && /* !isAuthRoute && */(isTablet || isDesktop)) {
return (
<Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
<DialogTrigger asChild={asChild}>{children}</DialogTrigger>
<DialogContent className="p-0 bg-transparent border-none">
<DialogHeader>
{/* `DialogContent` requires a `DialogTitle` for the component to be accessible for screen reader users. */}
<DialogTitle />
</DialogHeader>
<LoginForm />
</DialogContent>
</Dialog>
);
}
return (
// biome-ignore lint/a11y/useKeyWithClickEvents: <explanation>
<span onClick={handleLogin} className="cursor-pointer">
{children}
</span>
);
};

View File

@ -0,0 +1,158 @@
"use client";
// import { login } from "@/actions/login";
import { AuthCard } from "@/components/auth/auth-card";
import { Icons } from "@/components/icons/icons";
import { FormError } from "@/components/shared/form-error";
import { FormSuccess } from "@/components/shared/form-success";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { LoginSchema } from "@/lib/schemas";
import { cn } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import type * as z from "zod";
export const LoginForm = ({ className }: { className?: string }) => {
const searchParams = useSearchParams();
const callbackUrl = searchParams.get("callbackUrl");
const urlError =
searchParams.get("error") === "OAuthAccountNotLinked"
? "Email already in use with different provider!"
: "";
const [error, setError] = useState<string | undefined>("");
const [success, setSuccess] = useState<string | undefined>("");
const [isPending, startTransition] = useTransition();
const form = useForm<z.infer<typeof LoginSchema>>({
resolver: zodResolver(LoginSchema),
defaultValues: {
email: "",
password: "",
},
});
const onSubmit = (values: z.infer<typeof LoginSchema>) => {
setError("");
setSuccess("");
// startTransition(() => {
// login(values, callbackUrl)
// .then((data) => {
// // console.log('login, data:', data);
// if (data?.status === "error") {
// console.log("login, error:", data.message);
// form.reset();
// setError(data.message);
// }
// if (data?.status === "success") {
// console.log("login, success:", data.message);
// form.reset();
// setSuccess(data.message);
// // if success without redirect url, means sent confirmation email
// if (data.redirectUrl) {
// window.location.href = data.redirectUrl;
// }
// }
// })
// .catch((error) => {
// console.log("login, error:", error);
// setError("Something went wrong");
// });
// });
};
return (
<AuthCard
headerLabel="Welcome back"
bottomButtonLabel="Don't have an account? Sign up"
bottomButtonHref="/auth/register"
showSocialLoginButton
className={cn("", className)}
>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<div className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
{...field}
disabled={isPending}
placeholder="name@example.com"
type="email"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<div className="flex justify-between items-center">
<FormLabel>Password</FormLabel>
<Button
size="sm"
variant="link"
asChild
className="px-0 font-normal text-muted-foreground"
>
<Link href="/auth/reset" className="text-xs underline">
Forgot password?
</Link>
</Button>
</div>
<FormControl>
<Input
{...field}
disabled={isPending}
placeholder="******"
type="password"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormError message={error || urlError} />
<FormSuccess message={success} />
<Button
disabled={isPending}
size="lg"
type="submit"
className="w-full flex items-center justify-center gap-2"
>
{isPending ? (
<Icons.spinner className="w-4 h-4 animate-spin" />
) : (
""
)}
<span>Login</span>
</Button>
</form>
</Form>
</AuthCard>
);
};

View File

@ -0,0 +1,112 @@
"use client";
// import { newPassword } from "@/actions/new-password";
import { AuthCard } from "@/components/auth/auth-card";
import { Icons } from "@/components/icons/icons";
import { FormError } from "@/components/shared/form-error";
import { FormSuccess } from "@/components/shared/form-success";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { NewPasswordSchema } from "@/lib/schemas";
import { zodResolver } from "@hookform/resolvers/zod";
import { useSearchParams } from "next/navigation";
import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import type * as z from "zod";
export const NewPasswordForm = () => {
const searchParams = useSearchParams();
const token = searchParams.get("token");
const [error, setError] = useState<string | undefined>("");
const [success, setSuccess] = useState<string | undefined>("");
const [isPending, startTransition] = useTransition();
const form = useForm<z.infer<typeof NewPasswordSchema>>({
resolver: zodResolver(NewPasswordSchema),
defaultValues: {
password: "",
},
});
const onSubmit = (values: z.infer<typeof NewPasswordSchema>) => {
setError("");
setSuccess("");
// startTransition(() => {
// newPassword(values, token)
// .then((data) => {
// if (data?.status === "error") {
// console.log("newPassword, error:", data.message);
// setError(data.message);
// }
// if (data?.status === "success") {
// console.log("newPassword, success:", data.message);
// setSuccess(data.message);
// }
// })
// .catch(() => {
// console.log("newPassword, error:", error);
// setError("Something went wrong");
// });
// });
};
return (
<AuthCard
headerLabel="Reset password"
bottomButtonLabel="Back to login"
bottomButtonHref="/auth/login"
className="border-none"
>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<div className="space-y-4">
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input
{...field}
disabled={isPending}
placeholder="******"
type="password"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormError message={error} />
<FormSuccess message={success} />
<Button
disabled={isPending}
size="lg"
type="submit"
className="w-full flex items-center justify-center gap-2"
>
{isPending ? (
<Icons.spinner className="w-4 h-4 animate-spin" />
) : (
""
)}
<span>Reset password</span>
</Button>
</form>
</Form>
</AuthCard>
);
};

View File

@ -0,0 +1,62 @@
"use client";
// import { newVerification } from "@/actions/new-verification";
import { AuthCard } from "@/components/auth/auth-card";
import { Icons } from "@/components/icons/icons";
import { FormError } from "@/components/shared/form-error";
import { FormSuccess } from "@/components/shared/form-success";
import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
export const NewVerificationForm = () => {
const [error, setError] = useState<string | undefined>();
const [success, setSuccess] = useState<string | undefined>();
const searchParams = useSearchParams();
const token = searchParams.get("token");
const onSubmit = useCallback(() => {
if (success || error) return;
if (!token) {
setError("Missing token!");
return;
}
// newVerification(token)
// .then((data) => {
// if (data.status === "success") {
// setSuccess(data.message);
// console.log("newVerification, success:", data.message);
// }
// if (data.status === "error") {
// setError(data.message);
// console.log("newVerification, error:", data.message);
// }
// })
// .catch(() => {
// setError("Something went wrong");
// });
}, [token, success, error]);
useEffect(() => {
onSubmit();
}, [onSubmit]);
return (
<AuthCard
headerLabel="Confirming your verification"
bottomButtonLabel="Back to login"
bottomButtonHref="/auth/login"
className="border-none"
>
<div className="flex items-center w-full justify-center">
{!success && !error && (
<Icons.spinner className="w-4 h-4 animate-spin" />
)}
<FormSuccess message={success} />
{!success && <FormError message={error} />}
</div>
</AuthCard>
);
};

View File

@ -0,0 +1,141 @@
"use client";
// import { register } from "@/actions/register";
import { AuthCard } from "@/components/auth/auth-card";
import { Icons } from "@/components/icons/icons";
import { FormError } from "@/components/shared/form-error";
import { FormSuccess } from "@/components/shared/form-success";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { RegisterSchema } from "@/lib/schemas";
import { zodResolver } from "@hookform/resolvers/zod";
import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import type * as z from "zod";
export const RegisterForm = () => {
const [error, setError] = useState<string | undefined>("");
const [success, setSuccess] = useState<string | undefined>("");
const [isPending, startTransition] = useTransition();
const form = useForm<z.infer<typeof RegisterSchema>>({
resolver: zodResolver(RegisterSchema),
defaultValues: {
email: "",
password: "",
name: "",
},
});
const onSubmit = (values: z.infer<typeof RegisterSchema>) => {
setError("");
setSuccess("");
// startTransition(() => {
// register(values)
// .then((data) => {
// if (data.status === "error") {
// console.log("register, error:", data.message);
// setError(data.message);
// }
// if (data.status === "success") {
// console.log("register, success:", data.message);
// setSuccess(data.message);
// }
// })
// .catch((error) => {
// console.log("register, error:", error);
// setError("Something went wrong");
// });
// });
};
return (
<AuthCard
headerLabel="Create an account"
bottomButtonLabel="Already have an account? Sign in"
bottomButtonHref="/auth/login"
showSocialLoginButton
className="border-none"
>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<div className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input {...field} disabled={isPending} placeholder="name" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
{...field}
disabled={isPending}
placeholder="name@example.com"
type="email"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input
{...field}
disabled={isPending}
placeholder="******"
type="password"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormError message={error} />
<FormSuccess message={success} />
<Button
disabled={isPending}
size="lg"
type="submit"
className="w-full flex items-center justify-center gap-2"
>
{isPending ? (
<Icons.spinner className="w-4 h-4 animate-spin" />
) : (
""
)}
<span>Create an account</span>
</Button>
</form>
</Form>
</AuthCard>
);
};

View File

@ -0,0 +1,107 @@
"use client";
// import { reset } from "@/actions/reset";
import { AuthCard } from "@/components/auth/auth-card";
import { FormError } from "@/components/shared/form-error";
import { FormSuccess } from "@/components/shared/form-success";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { ResetSchema } from "@/lib/schemas";
import { zodResolver } from "@hookform/resolvers/zod";
import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import type * as z from "zod";
import { Icons } from "../icons/icons";
export const ResetForm = () => {
const [error, setError] = useState<string | undefined>("");
const [success, setSuccess] = useState<string | undefined>("");
const [isPending, startTransition] = useTransition();
const form = useForm<z.infer<typeof ResetSchema>>({
resolver: zodResolver(ResetSchema),
defaultValues: {
email: "",
},
});
const onSubmit = (values: z.infer<typeof ResetSchema>) => {
setError("");
setSuccess("");
// startTransition(() => {
// reset(values)
// .then((data) => {
// if (data.status === "error") {
// console.log("reset, error:", data.message);
// setError(data.message);
// }
// if (data.status === "success") {
// console.log("reset, success:", data.message);
// setSuccess(data.message);
// }
// })
// .catch((error) => {
// console.log("reset, error:", error);
// setError("Something went wrong");
// });
// });
};
return (
<AuthCard
headerLabel="Froget password?"
bottomButtonLabel="Back to login"
bottomButtonHref="/auth/login"
className="border-none"
>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<div className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
{...field}
disabled={isPending}
placeholder="name@example.com"
type="email"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormError message={error} />
<FormSuccess message={success} />
<Button
disabled={isPending}
size="lg"
type="submit"
className="w-full flex items-center justify-center gap-2"
>
{isPending ? (
<Icons.spinner className="w-4 h-4 animate-spin" />
) : (
""
)}
<span>Send reset email</span>
</Button>
</form>
</Form>
</AuthCard>
);
};

View File

@ -0,0 +1,61 @@
"use client";
import { Icons } from "@/components/icons/icons";
import { Button } from "@/components/ui/button";
// import { DEFAULT_LOGIN_REDIRECT } from "@/routes";
// import { signIn } from "next-auth/react";
import { useSearchParams } from "next/navigation";
import { useState } from "react";
import { FaBrandsGitHub } from "../icons/github";
import { FaBrandsGoogle } from "../icons/google";
/**
* social login buttons
*/
export const SocialLoginButton = () => {
const searchParams = useSearchParams();
const callbackUrl = searchParams.get("callbackUrl");
const [isLoading, setIsLoading] = useState<"google" | "github" | null>(null);
const onClick = async (provider: "google" | "github") => {
setIsLoading(provider);
// signIn(provider, {
// callbackUrl: callbackUrl || DEFAULT_LOGIN_REDIRECT,
// });
// no need to reset the loading state, keep loading before webpage redirects
// setIsLoading(null);
};
return (
<div className="w-full flex flex-col gap-4">
<Button
size="lg"
className="w-full"
variant="outline"
onClick={() => onClick("google")}
// disabled={isLoading === "google"}
>
{isLoading === "google" ? (
<Icons.spinner className="mr-2 size-4 animate-spin" />
) : (
<FaBrandsGoogle className="size-5 mr-2" />
)}
<span>Login with Google</span>
</Button>
<Button
size="lg"
className="w-full"
variant="outline"
onClick={() => onClick("github")}
// disabled={isLoading === "github"}
>
{isLoading === "github" ? (
<Icons.spinner className="mr-2 size-4 animate-spin" />
) : (
<FaBrandsGitHub className="size-5 mr-2" />
)}
<span>Login with GitHub</span>
</Button>
</div>
);
};