/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import { ArrowRight as ActionArrowRight } from '@/components/common/icons/ActionIcons';
import React, {
useContext,
useEffect,
useRef,
useState,
useCallback,
useMemo,
lazy,
Suspense,
} from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import {
API,
getLogo,
showError,
showInfo,
getSystemName,
savePostLoginRedirect,
finishLogin as runLoginFlow,
onGitHubOAuthClicked,
onDiscordOAuthClicked,
onOIDCClicked,
onLinuxDOOAuthClicked,
onWeChatOpenOAuthClicked,
onWeChatMPOAuthClicked,
prepareCredentialRequestOptions,
buildAssertionResult,
isPasskeySupported,
} from '../../helpers';
import Turnstile from 'react-turnstile';
import { Button, Checkbox, Form, Icon, Modal } from '@/components/ui';
import { Text } from '@/components/ui';
import {
IconGithubLogo,
IconMail,
IconLock,
IconKey,
} from '@/components/ui/icons';
import OIDCIcon from '../common/logo/OIDCIcon';
import WeChatIcon from '../common/logo/WeChatIcon';
import LinuxDoIcon from '../common/logo/LinuxDoIcon';
import DiscordIcon from '../common/logo/DiscordIcon';
import TwoFAVerification from './TwoFAVerification';
import { useTranslation } from 'react-i18next';
import AuthBackground from '../common/AuthBackground';
import { Shield, Smartphone, QrCode } from 'lucide-react';
import GlassCard from './GlassCard';
import AuthCardHeader from './AuthCardHeader';
import AuthLoginTabs from './AuthLoginTabs';
import AgreementModal from '../common/DocumentRenderer/AgreementModal';
import {
isMiniProgramWebView,
withMiniProgramLogins,
} from '../../helpers/miniProgram';
// 懒加载 Telegram 登录组件(345KB),只在需要时加载
const TelegramLogin = lazy(() => import('./TelegramLogin'));
// 检测是否在微信内浏览器中(结果不变,缓存计算)
const IS_WECHAT_BROWSER = (() => {
const ua = navigator.userAgent.toLowerCase();
return ua.indexOf('micromessenger') !== -1;
})();
// 检测是否是移动设备(结果不变,缓存计算)
const IS_MOBILE_DEVICE =
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
);
// 提取OAuthButton到组件外部,避免每次渲染都重建
const OAuthButton = React.memo(
({ icon, children, onClick, loading, disabled, iconColor, t }) => (
),
);
const LoginForm = () => {
let navigate = useNavigate();
const { t } = useTranslation();
const [inputs, setInputs] = useState({
username: '',
password: '',
wechat_verification_code: '',
});
const { username, password } = inputs;
const [searchParams, setSearchParams] = useSearchParams();
const [, userDispatch] = useContext(UserContext);
const [turnstileEnabled, setTurnstileEnabled] = useState(false);
const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
const [turnstileToken, setTurnstileToken] = useState('');
const [showWeChatLoginModal, setShowWeChatLoginModal] = useState(false);
const [showEmailLogin, setShowEmailLogin] = useState(false);
const [githubLoading, setGithubLoading] = useState(false);
const [discordLoading, setDiscordLoading] = useState(false);
const [oidcLoading, setOidcLoading] = useState(false);
const [linuxdoLoading, setLinuxdoLoading] = useState(false);
const [wechatOpenLoading, setWechatOpenLoading] = useState(false);
const [loginLoading, setLoginLoading] = useState(false);
const [wechatCodeSubmitLoading, setWechatCodeSubmitLoading] = useState(false);
const [showTwoFA, setShowTwoFA] = useState(false);
const [passkeySupported, setPasskeySupported] = useState(false);
const [passkeyLoading, setPasskeyLoading] = useState(false);
const [agreedToTerms, setAgreedToTerms] = useState(false);
const [hasUserAgreement, setHasUserAgreement] = useState(false);
const [hasPrivacyPolicy, setHasPrivacyPolicy] = useState(false);
const [agreementModal, setAgreementModal] = useState({
visible: false,
type: null,
});
const openAgreement = useCallback((e, type) => {
// 支持中键/Ctrl+点击等保留新标签页打开
if (e && (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1)) {
return;
}
if (e) e.preventDefault();
setAgreementModal({ visible: true, type });
}, []);
const closeAgreement = useCallback(() => {
setAgreementModal((prev) => ({ ...prev, visible: false }));
}, []);
const [githubButtonText, setGithubButtonText] = useState('');
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
const githubTimeoutRef = useRef(null);
const logo = getLogo();
const systemName = getSystemName();
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext);
// WeyAi 小程序的 web-view 里只留站内能完成的登录方式(见 helpers/miniProgram.js)。
const status = useMemo(() => {
const raw = statusState?.status || {};
return isMiniProgramWebView() ? withMiniProgramLogins(raw) : raw;
}, [statusState?.status]);
const statusLoaded = statusState?.status !== undefined;
// affCode 只需在挂载时提取一次,避免每次渲染都执行
useEffect(() => {
const affCode = new URLSearchParams(window.location.search).get('aff');
if (affCode) {
localStorage.setItem('aff', affCode);
}
}, []);
useEffect(() => {
if (status.turnstile_check) {
setTurnstileEnabled(true);
setTurnstileSiteKey(status.turnstile_site_key);
}
// 从 status 获取用户协议和隐私政策的启用状态
setHasUserAgreement(status.user_agreement_enabled || false);
setHasPrivacyPolicy(status.privacy_policy_enabled || false);
}, [status]);
useEffect(() => {
isPasskeySupported()
.then(setPasskeySupported)
.catch(() => setPasskeySupported(false));
return () => {
if (githubTimeoutRef.current) {
clearTimeout(githubTimeoutRef.current);
}
};
}, []);
useEffect(() => {
const redirect = searchParams.get('redirect');
if (redirect) {
savePostLoginRedirect(redirect);
}
if (searchParams.get('expired')) {
showError(t('未登录或登录已过期,请重新登录'));
const nextParams = new URLSearchParams(searchParams);
nextParams.delete('expired');
setSearchParams(nextParams, { replace: true });
}
}, [searchParams, setSearchParams, t]);
const finishLogin = useCallback(
(data, successMessage) =>
runLoginFlow({
data,
userDispatch,
navigate,
t,
successMessage,
}),
[navigate, t, userDispatch],
);
const onWeChatLoginClicked = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setShowWeChatLoginModal(true);
};
const onSubmitWeChatVerificationCode = async () => {
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setWechatCodeSubmitLoading(true);
try {
const res = await API.get(
`/api/oauth/wechat?code=${inputs.wechat_verification_code}`,
);
const { success, message, data } = res.data;
if (success) {
// Close modal regardless of session-verify outcome — finishLogin
// already surfaces the cookie-blocked error on failure, and leaving
// the modal open would let the user re-submit a now-consumed code.
setShowWeChatLoginModal(false);
await finishLogin(data);
} else {
showError(message);
}
} catch (error) {
showError(t('登录失败,请重试'));
} finally {
setWechatCodeSubmitLoading(false);
}
};
function handleChange(name, value) {
setInputs((inputs) => ({ ...inputs, [name]: value }));
}
async function handleSubmit(e) {
// Semi Form 里的按钮同时具备原生 submit 行为;先阻止浏览器
// 刷新/跳转,确保登录请求和 finishLogin 流程完整执行。
e?.preventDefault?.();
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setLoginLoading(true);
try {
if (username && password) {
const res = await API.post(
`/api/user/login?turnstile=${turnstileToken}`,
{
username,
password,
},
);
const { success, message, data } = res.data;
if (success) {
// 检查是否需要2FA验证
if (data && data.require_2fa) {
setShowTwoFA(true);
setLoginLoading(false);
return;
}
const loggedIn = await finishLogin(data);
if (loggedIn && username === 'root' && password === '123456') {
Modal.error({
title: t('您正在使用默认密码!'),
content: t('请立刻修改默认密码!'),
centered: true,
});
}
} else {
showError(message);
}
} else {
showError(t('请输入用户名和密码!'));
}
} catch (error) {
showError(t('登录失败,请重试'));
} finally {
setLoginLoading(false);
}
}
// 添加Telegram登录处理函数
const onTelegramLoginClicked = async (response) => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
const fields = [
'id',
'first_name',
'last_name',
'username',
'photo_url',
'auth_date',
'hash',
'lang',
];
const params = {};
fields.forEach((field) => {
if (response[field]) {
params[field] = response[field];
}
});
try {
const res = await API.get(`/api/oauth/telegram/login`, { params });
const { success, message, data } = res.data;
if (success) {
await finishLogin(data);
} else {
showError(message);
}
} catch (error) {
showError(t('登录失败,请重试'));
}
};
// 协议检查通用方法
const checkAgreement = useCallback(() => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return false;
}
return true;
}, [hasUserAgreement, hasPrivacyPolicy, agreedToTerms, t]);
// 包装的GitHub登录点击处理
const handleGitHubClick = async () => {
if (!checkAgreement()) return;
if (githubButtonDisabled) return;
setGithubLoading(true);
setGithubButtonDisabled(true);
setGithubButtonText(t('正在跳转 GitHub...'));
// 清除旧的超时定时器
if (githubTimeoutRef.current) {
clearTimeout(githubTimeoutRef.current);
}
try {
const opened = await onGitHubOAuthClicked(status.github_client_id);
if (!opened) {
// getOAuthState 失败,错误已由 helper 显示,立即恢复按钮
setGithubLoading(false);
setGithubButtonText('');
setGithubButtonDisabled(false);
return;
}
// window.open 成功调用,但弹窗可能被浏览器拦截,设置超时自动恢复
githubTimeoutRef.current = setTimeout(() => {
setGithubLoading(false);
setGithubButtonText('');
setGithubButtonDisabled(false);
showInfo(t('如果新窗口未打开,请检查浏览器是否拦截了弹出窗口'));
}, 5000);
} catch (error) {
setGithubLoading(false);
setGithubButtonText('');
setGithubButtonDisabled(false);
showError(t('GitHub 登录失败,请重试'));
}
};
// 包装的Discord登录点击处理
const handleDiscordClick = async () => {
if (!checkAgreement()) return;
setDiscordLoading(true);
try {
const opened = await onDiscordOAuthClicked(status.discord_client_id);
if (!opened) {
setDiscordLoading(false);
return;
}
// window.open 弹窗可能被拦截,超时后恢复按钮
setTimeout(() => {
setDiscordLoading(false);
}, 5000);
} catch (error) {
setDiscordLoading(false);
showError(t('Discord 登录失败,请重试'));
}
};
// 包装的OIDC登录点击处理
const handleOIDCClick = async () => {
if (!checkAgreement()) return;
setOidcLoading(true);
try {
const redirected = await onOIDCClicked(
status.oidc_authorization_endpoint,
status.oidc_client_id,
);
if (!redirected) {
// getOAuthState 失败,重置 loading
setOidcLoading(false);
}
// 如果 redirected 为 true,页面会跳转,loading 状态无需重置
} catch (error) {
setOidcLoading(false);
showError(t('OIDC 登录失败,请重试'));
}
};
// 包装的LinuxDO登录点击处理
const handleLinuxDOClick = async () => {
if (!checkAgreement()) return;
setLinuxdoLoading(true);
try {
const opened = await onLinuxDOOAuthClicked(status.linuxdo_client_id);
if (!opened) {
setLinuxdoLoading(false);
return;
}
// window.open 弹窗可能被拦截,超时后恢复按钮
setTimeout(() => {
setLinuxdoLoading(false);
}, 5000);
} catch (error) {
setLinuxdoLoading(false);
showError(t('LinuxDO 登录失败,请重试'));
}
};
// 微信扫码登录提示弹窗状态
const [showWeChatOpenTipModal, setShowWeChatOpenTipModal] = useState(false);
// 包装的微信开放平台登录点击处理
const handleWeChatOpenClick = async () => {
if (!checkAgreement()) return;
// 在微信内置浏览器中,且公众号网页授权已开启时,使用公众号授权直接登录
if (IS_WECHAT_BROWSER && status.wechat_mp_auth && status.wechat_mp_app_id) {
setWechatOpenLoading(true);
try {
const redirected = await onWeChatMPOAuthClicked(
status.wechat_mp_app_id,
);
if (!redirected) {
setWechatOpenLoading(false);
}
} catch (error) {
setWechatOpenLoading(false);
showError(t('微信登录失败,请重试'));
}
return;
}
// 在移动端且不在微信内时,显示提示弹窗
if (IS_MOBILE_DEVICE && !IS_WECHAT_BROWSER) {
setShowWeChatOpenTipModal(true);
return;
}
// PC端:使用开放平台扫码登录
setWechatOpenLoading(true);
try {
const redirected = await onWeChatOpenOAuthClicked(
status.wechat_open_app_id,
);
if (!redirected) {
setWechatOpenLoading(false);
}
} catch (error) {
setWechatOpenLoading(false);
showError(t('微信登录失败,请重试'));
}
};
// 强制继续微信扫码登录(用于移动端用户确认后)
const handleForceWeChatOpenLogin = async () => {
setShowWeChatOpenTipModal(false);
setWechatOpenLoading(true);
try {
const redirected = await onWeChatOpenOAuthClicked(
status.wechat_open_app_id,
);
if (!redirected) {
setWechatOpenLoading(false);
}
} catch (error) {
setWechatOpenLoading(false);
showError(t('微信登录失败,请重试'));
}
};
// 包装的邮箱登录选项点击处理
const handleEmailLoginClick = () => {
setShowEmailLogin(true);
};
const handlePasskeyLogin = async () => {
if (!checkAgreement()) return;
if (!passkeySupported) {
showInfo(t('当前环境无法使用 Passkey 登录'));
return;
}
if (!window.PublicKeyCredential) {
showInfo(t('当前浏览器不支持 Passkey'));
return;
}
setPasskeyLoading(true);
try {
const beginRes = await API.post('/api/user/passkey/login/begin');
const { success, message, data } = beginRes.data;
if (!success) {
showError(message || t('无法发起 Passkey 登录'));
return;
}
const publicKeyOptions = prepareCredentialRequestOptions(
data?.options || data?.publicKey || data,
);
const assertion = await navigator.credentials.get({
publicKey: publicKeyOptions,
});
const payload = buildAssertionResult(assertion);
if (!payload) {
showError(t('Passkey 验证失败,请重试'));
return;
}
const finishRes = await API.post(
'/api/user/passkey/login/finish',
payload,
);
const finish = finishRes.data;
if (finish.success) {
await finishLogin(finish.data);
} else {
showError(finish.message || t('Passkey 登录失败,请重试'));
}
} catch (error) {
if (error?.name === 'AbortError') {
showInfo(t('已取消 Passkey 登录'));
} else {
showError(t('Passkey 登录失败,请重试'));
}
} finally {
setPasskeyLoading(false);
}
};
// 包装的重置密码点击处理
const handleResetPasswordClick = () => {
navigate('/reset');
};
// 包装的其他登录选项点击处理
const handleOtherLoginOptionsClick = () => {
setShowEmailLogin(false);
};
// 2FA验证成功处理
const handle2FASuccess = async (data) => {
await finishLogin(data);
};
// 返回登录页面
const handleBackToLogin = () => {
setShowTwoFA(false);
setInputs({ username: '', password: '', wechat_verification_code: '' });
};
const renderOAuthOptions = () => {
return (
{status.wechat_login && (
} />}
iconColor='#07C160'
onClick={onWeChatLoginClicked}
t={t}
>
{t('使用 微信 继续')}
)}
{status.wechat_open_oauth && (
} />}
iconColor='#07C160'
onClick={handleWeChatOpenClick}
loading={wechatOpenLoading}
t={t}
>
{IS_WECHAT_BROWSER && status.wechat_mp_auth
? t('微信一键登录')
: t('使用 微信扫码 登录')}
)}
{status.github_oauth && (
}
onClick={handleGitHubClick}
loading={githubLoading}
disabled={githubButtonDisabled}
t={t}
>
{githubButtonText || t('使用 GitHub 登录')}
)}
{status.discord_oauth && (
}
iconColor='#5865F2'
onClick={handleDiscordClick}
loading={discordLoading}
t={t}
>
{t('使用 Discord 继续')}
)}
{status.oidc_enabled && (
}
iconColor='#1877F2'
onClick={handleOIDCClick}
loading={oidcLoading}
t={t}
>
{t('使用 OIDC 继续')}
)}
{status.linuxdo_oauth && (
}
iconColor='#E95420'
onClick={handleLinuxDOClick}
loading={linuxdoLoading}
t={t}
>
{t('使用 LinuxDO 继续')}
)}
{status.telegram_oauth && (
{t('加载中...')}
}
>
)}
{status.passkey_login && passkeySupported && (
}
iconColor='#6366F1'
onClick={handlePasskeyLogin}
loading={passkeyLoading}
t={t}
>
{t('Passkey 登录')}
)}
{/* 分隔线 */}
{/* 邮箱登录按钮 */}
{(hasUserAgreement || hasPrivacyPolicy) && (
)}
{!status.self_use_mode_enabled && (
{t('没有账户?')}{' '}
{t('立即注册')}
)}
{/* 安全提示 */}
{t('安全登录')}
);
};
const renderEmailLoginForm = () => {
return (
{status.passkey_login && passkeySupported && (
}
iconColor='#6366F1'
onClick={handlePasskeyLogin}
loading={passkeyLoading}
t={t}
>
{t('Passkey 登录')}
)}
{status.passkey_login && passkeySupported && (
)}
{t('用户名/邮箱')}
}
placeholder={t('请输入用户名或邮箱')}
name='username'
size='default'
autoComplete='username'
onChange={(value) => handleChange('username', value)}
prefix={}
/>
{/* 密码输入框 */}
{t('密码')}
}
placeholder={t('请输入密码')}
name='password'
mode='password'
size='default'
autoComplete='current-password'
onChange={(value) => handleChange('password', value)}
prefix={}
/>
{(hasUserAgreement || hasPrivacyPolicy) && (
)}
{/* 登录按钮 */}
{(status.github_oauth ||
status.discord_oauth ||
status.oidc_enabled ||
status.wechat_login ||
status.wechat_open_oauth ||
status.linuxdo_oauth ||
status.telegram_oauth) && (
)}
{!status.self_use_mode_enabled && (
{t('没有账户?')}{' '}
{t('立即注册')}
)}
{/* 安全提示 */}
{t('安全登录')}
);
};
// 微信登录模态框
const renderWeChatLoginModal = () => {
const isMobileView = IS_MOBILE_DEVICE;
const isInWeChat = IS_WECHAT_BROWSER;
return (
} style={{ color: '#07C160' }} />
{t('微信扫码登录')}
}
visible={showWeChatLoginModal}
maskClosable={true}
onOk={onSubmitWeChatVerificationCode}
onCancel={() => setShowWeChatLoginModal(false)}
okText={t('登录')}
centered={true}
okButtonProps={{
loading: wechatCodeSubmitLoading,
}}
className='wechat-login-modal'
>
{/* 移动端提示 */}
{isMobileView && !isInWeChat && (
{t('移动端登录提示')}
{t(
'请长按保存下方二维码,在微信中扫一扫打开。或使用其他设备的微信扫描二维码。',
)}
)}

