"use client"; import * as React from "react"; import { useSearchParams } from "next/navigation"; import { zodResolver } from "@hookform/resolvers/zod"; import { signIn } from "next-auth/react"; import { useTranslations } from "next-intl"; import { useForm } from "react-hook-form"; import { toast } from "sonner"; import useSWR from "swr"; import * as z from "zod"; import { cn, fetcher } from "@/lib/utils"; import { userAuthSchema, userPasswordAuthSchema } from "@/lib/validations/auth"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Icons } from "@/components/shared/icons"; import { Skeleton } from "../ui/skeleton"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs"; interface UserAuthFormProps extends React.HTMLAttributes { type?: string; } type FormData = z.infer; type FormData2 = z.infer; export function UserAuthForm({ className, type, ...props }: UserAuthFormProps) { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: zodResolver(userAuthSchema), }); const { register: register2, handleSubmit: handleSubmit2, formState: { errors: errors2 }, } = useForm({ resolver: zodResolver(userPasswordAuthSchema), }); const [isLoading, startTransition] = React.useTransition(); const [isGoogleLoading, setIsGoogleLoading] = React.useState(false); const [isGithubLoading, setIsGithubLoading] = React.useState(false); const [isLinuxDoLoading, setIsLinuxDoLoading] = React.useState(false); const [suffixWhiteList, setSuffixWhiteList] = React.useState([]); const searchParams = useSearchParams(); const t = useTranslations("Auth"); const { data: loginMethod, isLoading: isLoadingMethod } = useSWR< Record >("/api/feature", fetcher, { revalidateOnFocus: false, }); React.useEffect(() => { if ( loginMethod && !!loginMethod["enableSuffixLimit"] && loginMethod["suffixWhiteList"].length > 0 ) { setSuffixWhiteList(loginMethod["suffixWhiteList"].split(",")); } }, [loginMethod]); const checkEmailSuffix = (email: string) => { if (suffixWhiteList.length > 0) { const suffix = email.split("@")[1]; if (!suffixWhiteList.includes(suffix)) { toast.warning( t("Email domain not supported, Please use one of the following:"), { description: suffixWhiteList.join(", "), }, ); return false; } } return true; }; async function onSubmit(data: FormData) { if (!checkEmailSuffix(data.email)) return; startTransition(async () => { const signInResult = await signIn("resend", { email: data.email.toLowerCase(), redirect: false, callbackUrl: searchParams?.get("from") || "/dashboard", }); if (!signInResult?.ok) { toast.error(t("Something went wrong"), { description: "Your sign in request failed. Please try again.", }); } toast.success(t("Check your email"), { description: `${t("We sent you a login link")}. ${t("Be sure to check your spam too")}.`, }); }); } async function onSubmitPwd(data: FormData2) { if (!checkEmailSuffix(data.email)) return; startTransition(async () => { const signInResult = await signIn("credentials", { name: data.name, email: data.email, password: data.password, redirect: false, callbackUrl: searchParams?.get("from") || "/dashboard", }); // console.log("[signInResult]", signInResult); if (signInResult?.error) { const errorMaps = { Configuration: t("Auth configuration error"), CredentialsSignin: t("Incorrect email or password"), }; const errorMessage = errorMaps[signInResult.error] || t("Unknown error"); toast.error(t("Something went wrong"), { description: `[${signInResult.error}] ${errorMessage}.`, }); } else { toast.success(t("Welcome back!")); window.location.reload(); // router.push(searchParams?.get("from") || "/dashboard"); } }); } const rendeSeparator = () => { return (
{t("Or continue with")}
); }; if (isLoadingMethod || !loginMethod) { return (
{rendeSeparator()}
); } const rendeResend = () => loginMethod["resend"] && (
{errors?.email && (

{errors.email.message}

)}
); const rendeCredentials = () => loginMethod["credentials"] && (
{errors2?.email && (

{errors2.email.message}

)}
{errors2?.password && (

{errors2.password.message}

)}

📢 {t("Unregistered users will automatically create an account")}.

); return (
{!loginMethod.registration && (

📢 {t("Administrator has disabled new user registration")}.

)} {loginMethod["google"] && ( )} {loginMethod["github"] && ( )} {loginMethod["linuxdo"] && ( )} {(loginMethod["google"] || loginMethod["github"] || loginMethod["linuxdo"]) && (loginMethod["resend"] || loginMethod["credentials"]) && rendeSeparator()} {loginMethod["resend"] && loginMethod["credentials"] ? ( {t("Email Code")} {t("Password")} {rendeResend()} {rendeCredentials()} ) : ( <> {rendeResend()} {rendeCredentials()} )}
); }