/*
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 } from 'react-router-dom';
import {
API,
getLogo,
showError,
showInfo,
showSuccess,
getSystemName,
finishLogin as runLoginFlow,
onDiscordOAuthClicked,
onGitHubOAuthClicked,
onLinuxDOOAuthClicked,
onOIDCClicked,
onWeChatOpenOAuthClicked,
} from '../../helpers';
import Turnstile from 'react-turnstile';
import { Button, Checkbox, Form, Icon, Modal } from '@/components/ui';
import { Text } from '@/components/ui';
import {
IconGithubLogo,
IconMail,
IconUser,
IconLock,
IconKey,
} from '@/components/ui/icons';
import OIDCIcon from '../common/logo/OIDCIcon';
import LinuxDoIcon from '../common/logo/LinuxDoIcon';
import WeChatIcon from '../common/logo/WeChatIcon';
import DiscordIcon from '../common/logo/DiscordIcon';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import { useTranslation } from 'react-i18next';
import AuthBackground from '../common/AuthBackground';
import GlassCard from './GlassCard';
import AuthCardHeader from './AuthCardHeader';
import AuthLoginTabs from './AuthLoginTabs';
import { Shield, Smartphone, QrCode } from 'lucide-react';
import AgreementModal from '../common/DocumentRenderer/AgreementModal';
import {
isMiniProgramWebView,
withMiniProgramLogins,
} from '../../helpers/miniProgram';
// 懒加载 Telegram 登录组件(345KB),只在需要时加载
const TelegramLogin = lazy(() => import('./TelegramLogin'));
// 检测是否在微信内浏览器中
const isWeChatBrowser = () => {
const ua = navigator.userAgent.toLowerCase();
return ua.indexOf('micromessenger') !== -1;
};
// 检测是否是移动设备
const isMobileDevice = () => {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
);
};
const RegisterForm = () => {
let navigate = useNavigate();
const { t } = useTranslation();
const [inputs, setInputs] = useState({
username: '',
password: '',
password2: '',
email: '',
verification_code: '',
wechat_verification_code: '',
});
const { username, password, password2 } = inputs;
const [, userDispatch] = useContext(UserContext);
const [turnstileEnabled, setTurnstileEnabled] = useState(false);
const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
const [turnstileToken, setTurnstileToken] = useState('');
const [showWeChatLoginModal, setShowWeChatLoginModal] = useState(false);
const [showEmailRegister, setShowEmailRegister] = useState(false);
const [wechatLoading, setWechatLoading] = useState(false);
const [wechatOpenLoading, setWechatOpenLoading] = useState(false);
const [githubLoading, setGithubLoading] = useState(false);
const [discordLoading, setDiscordLoading] = useState(false);
const [oidcLoading, setOidcLoading] = useState(false);
const [linuxdoLoading, setLinuxdoLoading] = useState(false);
const [emailRegisterLoading, setEmailRegisterLoading] = useState(false);
const [registerLoading, setRegisterLoading] = useState(false);
const [verificationCodeLoading, setVerificationCodeLoading] = useState(false);
const [otherRegisterOptionsLoading, setOtherRegisterOptionsLoading] =
useState(false);
const [wechatCodeSubmitLoading, setWechatCodeSubmitLoading] = useState(false);
const [disableButton, setDisableButton] = useState(false);
const [countdown, setCountdown] = useState(30);
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) => {
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('使用 GitHub 继续');
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
const [showWeChatOpenTipModal, setShowWeChatOpenTipModal] = useState(false);
const githubTimeoutRef = useRef(null);
const logo = getLogo();
const systemName = getSystemName();
let affCode = new URLSearchParams(window.location.search).get('aff');
if (affCode) {
localStorage.setItem('aff', affCode);
}
// 使用 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;
const [showEmailVerification, setShowEmailVerification] = useState(() => {
return status.email_verification ?? false;
});
useEffect(() => {
setShowEmailVerification(status.email_verification);
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(() => {
let countdownInterval = null;
if (disableButton && countdown > 0) {
countdownInterval = setInterval(() => {
setCountdown(countdown - 1);
}, 1000);
} else if (countdown === 0) {
setDisableButton(false);
setCountdown(30);
}
return () => clearInterval(countdownInterval); // Clean up on unmount
}, [disableButton, countdown]);
useEffect(() => {
return () => {
if (githubTimeoutRef.current) {
clearTimeout(githubTimeoutRef.current);
}
};
}, []);
const finishLogin = (data) =>
runLoginFlow({ data, userDispatch, navigate, t });
const onWeChatLoginClicked = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setWechatLoading(true);
setShowWeChatLoginModal(true);
setWechatLoading(false);
};
// 微信开放平台扫码登录
const handleWeChatOpenClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
// 在移动端且不在微信内时,显示提示弹窗
if (isMobileDevice() && !isWeChatBrowser()) {
setShowWeChatOpenTipModal(true);
return;
}
setWechatOpenLoading(true);
try {
onWeChatOpenOAuthClicked(status.wechat_open_app_id);
} finally {
setTimeout(() => setWechatOpenLoading(false), 3000);
}
};
// 强制继续微信扫码登录(用于移动端用户确认后)
const handleForceWeChatOpenLogin = () => {
setShowWeChatOpenTipModal(false);
setWechatOpenLoading(true);
try {
onWeChatOpenOAuthClicked(status.wechat_open_app_id);
} finally {
setTimeout(() => setWechatOpenLoading(false), 3000);
}
};
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 before finishLogin so the user isn't tempted to re-submit a
// consumed wechat code if session verification fails.
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) {
if (e) {
e.preventDefault();
}
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
if (password.length < 8) {
showInfo(t('密码长度不得小于 8 位!'));
return;
}
if (password !== password2) {
showInfo(t('两次输入的密码不一致'));
return;
}
if (username && password) {
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setRegisterLoading(true);
try {
// 获取邀请码,优先使用 URL 参数,其次使用 localStorage
const finalAffCode = affCode || localStorage.getItem('aff');
// 创建请求数据,不直接修改 state
const requestData = {
...inputs,
aff_code: finalAffCode,
};
const res = await API.post(
`/api/user/register?turnstile=${turnstileToken}`,
requestData,
);
const { success, message } = res.data;
if (success) {
localStorage.setItem('new_user_gift_pending', inputs.username);
navigate('/login');
showSuccess(t('注册成功!'));
} else {
showError(message);
}
} catch (error) {
showError(t('注册失败,请重试'));
} finally {
setRegisterLoading(false);
}
}
}
const sendVerificationCode = async () => {
if (inputs.email === '') return;
if (turnstileEnabled && turnstileToken === '') {
showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setVerificationCodeLoading(true);
try {
const res = await API.get(
`/api/verification?email=${encodeURIComponent(inputs.email)}&turnstile=${turnstileToken}`,
);
const { success, message } = res.data;
if (success) {
showSuccess(t('验证码发送成功,请检查你的邮箱!'));
setDisableButton(true); // 发送成功后禁用按钮,开始倒计时
} else {
showError(message);
}
} catch (error) {
showError(t('发送验证码失败,请重试'));
} finally {
setVerificationCodeLoading(false);
}
};
const handleGitHubClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
if (githubButtonDisabled) {
return;
}
setGithubLoading(true);
setGithubButtonDisabled(true);
setGithubButtonText(t('正在跳转 GitHub...'));
if (githubTimeoutRef.current) {
clearTimeout(githubTimeoutRef.current);
}
githubTimeoutRef.current = setTimeout(() => {
setGithubLoading(false);
setGithubButtonText(t('请求超时,请刷新页面后重新发起 GitHub 登录'));
setGithubButtonDisabled(true);
}, 20000);
try {
onGitHubOAuthClicked(status.github_client_id);
} finally {
setTimeout(() => setGithubLoading(false), 3000);
}
};
const handleDiscordClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setDiscordLoading(true);
try {
onDiscordOAuthClicked(status.discord_client_id);
} finally {
setTimeout(() => setDiscordLoading(false), 3000);
}
};
const handleOIDCClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setOidcLoading(true);
try {
onOIDCClicked(status.oidc_authorization_endpoint, status.oidc_client_id);
} finally {
setTimeout(() => setOidcLoading(false), 3000);
}
};
const handleLinuxDOClick = () => {
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
showInfo(t('请先阅读并同意用户协议和隐私政策'));
return;
}
setLinuxdoLoading(true);
try {
onLinuxDOOAuthClicked(status.linuxdo_client_id);
} finally {
setTimeout(() => setLinuxdoLoading(false), 3000);
}
};
const handleEmailRegisterClick = () => {
setEmailRegisterLoading(true);
setShowEmailRegister(true);
setEmailRegisterLoading(false);
};
const handleOtherRegisterOptionsClick = () => {
setOtherRegisterOptionsLoading(true);
setShowEmailRegister(false);
setOtherRegisterOptionsLoading(false);
};
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 OAuthButton = ({
icon,
children,
onClick,
loading,
disabled,
iconColor,
}) => (
);
const renderOAuthOptions = () => {
return (
{status.wechat_login && (
} />}
iconColor='#07C160'
onClick={onWeChatLoginClicked}
loading={wechatLoading}
>
{t('使用 微信 继续')}
)}
{status.wechat_open_oauth && (
} />}
iconColor='#07C160'
onClick={handleWeChatOpenClick}
loading={wechatOpenLoading}
>
{t('使用 微信扫码 注册')}
)}
{status.github_oauth && (
}
onClick={handleGitHubClick}
loading={githubLoading}
disabled={githubButtonDisabled}
>
{t(githubButtonText)}
)}
{status.discord_oauth && (
}
iconColor='#5865F2'
onClick={handleDiscordClick}
loading={discordLoading}
>
{t('使用 Discord 继续')}
)}
{status.oidc_enabled && (
}
iconColor='#1877F2'
onClick={handleOIDCClick}
loading={oidcLoading}
>
{t('使用 OIDC 继续')}
)}
{status.linuxdo_oauth && (
}
iconColor='#E95420'
onClick={handleLinuxDOClick}
loading={linuxdoLoading}
>
{t('使用 LinuxDO 继续')}
)}
{status.telegram_oauth && (
{t('加载中...')}
}
>
)}
{/* 分隔线 */}
{/* 用户名注册按钮 */}
{(hasUserAgreement || hasPrivacyPolicy) && (
)}
{t('已有账户?')}{' '}
{t('登录')}
{/* 安全提示 */}
{t('安全注册')}
);
};
const renderEmailRegisterForm = () => {
return (
{t('用户名')}
}
placeholder={t('请输入用户名')}
name='username'
size='large'
autoComplete='username'
onChange={(value) => handleChange('username', value)}
prefix={}
/>
{/* 密码输入框 */}
{t('密码')}
}
placeholder={t('输入密码,最短 8 位,最长 20 位')}
name='password'
mode='password'
size='large'
autoComplete='new-password'
onChange={(value) => handleChange('password', value)}
prefix={}
/>
{/* 确认密码输入框 */}
{t('确认密码')}
}
placeholder={t('确认密码')}
name='password2'
mode='password'
size='large'
autoComplete='new-password'
onChange={(value) => handleChange('password2', value)}
prefix={}
/>
{showEmailVerification && (
<>
{t('邮箱')}
}
placeholder={t('输入邮箱地址')}
name='email'
type='email'
size='large'
autoComplete='email'
onChange={(value) => handleChange('email', value)}
prefix={}
suffix={
}
/>
{t('验证码')}
}
placeholder={t('输入验证码')}
name='verification_code'
size='large'
onChange={(value) => handleChange('verification_code', 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) && (
)}
{t('已有账户?')}{' '}
{t('登录')}
{/* 安全提示 */}
{t('安全注册')}
);
};
// 微信登录模态框
const renderWeChatLoginModal = () => {
const isMobileView = isMobileDevice();
const isInWeChat = isWeChatBrowser();
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('微信扫码登录功能在移动端体验不佳。建议您:')}
-
1
{t('使用电脑浏览器打开本页面进行扫码登录')}
-
2
{t('或使用用户名密码方式注册')}
{/* 操作按钮 */}
);
};
const renderSkeleton = () => {
return (
);
};
return (
{/* 企业开放自助注册时,注册页与登录页保持同样的「个人/企业」切换(自用模式下无注册入口,不展示) */}
{statusLoaded &&
!status.self_use_mode_enabled &&
status.org_self_register && (
)}
{!statusLoaded
? renderSkeleton()
: showEmailRegister ||
!(
status.github_oauth ||
status.discord_oauth ||
status.oidc_enabled ||
status.wechat_login ||
status.wechat_open_oauth ||
status.linuxdo_oauth ||
status.telegram_oauth
)
? renderEmailRegisterForm()
: renderOAuthOptions()}
{renderWeChatLoginModal()}
{renderWeChatOpenTipModal()}
{turnstileEnabled && (
{
setTurnstileToken(token);
}}
/>
)}
);
};
export default RegisterForm;