PersonalSetting.jsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. } from '../../helpers';
  25. import { UserContext } from '../../context/User';
  26. import { Modal } from '@douyinfe/semi-ui';
  27. import { useTranslation } from 'react-i18next';
  28. // 导入子组件
  29. import UserInfoHeader from './personal/components/UserInfoHeader';
  30. import AccountManagement from './personal/cards/AccountManagement';
  31. import NotificationSettings from './personal/cards/NotificationSettings';
  32. import EmailBindModal from './personal/modals/EmailBindModal';
  33. import WeChatBindModal from './personal/modals/WeChatBindModal';
  34. import AccountDeleteModal from './personal/modals/AccountDeleteModal';
  35. import ChangePasswordModal from './personal/modals/ChangePasswordModal';
  36. const PersonalSetting = () => {
  37. const [userState, userDispatch] = useContext(UserContext);
  38. let navigate = useNavigate();
  39. const { t } = useTranslation();
  40. const [inputs, setInputs] = useState({
  41. wechat_verification_code: '',
  42. email_verification_code: '',
  43. email: '',
  44. self_account_deletion_confirmation: '',
  45. original_password: '',
  46. set_new_password: '',
  47. set_new_password_confirmation: '',
  48. });
  49. const [status, setStatus] = useState({});
  50. const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);
  51. const [showWeChatBindModal, setShowWeChatBindModal] = useState(false);
  52. const [showEmailBindModal, setShowEmailBindModal] = useState(false);
  53. const [showAccountDeleteModal, setShowAccountDeleteModal] = useState(false);
  54. const [turnstileEnabled, setTurnstileEnabled] = useState(false);
  55. const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
  56. const [turnstileToken, setTurnstileToken] = useState('');
  57. const [loading, setLoading] = useState(false);
  58. const [disableButton, setDisableButton] = useState(false);
  59. const [countdown, setCountdown] = useState(30);
  60. const [systemToken, setSystemToken] = useState('');
  61. const [notificationSettings, setNotificationSettings] = useState({
  62. warningType: 'email',
  63. warningThreshold: 100000,
  64. webhookUrl: '',
  65. webhookSecret: '',
  66. notificationEmail: '',
  67. barkUrl: '',
  68. acceptUnsetModelRatioModel: false,
  69. recordIpLog: false,
  70. });
  71. useEffect(() => {
  72. let saved = localStorage.getItem('status');
  73. if (saved) {
  74. const parsed = JSON.parse(saved);
  75. setStatus(parsed);
  76. if (parsed.turnstile_check) {
  77. setTurnstileEnabled(true);
  78. setTurnstileSiteKey(parsed.turnstile_site_key);
  79. } else {
  80. setTurnstileEnabled(false);
  81. setTurnstileSiteKey('');
  82. }
  83. }
  84. // Always refresh status from server to avoid stale flags (e.g., admin just enabled OAuth)
  85. (async () => {
  86. try {
  87. const res = await API.get('/api/status');
  88. const { success, data } = res.data;
  89. if (success && data) {
  90. setStatus(data);
  91. setStatusData(data);
  92. if (data.turnstile_check) {
  93. setTurnstileEnabled(true);
  94. setTurnstileSiteKey(data.turnstile_site_key);
  95. } else {
  96. setTurnstileEnabled(false);
  97. setTurnstileSiteKey('');
  98. }
  99. }
  100. } catch (e) {
  101. // ignore and keep local status
  102. }
  103. })();
  104. getUserData();
  105. }, []);
  106. useEffect(() => {
  107. let countdownInterval = null;
  108. if (disableButton && countdown > 0) {
  109. countdownInterval = setInterval(() => {
  110. setCountdown(countdown - 1);
  111. }, 1000);
  112. } else if (countdown === 0) {
  113. setDisableButton(false);
  114. setCountdown(30);
  115. }
  116. return () => clearInterval(countdownInterval); // Clean up on unmount
  117. }, [disableButton, countdown]);
  118. useEffect(() => {
  119. if (userState?.user?.setting) {
  120. const settings = JSON.parse(userState.user.setting);
  121. setNotificationSettings({
  122. warningType: settings.notify_type || 'email',
  123. warningThreshold: settings.quota_warning_threshold || 500000,
  124. webhookUrl: settings.webhook_url || '',
  125. webhookSecret: settings.webhook_secret || '',
  126. notificationEmail: settings.notification_email || '',
  127. barkUrl: settings.bark_url || '',
  128. acceptUnsetModelRatioModel:
  129. settings.accept_unset_model_ratio_model || false,
  130. recordIpLog: settings.record_ip_log || false,
  131. });
  132. }
  133. }, [userState?.user?.setting]);
  134. const handleInputChange = (name, value) => {
  135. setInputs((inputs) => ({ ...inputs, [name]: value }));
  136. };
  137. const generateAccessToken = async () => {
  138. const res = await API.get('/api/user/token');
  139. const { success, message, data } = res.data;
  140. if (success) {
  141. setSystemToken(data);
  142. await copy(data);
  143. showSuccess(t('令牌已重置并已复制到剪贴板'));
  144. } else {
  145. showError(message);
  146. }
  147. };
  148. const getUserData = async () => {
  149. let res = await API.get(`/api/user/self`);
  150. const { success, message, data } = res.data;
  151. if (success) {
  152. userDispatch({ type: 'login', payload: data });
  153. } else {
  154. showError(message);
  155. }
  156. };
  157. const handleSystemTokenClick = async (e) => {
  158. e.target.select();
  159. await copy(e.target.value);
  160. showSuccess(t('系统令牌已复制到剪切板'));
  161. };
  162. const deleteAccount = async () => {
  163. if (inputs.self_account_deletion_confirmation !== userState.user.username) {
  164. showError(t('请输入你的账户名以确认删除!'));
  165. return;
  166. }
  167. const res = await API.delete('/api/user/self');
  168. const { success, message } = res.data;
  169. if (success) {
  170. showSuccess(t('账户已删除!'));
  171. await API.get('/api/user/logout');
  172. userDispatch({ type: 'logout' });
  173. localStorage.removeItem('user');
  174. navigate('/login');
  175. } else {
  176. showError(message);
  177. }
  178. };
  179. const bindWeChat = async () => {
  180. if (inputs.wechat_verification_code === '') return;
  181. const res = await API.get(
  182. `/api/oauth/wechat/bind?code=${inputs.wechat_verification_code}`,
  183. );
  184. const { success, message } = res.data;
  185. if (success) {
  186. showSuccess(t('微信账户绑定成功!'));
  187. setShowWeChatBindModal(false);
  188. } else {
  189. showError(message);
  190. }
  191. };
  192. const changePassword = async () => {
  193. if (inputs.original_password === '') {
  194. showError(t('请输入原密码!'));
  195. return;
  196. }
  197. if (inputs.set_new_password === '') {
  198. showError(t('请输入新密码!'));
  199. return;
  200. }
  201. if (inputs.original_password === inputs.set_new_password) {
  202. showError(t('新密码需要和原密码不一致!'));
  203. return;
  204. }
  205. if (inputs.set_new_password !== inputs.set_new_password_confirmation) {
  206. showError(t('两次输入的密码不一致!'));
  207. return;
  208. }
  209. const res = await API.put(`/api/user/self`, {
  210. original_password: inputs.original_password,
  211. password: inputs.set_new_password,
  212. });
  213. const { success, message } = res.data;
  214. if (success) {
  215. showSuccess(t('密码修改成功!'));
  216. setShowWeChatBindModal(false);
  217. } else {
  218. showError(message);
  219. }
  220. setShowChangePasswordModal(false);
  221. };
  222. const sendVerificationCode = async () => {
  223. if (inputs.email === '') {
  224. showError(t('请输入邮箱!'));
  225. return;
  226. }
  227. setDisableButton(true);
  228. if (turnstileEnabled && turnstileToken === '') {
  229. showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
  230. return;
  231. }
  232. setLoading(true);
  233. const res = await API.get(
  234. `/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`,
  235. );
  236. const { success, message } = res.data;
  237. if (success) {
  238. showSuccess(t('验证码发送成功,请检查邮箱!'));
  239. } else {
  240. showError(message);
  241. }
  242. setLoading(false);
  243. };
  244. const bindEmail = async () => {
  245. if (inputs.email_verification_code === '') {
  246. showError(t('请输入邮箱验证码!'));
  247. return;
  248. }
  249. setLoading(true);
  250. const res = await API.get(
  251. `/api/oauth/email/bind?email=${inputs.email}&code=${inputs.email_verification_code}`,
  252. );
  253. const { success, message } = res.data;
  254. if (success) {
  255. showSuccess(t('邮箱账户绑定成功!'));
  256. setShowEmailBindModal(false);
  257. userState.user.email = inputs.email;
  258. } else {
  259. showError(message);
  260. }
  261. setLoading(false);
  262. };
  263. const copyText = async (text) => {
  264. if (await copy(text)) {
  265. showSuccess(t('已复制:') + text);
  266. } else {
  267. // setSearchKeyword(text);
  268. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  269. }
  270. };
  271. const handleNotificationSettingChange = (type, value) => {
  272. setNotificationSettings((prev) => ({
  273. ...prev,
  274. [type]: value.target
  275. ? value.target.value !== undefined
  276. ? value.target.value
  277. : value.target.checked
  278. : value, // handle checkbox properly
  279. }));
  280. };
  281. const saveNotificationSettings = async () => {
  282. try {
  283. const res = await API.put('/api/user/setting', {
  284. notify_type: notificationSettings.warningType,
  285. quota_warning_threshold: parseFloat(
  286. notificationSettings.warningThreshold,
  287. ),
  288. webhook_url: notificationSettings.webhookUrl,
  289. webhook_secret: notificationSettings.webhookSecret,
  290. notification_email: notificationSettings.notificationEmail,
  291. bark_url: notificationSettings.barkUrl,
  292. accept_unset_model_ratio_model:
  293. notificationSettings.acceptUnsetModelRatioModel,
  294. record_ip_log: notificationSettings.recordIpLog,
  295. });
  296. if (res.data.success) {
  297. showSuccess(t('设置保存成功'));
  298. await getUserData();
  299. } else {
  300. showError(res.data.message);
  301. }
  302. } catch (error) {
  303. showError(t('设置保存失败'));
  304. }
  305. };
  306. return (
  307. <div className='mt-[60px]'>
  308. <div className='flex justify-center'>
  309. <div className='w-full max-w-7xl mx-auto px-2'>
  310. {/* 顶部用户信息区域 */}
  311. <UserInfoHeader t={t} userState={userState} />
  312. {/* 账户管理和其他设置 */}
  313. <div className='grid grid-cols-1 xl:grid-cols-2 items-start gap-4 md:gap-6 mt-4 md:mt-6'>
  314. {/* 左侧:账户管理设置 */}
  315. <AccountManagement
  316. t={t}
  317. userState={userState}
  318. status={status}
  319. systemToken={systemToken}
  320. setShowEmailBindModal={setShowEmailBindModal}
  321. setShowWeChatBindModal={setShowWeChatBindModal}
  322. generateAccessToken={generateAccessToken}
  323. handleSystemTokenClick={handleSystemTokenClick}
  324. setShowChangePasswordModal={setShowChangePasswordModal}
  325. setShowAccountDeleteModal={setShowAccountDeleteModal}
  326. />
  327. {/* 右侧:其他设置 */}
  328. <NotificationSettings
  329. t={t}
  330. notificationSettings={notificationSettings}
  331. handleNotificationSettingChange={handleNotificationSettingChange}
  332. saveNotificationSettings={saveNotificationSettings}
  333. />
  334. </div>
  335. </div>
  336. </div>
  337. {/* 模态框组件 */}
  338. <EmailBindModal
  339. t={t}
  340. showEmailBindModal={showEmailBindModal}
  341. setShowEmailBindModal={setShowEmailBindModal}
  342. inputs={inputs}
  343. handleInputChange={handleInputChange}
  344. sendVerificationCode={sendVerificationCode}
  345. bindEmail={bindEmail}
  346. disableButton={disableButton}
  347. loading={loading}
  348. countdown={countdown}
  349. turnstileEnabled={turnstileEnabled}
  350. turnstileSiteKey={turnstileSiteKey}
  351. setTurnstileToken={setTurnstileToken}
  352. />
  353. <WeChatBindModal
  354. t={t}
  355. showWeChatBindModal={showWeChatBindModal}
  356. setShowWeChatBindModal={setShowWeChatBindModal}
  357. inputs={inputs}
  358. handleInputChange={handleInputChange}
  359. bindWeChat={bindWeChat}
  360. status={status}
  361. />
  362. <AccountDeleteModal
  363. t={t}
  364. showAccountDeleteModal={showAccountDeleteModal}
  365. setShowAccountDeleteModal={setShowAccountDeleteModal}
  366. inputs={inputs}
  367. handleInputChange={handleInputChange}
  368. deleteAccount={deleteAccount}
  369. userState={userState}
  370. turnstileEnabled={turnstileEnabled}
  371. turnstileSiteKey={turnstileSiteKey}
  372. setTurnstileToken={setTurnstileToken}
  373. />
  374. <ChangePasswordModal
  375. t={t}
  376. showChangePasswordModal={showChangePasswordModal}
  377. setShowChangePasswordModal={setShowChangePasswordModal}
  378. inputs={inputs}
  379. handleInputChange={handleInputChange}
  380. changePassword={changePassword}
  381. turnstileEnabled={turnstileEnabled}
  382. turnstileSiteKey={turnstileSiteKey}
  383. setTurnstileToken={setTurnstileToken}
  384. />
  385. </div>
  386. );
  387. };
  388. export default PersonalSetting;