AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
import { useToast } from "@/components/molecules/Toast/use-toast";
import { useCaptureMarketingPrompt } from "@/hooks/useCaptureMarketingPrompt";
import { sanitizeAuthNext } from "@/lib/auth-redirect";
import { isBannedNotice } from "@/lib/auth/account-banned";
import {
EMAIL_VERIFICATION_NOTICE_PARAM,
getEmailVerificationNotice,
} from "@/lib/auth/email-verification";
import { useAuth } from "@/lib/auth/hooks/useAuth";
import { environment } from "@/services/environment";
import { loginFormSchema, LoginProvider } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import z from "zod";
import { login as loginAction } from "./actions";
export function useLoginPage() {
useCaptureMarketingPrompt();
const { user, isUserLoading, isLoggedIn } = useAuth();
const [feedback, setFeedback] = useState<string | null>(null);
const router = useRouter();
const searchParams = useSearchParams();
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const [isLoggingIn, setIsLoggingIn] = useState(false);
const [isGoogleLoading, setIsGoogleLoading] = useState(false);
const [showNotAllowedModal, setShowNotAllowedModal] = useState(false);
const [verificationEmail, setVerificationEmail] = useState<string | null>(
null,
);
const isCloudEnv = environment.isCloud();
// Same-origin redirect target; off-site values are dropped so a crafted
// `/login?next=https://phishing.site` cannot redirect users elsewhere.
const nextUrl = sanitizeAuthNext(searchParams.get("next"));
const verificationNotice = getEmailVerificationNotice(
searchParams.get(EMAIL_VERIFICATION_NOTICE_PARAM),
);
const showBannedNotice = isBannedNotice(searchParams);
// Only honour explicit `?next=` deep links here. Generic "already logged in
// on /login, get me out" is handled by OnboardingProvider so the user lands
// straight on /onboarding or /copilot. Otherwise we'd bounce
// /login → / → /copilot → /onboarding, and each hop renders before the next
// redirect — that intermediate /copilot render is the flash users see.
useEffect(() => {
if (isLoggedIn && !isLoggingIn && nextUrl) {
router.replace(nextUrl);
}
}, [isLoggedIn, isLoggingIn, nextUrl, router]);
const form = useForm<z.infer<typeof loginFormSchema>>({
resolver: zodResolver(loginFormSchema),
defaultValues: {
email: "",
password: "",
},
});
async function handleProviderLogin(provider: LoginProvider) {
setIsGoogleLoading(true);
setIsLoggingIn(true);
try {
// Include next URL in OAuth flow if present
const callbackUrl = nextUrl
? `/auth/callback?next=${encodeURIComponent(nextUrl)}`
: `/auth/callback`;
const fullCallbackUrl = `${window.location.origin}${callbackUrl}`;
const response = await fetch("/api/auth/login/with-provider", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ provider, redirectTo: fullCallbackUrl }),
});
if (!response.ok) {
const { error } = await response.json();
throw new Error(error || "Failed to start OAuth flow");
}
const { url } = await response.json();
if (url) window.location.href = url as string;
} catch (error) {
setIsGoogleLoading(false);
setIsLoggingIn(false);
setFeedback(
error instanceof Error ? error.message : "Failed to start OAuth flow",
);
}
}
async function handleLogin(data: z.infer<typeof loginFormSchema>) {
setIsLoading(true);
setIsLoggingIn(true);
if (data.email.includes("@agpt.co")) {
toast({
title: "Please use Google SSO to login using an AutoGPT email.",
variant: "default",
});
setIsLoading(false);
setIsLoggingIn(false);
return;
}
try {
const result = await loginAction(data.email, data.password, nextUrl);
if (result.error === "email_not_verified" && result.email) {
setVerificationEmail(result.email);
setIsLoading(false);
setIsLoggingIn(false);
return;
}
if (!result.success) {
throw new Error(result.error || "Login failed");
}
// Use full page navigation to ensure middleware processes the new auth cookies.
// router.replace() does a soft navigation where the cookie store may not
// immediately reflect cookies set by the server action, causing a blank page.
// This matches the OAuth flow which also uses window.location.href.
window.location.href = nextUrl || result.next || "/";
} catch (error) {
toast({
title:
error instanceof Error
? error.message
: "Unexpected error during login",
variant: "destructive",
});
setIsLoading(false);
setIsLoggingIn(false);
}
}
return {
form,
feedback,
nextUrl,
verificationEmail,
verificationNotice,
showBannedNotice,
user,
isLoading,
isGoogleLoading,
isCloudEnv,
isUserLoading,
showNotAllowedModal,
handleSubmit: form.handleSubmit(handleLogin),
handleProviderLogin,
handleCloseNotAllowedModal: () => setShowNotAllowedModal(false),
handleBackToLogin: () => setVerificationEmail(null),
};
}