PersonalSetting.jsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 { useNavigate } from 'react-router-dom';
  17. import {
  18. API,
  19. copy,
  20. showError,
  21. showInfo,
  22. showSuccess,
  23. setStatusData,
  24. prepareCredentialCreationOptions,
  25. buildRegistrationResult,
  26. isPasskeySupported,
  27. setUserData,
  28. } from '../../helpers';
  29. import { UserContext } from '../../context/User';
  30. import { Modal } from '@douyinfe/semi-ui';
  31. import { useTranslation } from 'react-i18next';
  32. // 导入子组件
  33. import UserInfoHeader from './personal/components/UserInfoHeader';
  34. import AccountManagement from './personal/cards/AccountManagement';
  35. import NotificationSettings from './personal/cards/NotificationSettings';
  36. import EmailBindModal from './personal/modals/EmailBindModal';
  37. import WeChatBindModal from './personal/modals/WeChatBindModal';
  38. import AccountDeleteModal from './personal/modals/AccountDeleteModal';
  39. import ChangePasswordModal from './personal/modals/ChangePasswordModal';
  40. const PersonalSetting = () => {
  41. const [userState, userDispatch] = useContext(UserContext);
  42. let navigate = useNavigate();
  43. const { t } = useTranslation();
  44. const [inputs, setInputs] = useState({
  45. wechat_verification_code: '',
  46. email_verification_code: '',
  47. email: '',
  48. self_account_deletion_confirmation: '',
  49. original_password: '',
  50. set_new_password: '',
  51. set_new_password_confirmation: '',
  52. });
  53. const [status, setStatus] = useState({});
  54. const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);
  55. const [showWeChatBindModal, setShowWeChatBindModal] = useState(false);
  56. const [showEmailBindModal, setShowEmailBindModal] = useState(false);
  57. const [showAccountDeleteModal, setShowAccountDeleteModal] = useState(false);
  58. const [turnstileEnabled, setTurnstileEnabled] = useState(false);
  59. const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
  60. const [turnstileToken, setTurnstileToken] = useState('');
  61. const [loading, setLoading] = useState(false);
  62. const [disableButton, setDisableButton] = useState(false);
  63. const [countdown, setCountdown] = useState(30);
  64. const [systemToken, setSystemToken] = useState('');
  65. const [passkeyStatus, setPasskeyStatus] = useState({ enabled: false });
  66. const [passkeyRegisterLoading, setPasskeyRegisterLoading] = useState(false);
  67. const [passkeyDeleteLoading, setPasskeyDeleteLoading] = useState(false);
  68. const [passkeySupported, setPasskeySupported] = useState(false);
  69. const [notificationSettings, setNotificationSettings] = useState({
  70. warningType: 'email',
  71. warningThreshold: 100000,
  72. webhookUrl: '',
  73. webhookSecret: '',
  74. notificationEmail: '',
  75. barkUrl: '',
  76. gotifyUrl: '',
  77. gotifyToken: '',
  78. gotifyPriority: 5,
  79. acceptUnsetModelRatioModel: false,
  80. recordIpLog: false,
  81. });
  82. useEffect(() => {
  83. let saved = localStorage.getItem('status');
  84. if (saved) {
  85. const parsed = JSON.parse(saved);
  86. setStatus(parsed);
  87. if (parsed.turnstile_check) {
  88. setTurnstileEnabled(true);
  89. setTurnstileSiteKey(parsed.turnstile_site_key);
  90. } else {
  91. setTurnstileEnabled(false);
  92. setTurnstileSiteKey('');
  93. }
  94. }
  95. // Always refresh status from server to avoid stale flags (e.g., admin just enabled OAuth)
  96. (async () => {
  97. try {
  98. const res = await API.get('/api/status');
  99. const { success, data } = res.data;
  100. if (success && data) {
  101. setStatus(data);
  102. setStatusData(data);
  103. if (data.turnstile_check) {
  104. setTurnstileEnabled(true);
  105. setTurnstileSiteKey(data.turnstile_site_key);
  106. } else {
  107. setTurnstileEnabled(false);
  108. setTurnstileSiteKey('');
  109. }
  110. }
  111. } catch (e) {
  112. // ignore and keep local status
  113. }
  114. })();
  115. getUserData();
  116. isPasskeySupported()
  117. .then(setPasskeySupported)
  118. .catch(() => setPasskeySupported(false));
  119. }, []);
  120. useEffect(() => {
  121. let countdownInterval = null;
  122. if (disableButton && countdown > 0) {
  123. countdownInterval = setInterval(() => {
  124. setCountdown(countdown - 1);
  125. }, 1000);
  126. } else if (countdown === 0) {
  127. setDisableButton(false);
  128. setCountdown(30);
  129. }
  130. return () => clearInterval(countdownInterval); // Clean up on unmount
  131. }, [disableButton, countdown]);
  132. useEffect(() => {
  133. if (userState?.user?.setting) {
  134. const settings = JSON.parse(userState.user.setting);
  135. setNotificationSettings({
  136. warningType: settings.notify_type || 'email',
  137. warningThreshold: settings.quota_warning_threshold || 500000,
  138. webhookUrl: settings.webhook_url || '',
  139. webhookSecret: settings.webhook_secret || '',
  140. notificationEmail: settings.notification_email || '',
  141. barkUrl: settings.bark_url || '',
  142. gotifyUrl: settings.gotify_url || '',
  143. gotifyToken: settings.gotify_token || '',
  144. gotifyPriority:
  145. settings.gotify_priority !== undefined
  146. ? settings.gotify_priority
  147. : 5,
  148. acceptUnsetModelRatioModel:
  149. settings.accept_unset_model_ratio_model || false,
  150. recordIpLog: settings.record_ip_log || false,
  151. });
  152. }
  153. }, [userState?.user?.setting]);
  154. const handleInputChange = (name, value) => {
  155. setInputs((inputs) => ({ ...inputs, [name]: value }));
  156. };
  157. const generateAccessToken = async () => {
  158. const res = await API.get('/api/user/token');
  159. const { success, message, data } = res.data;
  160. if (success) {
  161. setSystemToken(data);
  162. await copy(data);
  163. showSuccess(t('令牌已重置并已复制到剪贴板'));
  164. } else {
  165. showError(message);
  166. }
  167. };
  168. const loadPasskeyStatus = async () => {
  169. try {
  170. const res = await API.get('/api/user/passkey');
  171. const { success, data, message } = res.data;
  172. if (success) {
  173. setPasskeyStatus({
  174. enabled: data?.enabled || false,
  175. last_used_at: data?.last_used_at || null,
  176. backup_eligible: data?.backup_eligible || false,
  177. backup_state: data?.backup_state || false,
  178. });
  179. } else {
  180. showError(message);
  181. }
  182. } catch (error) {
  183. // 忽略错误,保留默认状态
  184. }
  185. };
  186. const handleRegisterPasskey = async () => {
  187. if (!passkeySupported || !window.PublicKeyCredential) {
  188. showInfo(t('当前设备不支持 Passkey'));
  189. return;
  190. }
  191. setPasskeyRegisterLoading(true);
  192. try {
  193. const beginRes = await API.post('/api/user/passkey/register/begin');
  194. const { success, message, data } = beginRes.data;
  195. if (!success) {
  196. showError(message || t('无法发起 Passkey 注册'));
  197. return;
  198. }
  199. const publicKey = prepareCredentialCreationOptions(data?.options || data?.publicKey || data);
  200. const credential = await navigator.credentials.create({ publicKey });
  201. const payload = buildRegistrationResult(credential);
  202. if (!payload) {
  203. showError(t('Passkey 注册失败,请重试'));
  204. return;
  205. }
  206. const finishRes = await API.post('/api/user/passkey/register/finish', payload);
  207. if (finishRes.data.success) {
  208. showSuccess(t('Passkey 注册成功'));
  209. await loadPasskeyStatus();
  210. } else {
  211. showError(finishRes.data.message || t('Passkey 注册失败,请重试'));
  212. }
  213. } catch (error) {
  214. if (error?.name === 'AbortError') {
  215. showInfo(t('已取消 Passkey 注册'));
  216. } else {
  217. showError(t('Passkey 注册失败,请重试'));
  218. }
  219. } finally {
  220. setPasskeyRegisterLoading(false);
  221. }
  222. };
  223. const handleRemovePasskey = async () => {
  224. setPasskeyDeleteLoading(true);
  225. try {
  226. const res = await API.delete('/api/user/passkey');
  227. const { success, message } = res.data;
  228. if (success) {
  229. showSuccess(t('Passkey 已解绑'));
  230. await loadPasskeyStatus();
  231. } else {
  232. showError(message || t('操作失败,请重试'));
  233. }
  234. } catch (error) {
  235. showError(t('操作失败,请重试'));
  236. } finally {
  237. setPasskeyDeleteLoading(false);
  238. }
  239. };
  240. const getUserData = async () => {
  241. let res = await API.get(`/api/user/self`);
  242. const { success, message, data } = res.data;
  243. if (success) {
  244. userDispatch({ type: 'login', payload: data });
  245. setUserData(data);
  246. await loadPasskeyStatus();
  247. } else {
  248. showError(message);
  249. }
  250. };
  251. const handleSystemTokenClick = async (e) => {
  252. e.target.select();
  253. await copy(e.target.value);
  254. showSuccess(t('系统令牌已复制到剪切板'));
  255. };
  256. const deleteAccount = async () => {
  257. if (inputs.self_account_deletion_confirmation !== userState.user.username) {
  258. showError(t('请输入你的账户名以确认删除!'));
  259. return;
  260. }
  261. const res = await API.delete('/api/user/self');
  262. const { success, message } = res.data;
  263. if (success) {
  264. showSuccess(t('账户已删除!'));
  265. await API.get('/api/user/logout');
  266. userDispatch({ type: 'logout' });
  267. localStorage.removeItem('user');
  268. navigate('/login');
  269. } else {
  270. showError(message);
  271. }
  272. };
  273. const bindWeChat = async () => {
  274. if (inputs.wechat_verification_code === '') return;
  275. const res = await API.get(
  276. `/api/oauth/wechat/bind?code=${inputs.wechat_verification_code}`,
  277. );
  278. const { success, message } = res.data;
  279. if (success) {
  280. showSuccess(t('微信账户绑定成功!'));
  281. setShowWeChatBindModal(false);
  282. } else {
  283. showError(message);
  284. }
  285. };
  286. const changePassword = async () => {
  287. if (inputs.original_password === '') {
  288. showError(t('请输入原密码!'));
  289. return;
  290. }
  291. if (inputs.set_new_password === '') {
  292. showError(t('请输入新密码!'));
  293. return;
  294. }
  295. if (inputs.original_password === inputs.set_new_password) {
  296. showError(t('新密码需要和原密码不一致!'));
  297. return;
  298. }
  299. if (inputs.set_new_password !== inputs.set_new_password_confirmation) {
  300. showError(t('两次输入的密码不一致!'));
  301. return;
  302. }
  303. const res = await API.put(`/api/user/self`, {
  304. original_password: inputs.original_password,
  305. password: inputs.set_new_password,
  306. });
  307. const { success, message } = res.data;
  308. if (success) {
  309. showSuccess(t('密码修改成功!'));
  310. setShowWeChatBindModal(false);
  311. } else {
  312. showError(message);
  313. }
  314. setShowChangePasswordModal(false);
  315. };
  316. const sendVerificationCode = async () => {
  317. if (inputs.email === '') {
  318. showError(t('请输入邮箱!'));
  319. return;
  320. }
  321. setDisableButton(true);
  322. if (turnstileEnabled && turnstileToken === '') {
  323. showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
  324. return;
  325. }
  326. setLoading(true);
  327. const res = await API.get(
  328. `/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`,
  329. );
  330. const { success, message } = res.data;
  331. if (success) {
  332. showSuccess(t('验证码发送成功,请检查邮箱!'));
  333. } else {
  334. showError(message);
  335. }
  336. setLoading(false);
  337. };
  338. const bindEmail = async () => {
  339. if (inputs.email_verification_code === '') {
  340. showError(t('请输入邮箱验证码!'));
  341. return;
  342. }
  343. setLoading(true);
  344. const res = await API.get(
  345. `/api/oauth/email/bind?email=${inputs.email}&code=${inputs.email_verification_code}`,
  346. );
  347. const { success, message } = res.data;
  348. if (success) {
  349. showSuccess(t('邮箱账户绑定成功!'));
  350. setShowEmailBindModal(false);
  351. userState.user.email = inputs.email;
  352. } else {
  353. showError(message);
  354. }
  355. setLoading(false);
  356. };
  357. const copyText = async (text) => {
  358. if (await copy(text)) {
  359. showSuccess(t('已复制:') + text);
  360. } else {
  361. // setSearchKeyword(text);
  362. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  363. }
  364. };
  365. const handleNotificationSettingChange = (type, value) => {
  366. setNotificationSettings((prev) => ({
  367. ...prev,
  368. [type]: value.target
  369. ? value.target.value !== undefined
  370. ? value.target.value
  371. : value.target.checked
  372. : value, // handle checkbox properly
  373. }));
  374. };
  375. const saveNotificationSettings = async () => {
  376. try {
  377. const res = await API.put('/api/user/setting', {
  378. notify_type: notificationSettings.warningType,
  379. quota_warning_threshold: parseFloat(
  380. notificationSettings.warningThreshold,
  381. ),
  382. webhook_url: notificationSettings.webhookUrl,
  383. webhook_secret: notificationSettings.webhookSecret,
  384. notification_email: notificationSettings.notificationEmail,
  385. bark_url: notificationSettings.barkUrl,
  386. gotify_url: notificationSettings.gotifyUrl,
  387. gotify_token: notificationSettings.gotifyToken,
  388. gotify_priority: (() => {
  389. const parsed = parseInt(notificationSettings.gotifyPriority);
  390. return isNaN(parsed) ? 5 : parsed;
  391. })(),
  392. accept_unset_model_ratio_model:
  393. notificationSettings.acceptUnsetModelRatioModel,
  394. record_ip_log: notificationSettings.recordIpLog,
  395. });
  396. if (res.data.success) {
  397. showSuccess(t('设置保存成功'));
  398. await getUserData();
  399. } else {
  400. showError(res.data.message);
  401. }
  402. } catch (error) {
  403. showError(t('设置保存失败'));
  404. }
  405. };
  406. return (
  407. <div className='mt-[60px]'>
  408. <div className='flex justify-center'>
  409. <div className='w-full max-w-7xl mx-auto px-2'>
  410. {/* 顶部用户信息区域 */}
  411. <UserInfoHeader t={t} userState={userState} />
  412. {/* 账户管理和其他设置 */}
  413. <div className='grid grid-cols-1 xl:grid-cols-2 items-start gap-4 md:gap-6 mt-4 md:mt-6'>
  414. {/* 左侧:账户管理设置 */}
  415. <AccountManagement
  416. t={t}
  417. userState={userState}
  418. status={status}
  419. systemToken={systemToken}
  420. setShowEmailBindModal={setShowEmailBindModal}
  421. setShowWeChatBindModal={setShowWeChatBindModal}
  422. generateAccessToken={generateAccessToken}
  423. handleSystemTokenClick={handleSystemTokenClick}
  424. setShowChangePasswordModal={setShowChangePasswordModal}
  425. setShowAccountDeleteModal={setShowAccountDeleteModal}
  426. passkeyStatus={passkeyStatus}
  427. passkeySupported={passkeySupported}
  428. passkeyRegisterLoading={passkeyRegisterLoading}
  429. passkeyDeleteLoading={passkeyDeleteLoading}
  430. onPasskeyRegister={handleRegisterPasskey}
  431. onPasskeyDelete={handleRemovePasskey}
  432. />
  433. {/* 右侧:其他设置 */}
  434. <NotificationSettings
  435. t={t}
  436. notificationSettings={notificationSettings}
  437. handleNotificationSettingChange={handleNotificationSettingChange}
  438. saveNotificationSettings={saveNotificationSettings}
  439. />
  440. </div>
  441. </div>
  442. </div>
  443. {/* 模态框组件 */}
  444. <EmailBindModal
  445. t={t}
  446. showEmailBindModal={showEmailBindModal}
  447. setShowEmailBindModal={setShowEmailBindModal}
  448. inputs={inputs}
  449. handleInputChange={handleInputChange}
  450. sendVerificationCode={sendVerificationCode}
  451. bindEmail={bindEmail}
  452. disableButton={disableButton}
  453. loading={loading}
  454. countdown={countdown}
  455. turnstileEnabled={turnstileEnabled}
  456. turnstileSiteKey={turnstileSiteKey}
  457. setTurnstileToken={setTurnstileToken}
  458. />
  459. <WeChatBindModal
  460. t={t}
  461. showWeChatBindModal={showWeChatBindModal}
  462. setShowWeChatBindModal={setShowWeChatBindModal}
  463. inputs={inputs}
  464. handleInputChange={handleInputChange}
  465. bindWeChat={bindWeChat}
  466. status={status}
  467. />
  468. <AccountDeleteModal
  469. t={t}
  470. showAccountDeleteModal={showAccountDeleteModal}
  471. setShowAccountDeleteModal={setShowAccountDeleteModal}
  472. inputs={inputs}
  473. handleInputChange={handleInputChange}
  474. deleteAccount={deleteAccount}
  475. userState={userState}
  476. turnstileEnabled={turnstileEnabled}
  477. turnstileSiteKey={turnstileSiteKey}
  478. setTurnstileToken={setTurnstileToken}
  479. />
  480. <ChangePasswordModal
  481. t={t}
  482. showChangePasswordModal={showChangePasswordModal}
  483. setShowChangePasswordModal={setShowChangePasswordModal}
  484. inputs={inputs}
  485. handleInputChange={handleInputChange}
  486. changePassword={changePassword}
  487. turnstileEnabled={turnstileEnabled}
  488. turnstileSiteKey={turnstileSiteKey}
  489. setTurnstileToken={setTurnstileToken}
  490. />
  491. </div>
  492. );
  493. };
  494. export default PersonalSetting;