Files
monkey-ai-web/src/components/auth/LoginForm.jsx
T
2026-11-18 19:09:00 +08:00

1248 lines
40 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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 <https://www.gnu.org/licenses/>.
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 AuthDivider from './AuthDivider';
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到组件外部,避免每次渲染都重建
// 第三方登录按钮:统一为 36px 描边按钮,无位移 / 扫光动效(尺寸见 prototype.css .auth-login-page)
const OAuthButton = React.memo(
({ icon, children, onClick, loading, disabled, iconColor }) => (
<Button
block
className='auth-oauth-button'
onClick={onClick}
loading={loading}
disabled={disabled}
icon={
<span
className='auth-oauth-icon'
style={iconColor ? { color: iconColor } : undefined}
>
{icon}
</span>
}
>
{children}
</Button>
),
);
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 wechatFormApi = useRef(null);
const submitWeChatCodeWithValidation = async () => {
try {
await wechatFormApi.current?.validate();
} catch {
return;
}
await onSubmitWeChatVerificationCode();
};
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 (
<GlassCard>
<AuthCardHeader
logo={logo}
title={systemName}
subtitle={t('请选择登录方式')}
/>
<div className='auth-option-list'>
{status.wechat_login && (
<OAuthButton
icon={<Icon svg={<WeChatIcon />} />}
iconColor='#07C160'
onClick={onWeChatLoginClicked}
t={t}
>
{t('使用 微信 继续')}
</OAuthButton>
)}
{status.wechat_open_oauth && (
<OAuthButton
icon={<Icon svg={<WeChatIcon />} />}
iconColor='#07C160'
onClick={handleWeChatOpenClick}
loading={wechatOpenLoading}
t={t}
>
{IS_WECHAT_BROWSER && status.wechat_mp_auth
? t('微信一键登录')
: t('使用 微信扫码 登录')}
</OAuthButton>
)}
{status.github_oauth && (
<OAuthButton
icon={<IconGithubLogo size='large' />}
onClick={handleGitHubClick}
loading={githubLoading}
disabled={githubButtonDisabled}
t={t}
>
{githubButtonText || t('使用 GitHub 登录')}
</OAuthButton>
)}
{status.discord_oauth && (
<OAuthButton
icon={<DiscordIcon />}
iconColor='#5865F2'
onClick={handleDiscordClick}
loading={discordLoading}
t={t}
>
{t('使用 Discord 继续')}
</OAuthButton>
)}
{status.oidc_enabled && (
<OAuthButton
icon={<OIDCIcon />}
iconColor='#1877F2'
onClick={handleOIDCClick}
loading={oidcLoading}
t={t}
>
{t('使用 OIDC 继续')}
</OAuthButton>
)}
{status.linuxdo_oauth && (
<OAuthButton
icon={<LinuxDoIcon style={{ width: '20px', height: '20px' }} />}
iconColor='#E95420'
onClick={handleLinuxDOClick}
loading={linuxdoLoading}
t={t}
>
{t('使用 LinuxDO 继续')}
</OAuthButton>
)}
{status.telegram_oauth && (
<Suspense
fallback={
<div className='flex justify-center my-2 h-10 items-center text-gray-400 text-xs'>
{t('加载中...')}
</div>
}
>
<TelegramLogin
onAuth={onTelegramLoginClicked}
botName={status.telegram_bot_name}
/>
</Suspense>
)}
{status.passkey_login && passkeySupported && (
<OAuthButton
icon={<IconKey />}
iconColor='#6366F1'
onClick={handlePasskeyLogin}
loading={passkeyLoading}
t={t}
>
{t('Passkey 登录')}
</OAuthButton>
)}
<AuthDivider>{t('或')}</AuthDivider>
{/* 邮箱登录按钮 */}
<Button
theme='solid'
block
className='auth-login-submit'
icon={<IconMail />}
onClick={handleEmailLoginClick}
>
{t('邮箱/用户名 登录')}
</Button>
</div>
{(hasUserAgreement || hasPrivacyPolicy) && (
<div className='auth-login-agreement flex justify-center'>
<Checkbox
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
>
<Text
size='small'
className='text-gray-500 dark:text-gray-400 text-xs'
>
{t('我已阅读并同意')}
{hasUserAgreement && (
<a
href='/user-agreement'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'agreement')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-1 font-medium transition-colors'
>
{t('服务协议')}
</a>
)}
{hasUserAgreement && hasPrivacyPolicy && t('和')}
{hasPrivacyPolicy && (
<a
href='/privacy-policy'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'privacy')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-1 font-medium transition-colors'
>
{t('隐私政策')}
</a>
)}
</Text>
</Checkbox>
</div>
)}
{!status.self_use_mode_enabled && (
<div className='auth-login-register text-center'>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('没有账户?')}{' '}
<Link
to='/register'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
>
{t('立即注册')}
</Link>
</Text>
</div>
)}
{/* 安全提示 */}
<div className='auth-login-security'>
<Shield size={12} />
<span>{t('安全登录')}</span>
</div>
</GlassCard>
);
};
const renderEmailLoginForm = () => {
return (
<GlassCard>
<AuthCardHeader
logo={logo}
title={systemName}
subtitle={t('欢迎回来')}
wrapperClassName='mb-3'
logoWrapperClassName='mb-2'
/>
{status.passkey_login && passkeySupported && (
<OAuthButton
icon={<IconKey />}
iconColor='#6366F1'
onClick={handlePasskeyLogin}
loading={passkeyLoading}
t={t}
>
{t('Passkey 登录')}
</OAuthButton>
)}
{status.passkey_login && passkeySupported && (
<AuthDivider>{t('或')}</AuthDivider>
)}
<Form className='auth-login-form' onSubmit={handleSubmit}>
<Form.Input
field='username'
className='auth-login-required-field'
rules={[{ required: true, message: t('请输入用户名/邮箱') }]}
required
aria-required='true'
label={t('用户名/邮箱')}
placeholder={t('请输入用户名或邮箱')}
name='username'
size='default'
autoComplete='username'
onChange={(value) => handleChange('username', value)}
prefix={<IconMail size='small' />}
/>
{/* 密码输入框 */}
<Form.Input
field='password'
className='auth-login-required-field'
rules={[{ required: true, message: t('请输入密码') }]}
required
aria-required='true'
label={t('密码')}
placeholder={t('请输入密码')}
name='password'
mode='password'
size='default'
autoComplete='current-password'
onChange={(value) => handleChange('password', value)}
prefix={<IconLock size='small' />}
/>
{(hasUserAgreement || hasPrivacyPolicy) && (
<div className='auth-login-agree-row flex items-center'>
<Checkbox
checked={agreedToTerms}
onChange={(e) => setAgreedToTerms(e.target.checked)}
>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('我已阅读并同意')}
{hasUserAgreement && (
<a
href='/user-agreement'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'agreement')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-0.5 font-medium transition-colors'
>
{t('服务协议')}
</a>
)}
{hasUserAgreement && hasPrivacyPolicy && t('和')}
{hasPrivacyPolicy && (
<a
href='/privacy-policy'
target='_blank'
rel='noopener noreferrer'
onClick={(e) => openAgreement(e, 'privacy')}
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from mx-0.5 font-medium transition-colors'
>
{t('隐私政策')}
</a>
)}
</Text>
</Checkbox>
</div>
)}
<div className='auth-login-actions'>
{/* 登录按钮 */}
<Button
theme='solid'
htmlType='submit'
loading={loginLoading}
block
disabled={
loginLoading ||
((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms)
}
className='auth-login-submit'
>
<span className='font-semibold'>{t('登 录')}</span>
<ActionArrowRight size={16} />
</Button>
<Button
theme='borderless'
type='tertiary'
size='small'
className='auth-login-forgot'
onClick={handleResetPasswordClick}
>
{t('忘记密码?')}
</Button>
</div>
</Form>
{(status.github_oauth ||
status.discord_oauth ||
status.oidc_enabled ||
status.wechat_login ||
status.wechat_open_oauth ||
status.linuxdo_oauth ||
status.telegram_oauth) && (
<div>
<AuthDivider>{t('或')}</AuthDivider>
<Button
block
className='auth-oauth-button'
onClick={handleOtherLoginOptionsClick}
>
{t('其他登录选项')}
</Button>
</div>
)}
{!status.self_use_mode_enabled && (
<div className='auth-login-register text-center'>
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
{t('没有账户?')}{' '}
<Link
to='/register'
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
>
{t('立即注册')}
</Link>
</Text>
</div>
)}
{/* 安全提示 */}
<div className='auth-login-security'>
<Shield size={12} />
<span>{t('安全登录')}</span>
</div>
</GlassCard>
);
};
// 微信登录模态框
const renderWeChatLoginModal = () => {
const isMobileView = IS_MOBILE_DEVICE;
const isInWeChat = IS_WECHAT_BROWSER;
return (
<Modal
title={
<div className='flex items-center gap-2'>
<div className='w-8 h-8 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center'>
<Icon svg={<WeChatIcon />} style={{ color: '#07C160' }} />
</div>
<span>{t('微信扫码登录')}</span>
</div>
}
visible={showWeChatLoginModal}
maskClosable={true}
onOk={submitWeChatCodeWithValidation}
onCancel={() => setShowWeChatLoginModal(false)}
okText={t('登录')}
centered={true}
okButtonProps={{
loading: wechatCodeSubmitLoading,
}}
className='wechat-login-modal auth-login-modal'
>
{/* 移动端提示 */}
{isMobileView && !isInWeChat && (
<div className='mb-4 p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl'>
<div className='flex items-start gap-2'>
<Smartphone
size={18}
className='text-amber-600 dark:text-amber-400 mt-0.5 shrink-0'
/>
<div>
<p className='text-sm text-amber-800 dark:text-amber-200 font-medium'>
{t('移动端登录提示')}
</p>
<p className='text-xs text-amber-600 dark:text-amber-400 mt-1'>
{t(
'请长按保存下方二维码,在微信中扫一扫打开。或使用其他设备的微信扫描二维码。',
)}
</p>
</div>
</div>
</div>
)}
<div className='flex flex-col items-center'>
<div className='relative p-2 bg-white rounded-xl shadow-lg'>
<img
src={status.wechat_qrcode}
alt={t('微信二维码')}
className='rounded-lg'
/>
{/* 移动端可长按保存提示 */}
{isMobileView && (
<div className='absolute -bottom-2 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-gray-900/80 text-white text-[10px] rounded-full whitespace-nowrap'>
{t('长按保存')}
</div>
)}
</div>
</div>
<div className='text-center my-4 px-4'>
<div className='flex items-center justify-center gap-2 mb-2'>
<QrCode size={16} className='text-gray-400' />
<p className='text-gray-600 dark:text-gray-300 text-sm'>
{isMobileView
? t('使用其他设备微信扫码关注公众号')
: t('微信扫码关注公众号')}
</p>
</div>
<p className='text-gray-500 dark:text-gray-400 text-xs'>
{t('输入「验证码」获取验证码(三分钟内有效)')}
</p>
</div>
<Form getFormApi={(api) => (wechatFormApi.current = api)}>
<Form.Input
field='wechat_verification_code'
placeholder={t('请输入验证码')}
label={t('验证码')}
rules={[{ required: true, message: t('请输入验证码') }]}
value={inputs.wechat_verification_code}
onChange={(value) =>
handleChange('wechat_verification_code', value)
}
/>
</Form>
</Modal>
);
};
// 移动端微信扫码登录提示弹窗
const renderWeChatOpenTipModal = () => {
return (
<Modal
title={
<div className='flex items-center gap-2'>
<div className='w-8 h-8 bg-amber-100 dark:bg-amber-900/30 rounded-lg flex items-center justify-center'>
<Smartphone size={18} className='text-amber-600' />
</div>
<span>{t('移动端登录提示')}</span>
</div>
}
visible={showWeChatOpenTipModal}
maskClosable={true}
onCancel={() => setShowWeChatOpenTipModal(false)}
footer={null}
centered={true}
className='wechat-tip-modal'
>
<div className='space-y-4'>
{/* 提示信息 */}
<div className='p-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl'>
<p className='text-sm text-amber-800 dark:text-amber-200'>
{t('微信扫码登录功能在移动端体验不佳。建议您:')}
</p>
<ul className='mt-2 space-y-1.5 text-xs text-amber-700 dark:text-amber-300'>
{status.wechat_mp_auth && (
<li className='flex items-start gap-2'>
<span className='w-4 h-4 bg-green-200 dark:bg-green-800 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5'>
✓
</span>
<span>{t('在微信中打开此页面,即可一键登录')}</span>
</li>
)}
<li className='flex items-start gap-2'>
<span className='w-4 h-4 bg-amber-200 dark:bg-amber-800 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5'>
1
</span>
<span>{t('使用电脑浏览器打开本页面进行扫码登录')}</span>
</li>
<li className='flex items-start gap-2'>
<span className='w-4 h-4 bg-amber-200 dark:bg-amber-800 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5'>
2
</span>
<span>{t('或使用邮箱/用户名密码方式登录')}</span>
</li>
</ul>
</div>
{/* 操作按钮 */}
<div className='flex gap-3'>
<Button
block
onClick={() => {
setShowWeChatOpenTipModal(false);
setShowEmailLogin(true);
}}
className='!rounded-xl !h-10'
>
{t('使用邮箱登录')}
</Button>
<Button
block
theme='solid'
type='warning'
onClick={handleForceWeChatOpenLogin}
className='!rounded-xl !h-10'
>
{t('仍然继续')}
</Button>
</div>
</div>
</Modal>
);
};
// 2FA验证弹窗
const render2FAModal = () => {
return (
<Modal
title={
<div className='flex items-center gap-3'>
<div className='auth-modal-title-icon'>
<Shield size={18} />
</div>
<div>
<div className='font-semibold'>{t('两步验证')}</div>
<div className='text-xs text-gray-500 dark:text-gray-400 font-normal'>
{t('请输入验证码完成登录')}
</div>
</div>
</div>
}
visible={showTwoFA}
onCancel={handleBackToLogin}
footer={null}
width={450}
centered
className='auth-login-modal'
>
<TwoFAVerification
onSuccess={handle2FASuccess}
onBack={handleBackToLogin}
isModal={true}
/>
</Modal>
);
};
const renderSkeleton = () => {
return (
<GlassCard withCornerHalos={false} withAurora={false}>
<div className='flex flex-col items-center justify-center mb-5'>
<div className='w-14 h-14 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse mb-3' />
<div className='w-24 h-5 rounded bg-gray-200/60 dark:bg-white/10 animate-pulse mb-1' />
<div className='w-32 h-3 rounded bg-gray-100/80 dark:bg-white/5 animate-pulse' />
</div>
<div className='space-y-2'>
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
</div>
</GlassCard>
);
};
return (
<div
className='auth-login-page relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
// 抵扣 PageLayout 跑马灯占位高度,保证占位+容器恰为一屏,避免幽灵滚动
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
>
<AuthBackground />
<div className='w-full max-w-md z-10 flex flex-col items-center'>
{statusLoaded && !status.self_use_mode_enabled && (
<div className='w-full max-w-sm mb-4'>
<AuthLoginTabs active='personal' />
</div>
)}
{!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 && (
<div className='flex justify-center mt-6'>
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => {
setTurnstileToken(token);
}}
/>
</div>
)}
</div>
<AgreementModal
visible={agreementModal.visible}
type={agreementModal.type}
onClose={closeAgreement}
/>
</div>
);
};
export default LoginForm;