"use client"; import Link from "next/link"; import { useActionState, useEffect, useState, useRef, useCallback } from "react"; import { useTheme } from "next-themes"; import { Moon, Sun, X } from "lucide-react"; import { signIn } from "next-auth/react"; // Import signIn import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { AuthForm } from "@/components/auth-form"; import { SubmitButton } from "@/components/submit-button"; import { toast } from "@/components/toast"; import { type LoginActionState, login } from "../actions"; import { Button } from "@/components/ui/button"; import { AntigravityBackground } from "@/components/antigravity-background"; import { createClientLogger } from "@/lib/observability/client-logger"; const logger = createClientLogger("auth-login"); function getSafeLoginCallbackUrl() { const { origin, search } = window.location; const callbackUrl = new URLSearchParams(search).get("callbackUrl"); if (!callbackUrl?.startsWith("/")) return "/"; try { const { origin: targetOrigin, pathname, search, hash } = new URL(callbackUrl, origin); if (targetOrigin !== origin || pathname.startsWith("//")) return "/"; return pathname + search + hash; } catch { return "/"; } } export default function Page() { const [email, setEmail] = useState(""); const [isSuccessful, setIsSuccessful] = useState(false); const [siteName, setSiteName] = useState("AI Chatbot"); const [siteLogo, setSiteLogo] = useState(null); const [siteLogoDark, setSiteLogoDark] = useState(null); const [isDingTalkEnabled, setIsDingTalkEnabled] = useState(false); const [isGoogleEnabled, setIsGoogleEnabled] = useState(false); const [isGoogleConfigured, setIsGoogleConfigured] = useState(false); const [dingTalkAppKey, setDingTalkAppKey] = useState(null); const [dingTalkOrganizations, setDingTalkOrganizations] = useState([]); const [isRegistrationEnabled, setIsRegistrationEnabled] = useState(true); const [showDingTalkModal, setShowDingTalkModal] = useState(false); const [dingTalkIframeSrc, setDingTalkIframeSrc] = useState(""); const [showOrgMenu, setShowOrgMenu] = useState(false); const { setTheme, resolvedTheme } = useTheme(); const [mounted, setMounted] = useState(false); const [isHandlingToken, setIsHandlingToken] = useState(false); const [isCheckingExistingSession, setIsCheckingExistingSession] = useState(true); // 系统通知状态 const [notification, setNotification] = useState<{ enabled: boolean; title: string; content: string } | null>(null); const [showNotification, setShowNotification] = useState(false); const loginRedirectTimerRef = useRef(null); const loginRedirectFallbackTimerRef = useRef(null); const iframeRef = useRef(null); // 声明 formAction 在前面 const [state, formAction] = useActionState( login, { status: "idle", } ); useEffect(() => { let cancelled = false; fetch("/api/auth/validate-session", { cache: "no-store", credentials: "include", }) .then((res) => res.json()) .then((data) => { if (cancelled) return; if (data?.valid === true && data?.userType !== "guest") { window.location.replace(getSafeLoginCallbackUrl()); return; } setIsCheckingExistingSession(false); }) .catch(() => { if (!cancelled) { setIsCheckingExistingSession(false); } }); return () => { cancelled = true; }; }, []); // 使用 token 完成钉钉登录 const completeDingTalkLogin = useCallback(async (token: string) => { logger.debug("[DingTalk] Completing login with token", { hasToken: Boolean(token) }); setIsHandlingToken(true); const callbackUrl = getSafeLoginCallbackUrl(); try { // 获取 CSRF token const csrfRes = await fetch("/api/auth/csrf"); const { csrfToken } = await csrfRes.json(); logger.debug("[DingTalk] CSRF token resolved"); // 手动构造登录请求 const loginRes = await fetch("/api/auth/callback/credentials", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "X-Auth-Return-Redirect": "1", }, body: new URLSearchParams({ csrfToken, token, callbackUrl, }), credentials: "include", // 重要:确保 cookie 被发送和接收 }); // 检查响应类型 const contentType = loginRes.headers.get("content-type"); logger.debug("[DingTalk] Login response received", { status: loginRes.status, redirected: loginRes.redirected, contentType, }); if (loginRes.redirected || loginRes.status === 302) { // 登录成功,被重定向 logger.debug("[DingTalk] Login redirected successfully"); // 等待一小段时间确保 cookie 被设置 await new Promise(resolve => setTimeout(resolve, 300)); // 验证 session 是否创建成功 const sessionRes = await fetch("/api/auth/session"); const session = await sessionRes.json(); logger.debug("[DingTalk] Session validation completed", { hasUser: Boolean(session?.user), }); if (session && session.user) { logger.debug("[DingTalk] Session validated, redirecting..."); setIsSuccessful(true); // 使用 replace 而不是 href,避免在历史记录中留下登录页 // 增加短暂延迟确保 cookie 完全同步 setTimeout(() => { window.location.replace(callbackUrl); }, 200); } else { logger.error("[DingTalk] Session not created after login"); setIsHandlingToken(false); toast({ type: "error", description: "登录失败:无法创建会话" }); } } else if (contentType?.includes("application/json")) { const result = await loginRes.json(); logger.debug("[DingTalk] Login JSON response received", { ok: loginRes.ok, hasUrl: Boolean(result?.url), hasError: Boolean(result?.error), }); if (result.url || loginRes.ok) { // 登录成功 logger.debug("[DingTalk] Login successful"); // 等待一小段时间确保 cookie 被设置 await new Promise(resolve => setTimeout(resolve, 300)); // 验证 session const sessionRes = await fetch("/api/auth/session"); const session = await sessionRes.json(); logger.debug("[DingTalk] Session validation completed", { hasUser: Boolean(session?.user), }); if (session && session.user) { logger.debug("[DingTalk] Session validated, redirecting..."); setIsSuccessful(true); // 使用 replace 而不是 href,避免在历史记录中留下登录页 // 增加短暂延迟确保 cookie 完全同步 setTimeout(() => { window.location.replace(callbackUrl); }, 200); } else { logger.error("[DingTalk] Session not created"); setIsHandlingToken(false); toast({ type: "error", description: "登录失败:无法创建会话" }); } } else { // 登录失败 logger.error("[DingTalk] Login failed", { hasError: Boolean(result?.error), }); setIsHandlingToken(false); toast({ type: "error", description: result.error || "登录失败,请重试" }); } } else { // 未知响应 await loginRes.text(); logger.error("[DingTalk] Unexpected response type", { status: loginRes.status, contentType, }); setIsHandlingToken(false); toast({ type: "error", description: "登录失败:服务器响应异常" }); } } catch (error) { logger.error("[DingTalk] Login error:", error); setIsHandlingToken(false); toast({ type: "error", description: "登录发生错误:" + (error instanceof Error ? error.message : String(error)) }); } }, []); // Chunk 加载错误自动恢复 useEffect(() => { const handleChunkError = (event: ErrorEvent) => { const target = event.target as any; if (target?.src?.includes("/_next/static/chunks/") || event.message?.includes("Failed to load chunk")) { logger.error("[ChunkError] 检测到chunk加载失败,3秒后自动刷新页面"); // 3秒后自动刷新页面(清除缓存) setTimeout(() => { window.location.reload(); }, 3000); } }; window.addEventListener("error", handleChunkError, true); return () => window.removeEventListener("error", handleChunkError, true); }, []); // 初始化设置 useEffect(() => { setMounted(true); // 获取网站设置(添加时间戳防止缓存) fetch(`/api/site-settings?scope=auth&t=${Date.now()}`) .then((res) => res.json()) .then((data) => { logger.debug("[Login] Site settings loaded", { hasSiteName: Boolean(data.siteName), hasSiteLogo: Boolean(data.siteLogo), hasNotification: Boolean(data.notification), }); if (data.siteName) setSiteName(data.siteName); if (data.siteLogo) setSiteLogo(data.siteLogo); if (data.siteLogoDark) setSiteLogoDark(data.siteLogoDark); // 处理系统通知 if (data.notification && data.notification.enabled) { logger.debug("[Login] Setting notification and showing dialog"); setNotification(data.notification); // 每次访问登录页都显示通知(重要公告) setShowNotification(true); } else { logger.debug("[Login] Notification not enabled or missing"); } }) .catch((err) => { logger.error("[Login] Failed to fetch site settings:", err); }); // 获取认证设置 fetch("/api/auth-settings") .then((res) => res.json()) .then((data) => { if (data.isDingTalkEnabled) setIsDingTalkEnabled(true); if (data.isGoogleEnabled) setIsGoogleEnabled(true); if (data.isGoogleConfigured) setIsGoogleConfigured(true); if (data.dingTalkAppKey) setDingTalkAppKey(data.dingTalkAppKey); const rawOrganizations = Array.isArray(data.organizations) ? data.organizations : Array.isArray(data.dingTalkOrganizations) ? data.dingTalkOrganizations : []; if (rawOrganizations.length > 0) { setDingTalkOrganizations( rawOrganizations .map((org: { name?: string } | string) => typeof org === "string" ? org : org.name, ) .filter((name: string | undefined): name is string => Boolean(name?.trim())) .map((name: string) => name.trim()), ); } if (data.isRegistrationEnabled !== undefined) { setIsRegistrationEnabled(data.isRegistrationEnabled); } }) .catch((error) => { logger.error("[Login] Failed to fetch auth settings", error); }); }, []); const handleGoogleLogin = async () => { if (!isGoogleEnabled) { toast({ type: "error", description: "Google 登录未启用" }); return; } if (!isGoogleConfigured) { toast({ type: "error", description: "Google 登录未完成服务器配置" }); return; } await signIn("google", { redirectTo: getSafeLoginCallbackUrl() }); }; // 检查 URL 中是否有钉钉 Token(页面加载时自动登录) useEffect(() => { const params = new URLSearchParams(window.location.search); const token = params.get("dingtalk_token"); if (token) { completeDingTalkLogin(token); } }, [completeDingTalkLogin]); // 监听来自钉钉回调页面的消息 useEffect(() => { const handleMessage = (event: MessageEvent) => { logger.debug("[DingTalk] Received message", { type: event.data?.type, hasToken: Boolean(event.data?.token), }); if (event.data && event.data.type === "dingtalk_login_success") { setShowDingTalkModal(false); setDingTalkIframeSrc(""); // 使用返回的 token 完成 Auth.js 登录 if (event.data.token) { toast({ type: "success", description: "钉钉认证成功,正在登录..." }); completeDingTalkLogin(event.data.token); } else { toast({ type: "error", description: "钉钉登录失败:未获取到登录凭证" }); } } else if (event.data && event.data.type === "dingtalk_login_error") { setShowDingTalkModal(false); setDingTalkIframeSrc(""); toast({ type: "error", description: "钉钉登录失败:" + (event.data.message || "未知错误") }); } }; window.addEventListener("message", handleMessage); return () => window.removeEventListener("message", handleMessage); }, [completeDingTalkLogin]); // 处理登录状态变化 useEffect(() => { if (loginRedirectTimerRef.current) { window.clearTimeout(loginRedirectTimerRef.current); loginRedirectTimerRef.current = null; } if (loginRedirectFallbackTimerRef.current) { window.clearTimeout(loginRedirectFallbackTimerRef.current); loginRedirectFallbackTimerRef.current = null; } if (state.status === "failed") { setIsSuccessful(false); setIsHandlingToken(false); toast({ type: "error", description: "邮箱或密码不正确", }); } else if (state.status === "invalid_data") { setIsSuccessful(false); setIsHandlingToken(false); toast({ type: "error", description: "提交的信息校验失败", }); } else if (state.status === "success") { const callbackUrl = getSafeLoginCallbackUrl(); toast({ type: "success", description: "登录成功,正在跳转" }); setIsSuccessful(true); loginRedirectTimerRef.current = window.setTimeout(() => { window.location.replace(callbackUrl); }, 120); loginRedirectFallbackTimerRef.current = window.setTimeout(() => { window.location.assign(callbackUrl); }, 1600); } }, [state.status]); const handleSubmit = (formData: FormData) => { setIsSuccessful(false); setEmail(formData.get("email") as string); formAction(formData); }; useEffect(() => { return () => { if (loginRedirectTimerRef.current) { window.clearTimeout(loginRedirectTimerRef.current); } if (loginRedirectFallbackTimerRef.current) { window.clearTimeout(loginRedirectFallbackTimerRef.current); } }; }, []); const buildDingTalkLoginUrl = (orgName?: string) => { const params = new URLSearchParams(); if (orgName) params.set("org", orgName); const callbackUrl = getSafeLoginCallbackUrl(); if (callbackUrl !== "/") { params.set("callbackUrl", callbackUrl); } const query = params.toString(); return `/api/auth/dingtalk/login${query ? `?${query}` : ""}`; }; // 根据组织名称启动钉钉登录。钉钉授权页禁止第三方 iframe 嵌入,必须使用顶层跳转。 const startDingTalkLoginForOrg = (orgName: string) => { // 清除 URL 中的 token 参数,避免干扰 if ( typeof window !== "undefined" && window.location.search.includes("dingtalk_token") ) { const newUrl = window.location.pathname; window.history.replaceState({}, "", newUrl); } const loginUrl = buildDingTalkLoginUrl(orgName); logger.debug("[DingTalk] Redirecting org login", { hasOrg: Boolean(orgName), loginUrl, }); setShowDingTalkModal(true); setShowOrgMenu(false); window.location.assign(loginUrl); }; // 钉钉登录 - 支持多组织 const handleDingTalkLogin = () => { if (!isDingTalkEnabled) { toast({ type: "error", description: "钉钉登录未启用" }); return; } // 没有配置多组织:回退到单一 appKey 流程 if (dingTalkOrganizations.length === 0) { if (!dingTalkAppKey) { toast({ type: "error", description: "钉钉登录未正确配置" }); return; } if ( typeof window === "undefined" || typeof window.location === "undefined" ) { toast({ type: "error", description: "当前环境不支持钉钉登录" }); return; } // 清除 URL 中的 token 参数,避免干扰 if (window.location.search.includes("dingtalk_token")) { const newUrl = window.location.pathname; window.history.replaceState({}, "", newUrl); } const loginUrl = buildDingTalkLoginUrl(); logger.debug("[DingTalk] Redirecting OAuth login", { loginUrl }); window.location.assign(loginUrl); return; } // 只有一个组织:直接使用该组织登录 if (dingTalkOrganizations.length === 1) { startDingTalkLoginForOrg(dingTalkOrganizations[0] as string); return; } // 多组织:直接打开弹窗中的组织列表,避免悬浮菜单被页面层级覆盖 setDingTalkIframeSrc(""); setShowDingTalkModal(true); setShowOrgMenu(false); }; // 关闭钉钉登录弹窗 const closeDingTalkModal = () => { setShowDingTalkModal(false); setDingTalkIframeSrc(""); }; // 决定显示哪个 LOGO const displayLogo = mounted ? (resolvedTheme === "dark" && siteLogoDark ? siteLogoDark : siteLogo) : siteLogo; const hasThirdPartyLogin = (isDingTalkEnabled && (Boolean(dingTalkAppKey) || dingTalkOrganizations.length > 0)) || (isGoogleEnabled && isGoogleConfigured); if (isCheckingExistingSession) { return (
正在检查登录状态...
); } return (
{/* Antigravity 动画背景 */} {/* 主题切换按钮 */}
{displayLogo ? ( // eslint-disable-next-line @next/next/no-img-element {siteName} ) : null}

登录 {siteName}

使用邮箱与密码进入系统

登录 {hasThirdPartyLogin && (
或使用第三方登录
{isDingTalkEnabled && (dingTalkAppKey || dingTalkOrganizations.length > 0) ? ( ) : null} {isGoogleEnabled && isGoogleConfigured ? ( ) : null}
{/* 多组织下的小型选择框(悬浮在按钮附近) */} {dingTalkOrganizations.length > 1 && showOrgMenu && (
{dingTalkOrganizations.map((org) => ( ))}
)}
)} {isRegistrationEnabled && (

还没有账号? 立即注册 ,即可免费体验。

)}
{/* 钉钉登录 iframe 弹窗 / 多组织选择 */} {showDingTalkModal && (
{ if (e.target === e.currentTarget) closeDingTalkModal(); }} >

钉钉登录

{/* 多组织选择 */} {dingTalkOrganizations.length > 1 && !dingTalkIframeSrc && (

请选择要使用的钉钉组织进行登录:

{dingTalkOrganizations.map((org) => ( ))}

选择后将跳转到钉钉完成授权。

)} {/* 登录 iframe */} {dingTalkIframeSrc && (