{/* 移动端可长按保存提示 */}
{isMobileView && (
{t('长按保存')}
)}
{isMobileView
? t('使用其他设备微信扫码关注公众号')
: t('微信扫码关注公众号')}
{t('输入「验证码」获取验证码(三分钟内有效)')}
handleChange('wechat_verification_code', value)
}
className='!rounded-xl'
/>
);
};
// 移动端微信扫码登录提示弹窗
const renderWeChatOpenTipModal = () => {
return (
{t('移动端登录提示')}
}
visible={showWeChatOpenTipModal}
maskClosable={true}
onCancel={() => setShowWeChatOpenTipModal(false)}
footer={null}
centered={true}
className='wechat-tip-modal'
>
{/* 提示信息 */}
{t('微信扫码登录功能在移动端体验不佳。建议您:')}
{status.wechat_mp_auth && (
-
✓
{t('在微信中打开此页面,即可一键登录')}
)}
-
1
{t('使用电脑浏览器打开本页面进行扫码登录')}
-
2
{t('或使用邮箱/用户名密码方式登录')}
{/* 操作按钮 */}
);
};
// 2FA验证弹窗
const render2FAModal = () => {
return (
{t('两步验证')}
{t('请输入验证码完成登录')}
}
visible={showTwoFA}
onCancel={handleBackToLogin}
footer={null}
width={450}
centered
>
);
};
const renderSkeleton = () => {
return (
);
};
return (
{statusLoaded && !status.self_use_mode_enabled && (
)}
{!statusLoaded
? renderSkeleton()
: showEmailLogin ||
!(
status.github_oauth ||
status.discord_oauth ||
status.oidc_enabled ||
status.wechat_login ||
status.wechat_open_oauth ||
status.linuxdo_oauth ||
status.telegram_oauth
)
? renderEmailLoginForm()
: renderOAuthOptions()}
{renderWeChatLoginModal()}
{renderWeChatOpenTipModal()}
{render2FAModal()}
{turnstileEnabled && (
{
setTurnstileToken(token);
}}
/>
)}
);
};
export default LoginForm;