RegisterForm.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import React, { useContext, useEffect, useState } from 'react';
  16. import { Link, useNavigate } from 'react-router-dom';
  17. import {
  18. API,
  19. getLogo,
  20. showError,
  21. showInfo,
  22. showSuccess,
  23. updateAPI,
  24. getSystemName,
  25. setUserData
  26. } from '../../helpers/index.js';
  27. import Turnstile from 'react-turnstile';
  28. import {
  29. Button,
  30. Card,
  31. Divider,
  32. Form,
  33. Icon,
  34. Modal,
  35. } from '@douyinfe/semi-ui';
  36. import Title from '@douyinfe/semi-ui/lib/es/typography/title';
  37. import Text from '@douyinfe/semi-ui/lib/es/typography/text';
  38. import { IconGithubLogo, IconMail, IconUser, IconLock, IconKey } from '@douyinfe/semi-icons';
  39. import {
  40. onGitHubOAuthClicked,
  41. onLinuxDOOAuthClicked,
  42. onOIDCClicked,
  43. } from '../../helpers/index.js';
  44. import OIDCIcon from '../common/logo/OIDCIcon.js';
  45. import LinuxDoIcon from '../common/logo/LinuxDoIcon.js';
  46. import WeChatIcon from '../common/logo/WeChatIcon.js';
  47. import TelegramLoginButton from 'react-telegram-login/src';
  48. import { UserContext } from '../../context/User/index.js';
  49. import { useTranslation } from 'react-i18next';
  50. const RegisterForm = () => {
  51. let navigate = useNavigate();
  52. const { t } = useTranslation();
  53. const [inputs, setInputs] = useState({
  54. username: '',
  55. password: '',
  56. password2: '',
  57. email: '',
  58. verification_code: '',
  59. wechat_verification_code: '',
  60. });
  61. const { username, password, password2 } = inputs;
  62. const [userState, userDispatch] = useContext(UserContext);
  63. const [turnstileEnabled, setTurnstileEnabled] = useState(false);
  64. const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
  65. const [turnstileToken, setTurnstileToken] = useState('');
  66. const [showWeChatLoginModal, setShowWeChatLoginModal] = useState(false);
  67. const [showEmailRegister, setShowEmailRegister] = useState(false);
  68. const [wechatLoading, setWechatLoading] = useState(false);
  69. const [githubLoading, setGithubLoading] = useState(false);
  70. const [oidcLoading, setOidcLoading] = useState(false);
  71. const [linuxdoLoading, setLinuxdoLoading] = useState(false);
  72. const [emailRegisterLoading, setEmailRegisterLoading] = useState(false);
  73. const [registerLoading, setRegisterLoading] = useState(false);
  74. const [verificationCodeLoading, setVerificationCodeLoading] = useState(false);
  75. const [otherRegisterOptionsLoading, setOtherRegisterOptionsLoading] = useState(false);
  76. const [wechatCodeSubmitLoading, setWechatCodeSubmitLoading] = useState(false);
  77. const [disableButton, setDisableButton] = useState(false);
  78. const [countdown, setCountdown] = useState(30);
  79. const logo = getLogo();
  80. const systemName = getSystemName();
  81. let affCode = new URLSearchParams(window.location.search).get('aff');
  82. if (affCode) {
  83. localStorage.setItem('aff', affCode);
  84. }
  85. const [status] = useState(() => {
  86. const savedStatus = localStorage.getItem('status');
  87. return savedStatus ? JSON.parse(savedStatus) : {};
  88. });
  89. const [showEmailVerification, setShowEmailVerification] = useState(() => {
  90. return status.email_verification ?? false;
  91. });
  92. useEffect(() => {
  93. setShowEmailVerification(status.email_verification);
  94. if (status.turnstile_check) {
  95. setTurnstileEnabled(true);
  96. setTurnstileSiteKey(status.turnstile_site_key);
  97. }
  98. }, [status]);
  99. useEffect(() => {
  100. let countdownInterval = null;
  101. if (disableButton && countdown > 0) {
  102. countdownInterval = setInterval(() => {
  103. setCountdown(countdown - 1);
  104. }, 1000);
  105. } else if (countdown === 0) {
  106. setDisableButton(false);
  107. setCountdown(30);
  108. }
  109. return () => clearInterval(countdownInterval); // Clean up on unmount
  110. }, [disableButton, countdown]);
  111. const onWeChatLoginClicked = () => {
  112. setWechatLoading(true);
  113. setShowWeChatLoginModal(true);
  114. setWechatLoading(false);
  115. };
  116. const onSubmitWeChatVerificationCode = async () => {
  117. if (turnstileEnabled && turnstileToken === '') {
  118. showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
  119. return;
  120. }
  121. setWechatCodeSubmitLoading(true);
  122. try {
  123. const res = await API.get(
  124. `/api/oauth/wechat?code=${inputs.wechat_verification_code}`,
  125. );
  126. const { success, message, data } = res.data;
  127. if (success) {
  128. userDispatch({ type: 'login', payload: data });
  129. localStorage.setItem('user', JSON.stringify(data));
  130. setUserData(data);
  131. updateAPI();
  132. navigate('/');
  133. showSuccess('登录成功!');
  134. setShowWeChatLoginModal(false);
  135. } else {
  136. showError(message);
  137. }
  138. } catch (error) {
  139. showError('登录失败,请重试');
  140. } finally {
  141. setWechatCodeSubmitLoading(false);
  142. }
  143. };
  144. function handleChange(name, value) {
  145. setInputs((inputs) => ({ ...inputs, [name]: value }));
  146. }
  147. async function handleSubmit(e) {
  148. if (password.length < 8) {
  149. showInfo('密码长度不得小于 8 位!');
  150. return;
  151. }
  152. if (password !== password2) {
  153. showInfo('两次输入的密码不一致');
  154. return;
  155. }
  156. if (username && password) {
  157. if (turnstileEnabled && turnstileToken === '') {
  158. showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
  159. return;
  160. }
  161. setRegisterLoading(true);
  162. try {
  163. if (!affCode) {
  164. affCode = localStorage.getItem('aff');
  165. }
  166. inputs.aff_code = affCode;
  167. const res = await API.post(
  168. `/api/user/register?turnstile=${turnstileToken}`,
  169. inputs,
  170. );
  171. const { success, message } = res.data;
  172. if (success) {
  173. navigate('/login');
  174. showSuccess('注册成功!');
  175. } else {
  176. showError(message);
  177. }
  178. } catch (error) {
  179. showError('注册失败,请重试');
  180. } finally {
  181. setRegisterLoading(false);
  182. }
  183. }
  184. }
  185. const sendVerificationCode = async () => {
  186. if (inputs.email === '') return;
  187. if (turnstileEnabled && turnstileToken === '') {
  188. showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
  189. return;
  190. }
  191. setVerificationCodeLoading(true);
  192. try {
  193. const res = await API.get(
  194. `/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`,
  195. );
  196. const { success, message } = res.data;
  197. if (success) {
  198. showSuccess('验证码发送成功,请检查你的邮箱!');
  199. setDisableButton(true); // 发送成功后禁用按钮,开始倒计时
  200. } else {
  201. showError(message);
  202. }
  203. } catch (error) {
  204. showError('发送验证码失败,请重试');
  205. } finally {
  206. setVerificationCodeLoading(false);
  207. }
  208. };
  209. const handleGitHubClick = () => {
  210. setGithubLoading(true);
  211. try {
  212. onGitHubOAuthClicked(status.github_client_id);
  213. } finally {
  214. setTimeout(() => setGithubLoading(false), 3000);
  215. }
  216. };
  217. const handleOIDCClick = () => {
  218. setOidcLoading(true);
  219. try {
  220. onOIDCClicked(
  221. status.oidc_authorization_endpoint,
  222. status.oidc_client_id
  223. );
  224. } finally {
  225. setTimeout(() => setOidcLoading(false), 3000);
  226. }
  227. };
  228. const handleLinuxDOClick = () => {
  229. setLinuxdoLoading(true);
  230. try {
  231. onLinuxDOOAuthClicked(status.linuxdo_client_id);
  232. } finally {
  233. setTimeout(() => setLinuxdoLoading(false), 3000);
  234. }
  235. };
  236. const handleEmailRegisterClick = () => {
  237. setEmailRegisterLoading(true);
  238. setShowEmailRegister(true);
  239. setEmailRegisterLoading(false);
  240. };
  241. const handleOtherRegisterOptionsClick = () => {
  242. setOtherRegisterOptionsLoading(true);
  243. setShowEmailRegister(false);
  244. setOtherRegisterOptionsLoading(false);
  245. };
  246. const onTelegramLoginClicked = async (response) => {
  247. const fields = [
  248. 'id',
  249. 'first_name',
  250. 'last_name',
  251. 'username',
  252. 'photo_url',
  253. 'auth_date',
  254. 'hash',
  255. 'lang',
  256. ];
  257. const params = {};
  258. fields.forEach((field) => {
  259. if (response[field]) {
  260. params[field] = response[field];
  261. }
  262. });
  263. try {
  264. const res = await API.get(`/api/oauth/telegram/login`, { params });
  265. const { success, message, data } = res.data;
  266. if (success) {
  267. userDispatch({ type: 'login', payload: data });
  268. localStorage.setItem('user', JSON.stringify(data));
  269. showSuccess('登录成功!');
  270. setUserData(data);
  271. updateAPI();
  272. navigate('/');
  273. } else {
  274. showError(message);
  275. }
  276. } catch (error) {
  277. showError('登录失败,请重试');
  278. }
  279. };
  280. const renderOAuthOptions = () => {
  281. return (
  282. <div className="flex flex-col items-center">
  283. <div className="w-full max-w-md">
  284. <div className="flex items-center justify-center mb-6 gap-2">
  285. <img src={logo} alt="Logo" className="h-10 rounded-full" />
  286. <Title heading={3} className='!text-gray-800'>{systemName}</Title>
  287. </div>
  288. <Card className="border-0 !rounded-2xl overflow-hidden">
  289. <div className="flex justify-center pt-6 pb-2">
  290. <Title heading={3} className="text-gray-800 dark:text-gray-200">{t('注 册')}</Title>
  291. </div>
  292. <div className="px-2 py-8">
  293. <div className="space-y-3">
  294. {status.wechat_login && (
  295. <Button
  296. theme='outline'
  297. className="w-full h-12 flex items-center justify-center !rounded-full border border-gray-200 hover:bg-gray-50 transition-colors"
  298. type="tertiary"
  299. icon={<Icon svg={<WeChatIcon />} style={{ color: '#07C160' }} />}
  300. size="large"
  301. onClick={onWeChatLoginClicked}
  302. loading={wechatLoading}
  303. >
  304. <span className="ml-3">{t('使用 微信 继续')}</span>
  305. </Button>
  306. )}
  307. {status.github_oauth && (
  308. <Button
  309. theme='outline'
  310. className="w-full h-12 flex items-center justify-center !rounded-full border border-gray-200 hover:bg-gray-50 transition-colors"
  311. type="tertiary"
  312. icon={<IconGithubLogo size="large" />}
  313. size="large"
  314. onClick={handleGitHubClick}
  315. loading={githubLoading}
  316. >
  317. <span className="ml-3">{t('使用 GitHub 继续')}</span>
  318. </Button>
  319. )}
  320. {status.oidc_enabled && (
  321. <Button
  322. theme='outline'
  323. className="w-full h-12 flex items-center justify-center !rounded-full border border-gray-200 hover:bg-gray-50 transition-colors"
  324. type="tertiary"
  325. icon={<OIDCIcon style={{ color: '#1877F2' }} />}
  326. size="large"
  327. onClick={handleOIDCClick}
  328. loading={oidcLoading}
  329. >
  330. <span className="ml-3">{t('使用 OIDC 继续')}</span>
  331. </Button>
  332. )}
  333. {status.linuxdo_oauth && (
  334. <Button
  335. theme='outline'
  336. className="w-full h-12 flex items-center justify-center !rounded-full border border-gray-200 hover:bg-gray-50 transition-colors"
  337. type="tertiary"
  338. icon={<LinuxDoIcon style={{ color: '#E95420', width: '20px', height: '20px' }} />}
  339. size="large"
  340. onClick={handleLinuxDOClick}
  341. loading={linuxdoLoading}
  342. >
  343. <span className="ml-3">{t('使用 LinuxDO 继续')}</span>
  344. </Button>
  345. )}
  346. {status.telegram_oauth && (
  347. <div className="flex justify-center my-2">
  348. <TelegramLoginButton
  349. dataOnauth={onTelegramLoginClicked}
  350. botName={status.telegram_bot_name}
  351. />
  352. </div>
  353. )}
  354. <Divider margin='12px' align='center'>
  355. {t('或')}
  356. </Divider>
  357. <Button
  358. theme="solid"
  359. type="primary"
  360. className="w-full h-12 flex items-center justify-center bg-black text-white !rounded-full hover:bg-gray-800 transition-colors"
  361. icon={<IconMail size="large" />}
  362. size="large"
  363. onClick={handleEmailRegisterClick}
  364. loading={emailRegisterLoading}
  365. >
  366. <span className="ml-3">{t('使用 用户名 注册')}</span>
  367. </Button>
  368. </div>
  369. <div className="mt-6 text-center text-sm">
  370. <Text>{t('已有账户?')} <Link to="/login" className="text-blue-600 hover:text-blue-800 font-medium">{t('登录')}</Link></Text>
  371. </div>
  372. </div>
  373. </Card>
  374. </div>
  375. </div>
  376. );
  377. };
  378. const renderEmailRegisterForm = () => {
  379. return (
  380. <div className="flex flex-col items-center">
  381. <div className="w-full max-w-md">
  382. <div className="flex items-center justify-center mb-6 gap-2">
  383. <img src={logo} alt="Logo" className="h-10 rounded-full" />
  384. <Title heading={3} className='!text-gray-800'>{systemName}</Title>
  385. </div>
  386. <Card className="border-0 !rounded-2xl overflow-hidden">
  387. <div className="flex justify-center pt-6 pb-2">
  388. <Title heading={3} className="text-gray-800 dark:text-gray-200">{t('注 册')}</Title>
  389. </div>
  390. <div className="px-2 py-8">
  391. <Form className="space-y-3">
  392. <Form.Input
  393. field="username"
  394. label={t('用户名')}
  395. placeholder={t('请输入用户名')}
  396. name="username"
  397. size="large"
  398. onChange={(value) => handleChange('username', value)}
  399. prefix={<IconUser />}
  400. />
  401. <Form.Input
  402. field="password"
  403. label={t('密码')}
  404. placeholder={t('输入密码,最短 8 位,最长 20 位')}
  405. name="password"
  406. mode="password"
  407. size="large"
  408. onChange={(value) => handleChange('password', value)}
  409. prefix={<IconLock />}
  410. />
  411. <Form.Input
  412. field="password2"
  413. label={t('确认密码')}
  414. placeholder={t('确认密码')}
  415. name="password2"
  416. mode="password"
  417. size="large"
  418. onChange={(value) => handleChange('password2', value)}
  419. prefix={<IconLock />}
  420. />
  421. {showEmailVerification && (
  422. <>
  423. <Form.Input
  424. field="email"
  425. label={t('邮箱')}
  426. placeholder={t('输入邮箱地址')}
  427. name="email"
  428. type="email"
  429. size="large"
  430. onChange={(value) => handleChange('email', value)}
  431. prefix={<IconMail />}
  432. suffix={
  433. <Button
  434. onClick={sendVerificationCode}
  435. loading={verificationCodeLoading}
  436. disabled={disableButton || verificationCodeLoading}
  437. size="small"
  438. >
  439. {disableButton ? `${t('重新发送')} (${countdown})` : t('获取验证码')}
  440. </Button>
  441. }
  442. />
  443. <Form.Input
  444. field="verification_code"
  445. label={t('验证码')}
  446. placeholder={t('输入验证码')}
  447. name="verification_code"
  448. size="large"
  449. onChange={(value) => handleChange('verification_code', value)}
  450. prefix={<IconKey />}
  451. />
  452. </>
  453. )}
  454. <div className="space-y-2 pt-2">
  455. <Button
  456. theme="solid"
  457. className="w-full !rounded-full"
  458. type="primary"
  459. htmlType="submit"
  460. size="large"
  461. onClick={handleSubmit}
  462. loading={registerLoading}
  463. >
  464. {t('注册')}
  465. </Button>
  466. </div>
  467. </Form>
  468. {(status.github_oauth || status.oidc_enabled || status.wechat_login || status.linuxdo_oauth || status.telegram_oauth) && (
  469. <>
  470. <Divider margin='12px' align='center'>
  471. {t('或')}
  472. </Divider>
  473. <div className="mt-4 text-center">
  474. <Button
  475. theme="outline"
  476. type="tertiary"
  477. className="w-full !rounded-full"
  478. size="large"
  479. onClick={handleOtherRegisterOptionsClick}
  480. loading={otherRegisterOptionsLoading}
  481. >
  482. {t('其他注册选项')}
  483. </Button>
  484. </div>
  485. </>
  486. )}
  487. <div className="mt-6 text-center text-sm">
  488. <Text>{t('已有账户?')} <Link to="/login" className="text-blue-600 hover:text-blue-800 font-medium">{t('登录')}</Link></Text>
  489. </div>
  490. </div>
  491. </Card>
  492. </div>
  493. </div>
  494. );
  495. };
  496. const renderWeChatLoginModal = () => {
  497. return (
  498. <Modal
  499. title={t('微信扫码登录')}
  500. visible={showWeChatLoginModal}
  501. maskClosable={true}
  502. onOk={onSubmitWeChatVerificationCode}
  503. onCancel={() => setShowWeChatLoginModal(false)}
  504. okText={t('登录')}
  505. size="small"
  506. centered={true}
  507. okButtonProps={{
  508. loading: wechatCodeSubmitLoading,
  509. }}
  510. >
  511. <div className="flex flex-col items-center">
  512. <img src={status.wechat_qrcode} alt="微信二维码" className="mb-4" />
  513. </div>
  514. <div className="text-center mb-4">
  515. <p>{t('微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)')}</p>
  516. </div>
  517. <Form size="large">
  518. <Form.Input
  519. field="wechat_verification_code"
  520. placeholder={t('验证码')}
  521. label={t('验证码')}
  522. value={inputs.wechat_verification_code}
  523. onChange={(value) => handleChange('wechat_verification_code', value)}
  524. />
  525. </Form>
  526. </Modal>
  527. );
  528. };
  529. return (
  530. <div className="relative overflow-hidden bg-gray-100 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
  531. {/* 背景模糊晕染球 */}
  532. <div className="blur-ball blur-ball-indigo" style={{ top: '-80px', right: '-80px', transform: 'none' }} />
  533. <div className="blur-ball blur-ball-teal" style={{ top: '50%', left: '-120px' }} />
  534. <div className="w-full max-w-sm mt-[60px]">
  535. {showEmailRegister || !(status.github_oauth || status.oidc_enabled || status.wechat_login || status.linuxdo_oauth || status.telegram_oauth)
  536. ? renderEmailRegisterForm()
  537. : renderOAuthOptions()}
  538. {renderWeChatLoginModal()}
  539. {turnstileEnabled && (
  540. <div className="flex justify-center mt-6">
  541. <Turnstile
  542. sitekey={turnstileSiteKey}
  543. onVerify={(token) => {
  544. setTurnstileToken(token);
  545. }}
  546. />
  547. </div>
  548. )}
  549. </div>
  550. </div>
  551. );
  552. };
  553. export default RegisterForm;