SecurityTab.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import { useCallback, useEffect, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. Button,
  5. Empty,
  6. Form,
  7. Input,
  8. Modal,
  9. Space,
  10. Spin,
  11. Switch,
  12. Tabs,
  13. message,
  14. } from 'antd';
  15. import { ApiOutlined, SafetyOutlined, UserOutlined } from '@ant-design/icons';
  16. import { ClipboardManager, HttpUtil, IntlUtil, RandomUtil } from '@/utils';
  17. import type { AllSetting } from '@/models/setting';
  18. import { SettingListItem } from '@/components/ui';
  19. import { useMediaQuery } from '@/hooks/useMediaQuery';
  20. import { catTabLabel } from './catTabLabel';
  21. import TwoFactorModal from './TwoFactorModal';
  22. import './SecurityTab.css';
  23. interface ApiMsg<T = unknown> {
  24. success?: boolean;
  25. msg?: string;
  26. obj?: T;
  27. }
  28. interface ApiTokenRow {
  29. id: number;
  30. name: string;
  31. enabled: boolean;
  32. createdAt: number;
  33. scope: 'admin' | 'monitor' | 'node-sync';
  34. expiresAt: number;
  35. }
  36. interface SecurityTabProps {
  37. allSetting: AllSetting;
  38. updateSetting: (patch: Partial<AllSetting>) => void;
  39. saveSetting: (payload: Partial<AllSetting> & Record<string, unknown>) => Promise<unknown>;
  40. }
  41. const UNIX_MILLISECONDS_THRESHOLD = 100_000_000_000;
  42. function apiTokenCreatedAtMilliseconds(createdAt: number): number {
  43. return createdAt < UNIX_MILLISECONDS_THRESHOLD ? createdAt * 1000 : createdAt;
  44. }
  45. type TfaType = 'set' | 'confirm';
  46. interface TfaState {
  47. open: boolean;
  48. title: string;
  49. description: string;
  50. token: string;
  51. type: TfaType;
  52. onConfirm: (success: boolean, code?: string) => void;
  53. }
  54. const TFA_INITIAL: TfaState = {
  55. open: false,
  56. title: '',
  57. description: '',
  58. token: '',
  59. type: 'set',
  60. onConfirm: () => {},
  61. };
  62. export default function SecurityTab({ allSetting, updateSetting, saveSetting }: SecurityTabProps) {
  63. const { t } = useTranslation();
  64. const { isMobile } = useMediaQuery();
  65. const [modal, modalContextHolder] = Modal.useModal();
  66. const [messageApi, messageContextHolder] = message.useMessage();
  67. const [tfa, setTfa] = useState<TfaState>(TFA_INITIAL);
  68. const [user, setUser] = useState({
  69. oldUsername: '',
  70. oldPassword: '',
  71. newUsername: '',
  72. newPassword: '',
  73. });
  74. const [updating, setUpdating] = useState(false);
  75. const [apiTokens, setApiTokens] = useState<ApiTokenRow[]>([]);
  76. const [apiTokensLoading, setApiTokensLoading] = useState(false);
  77. const [createOpen, setCreateOpen] = useState(false);
  78. const [createName, setCreateName] = useState('');
  79. const [creating, setCreating] = useState(false);
  80. const [createdToken, setCreatedToken] = useState<{ name: string; token: string } | null>(null);
  81. const openTfa = useCallback((opts: Omit<TfaState, 'open'>) => {
  82. setTfa({ ...opts, open: true });
  83. }, []);
  84. const onTfaConfirm = useCallback((success: boolean, code?: string) => {
  85. tfa.onConfirm(success, code);
  86. }, [tfa]);
  87. function updateUserField<K extends keyof typeof user>(key: K, value: string) {
  88. setUser((prev) => ({ ...prev, [key]: value }));
  89. }
  90. const sendUpdateUser = useCallback(async (twoFactorCode = '') => {
  91. setUpdating(true);
  92. try {
  93. const msg = await HttpUtil.post('/panel/api/setting/updateUser', { ...user, twoFactorCode }) as ApiMsg;
  94. if (msg?.success) {
  95. await HttpUtil.post('/logout');
  96. const basePath = window.X_UI_BASE_PATH || '/';
  97. window.location.replace(basePath);
  98. }
  99. } finally {
  100. setUpdating(false);
  101. }
  102. }, [user]);
  103. function onUpdateUserClick() {
  104. if (allSetting.twoFactorEnable) {
  105. openTfa({
  106. title: t('pages.settings.security.twoFactorModalChangeCredentialsTitle'),
  107. description: t('pages.settings.security.twoFactorModalChangeCredentialsStep'),
  108. token: '',
  109. type: 'confirm',
  110. onConfirm: (ok: boolean, code?: string) => {
  111. if (ok) sendUpdateUser(code || '');
  112. },
  113. });
  114. } else {
  115. sendUpdateUser();
  116. }
  117. }
  118. const loadApiTokens = useCallback(async () => {
  119. setApiTokensLoading(true);
  120. try {
  121. const msg = await HttpUtil.get('/panel/api/setting/apiTokens') as ApiMsg<ApiTokenRow[]>;
  122. if (msg?.success) setApiTokens(Array.isArray(msg.obj) ? msg.obj : []);
  123. } finally {
  124. setApiTokensLoading(false);
  125. }
  126. }, []);
  127. useEffect(() => {
  128. loadApiTokens();
  129. }, [loadApiTokens]);
  130. async function copyToken(token: string) {
  131. if (!token) return;
  132. const ok = await ClipboardManager.copyText(token);
  133. if (ok) messageApi.success(t('copySuccess'));
  134. else messageApi.error(t('copyFail') ?? 'Copy failed');
  135. }
  136. function openCreateModal() {
  137. setCreateName('');
  138. setCreateOpen(true);
  139. }
  140. async function confirmCreateToken() {
  141. const name = createName.trim();
  142. if (!name) {
  143. messageApi.error(t('pages.settings.security.apiTokenNameRequired') || 'Name is required');
  144. return;
  145. }
  146. setCreating(true);
  147. try {
  148. const msg = await HttpUtil.post('/panel/api/setting/apiTokens/create', { name }) as ApiMsg<{ token?: string }>;
  149. if (msg?.success) {
  150. setCreateOpen(false);
  151. await loadApiTokens();
  152. if (msg.obj?.token) {
  153. setCreatedToken({ name, token: msg.obj.token });
  154. }
  155. }
  156. } finally {
  157. setCreating(false);
  158. }
  159. }
  160. function confirmDeleteToken(row: ApiTokenRow) {
  161. modal.confirm({
  162. title: `${t('delete')} "${row.name}"?`,
  163. content: t('pages.settings.security.apiTokenDeleteWarning')
  164. || 'Any caller using this token will stop authenticating immediately.',
  165. okText: t('delete'),
  166. cancelText: t('cancel'),
  167. okType: 'danger',
  168. onOk: async () => {
  169. const msg = await HttpUtil.post(`/panel/api/setting/apiTokens/delete/${row.id}`, { expectedScope: row.scope }) as ApiMsg;
  170. if (msg?.success) await loadApiTokens();
  171. },
  172. });
  173. }
  174. async function toggleTokenEnabled(row: ApiTokenRow) {
  175. const target = !row.enabled;
  176. const msg = await HttpUtil.post(`/panel/api/setting/apiTokens/setEnabled/${row.id}`, { enabled: target, expectedScope: row.scope }) as ApiMsg;
  177. if (msg?.success) {
  178. setApiTokens((prev) => prev.map((r) => (r.id === row.id ? { ...r, enabled: target } : r)));
  179. }
  180. }
  181. function formatTokenDate(ts: number): string {
  182. if (!ts) return '';
  183. return IntlUtil.formatDate(apiTokenCreatedAtMilliseconds(ts));
  184. }
  185. function toggleTwoFactor() {
  186. if (!allSetting.twoFactorEnable) {
  187. const newToken = RandomUtil.randomBase32String();
  188. openTfa({
  189. title: t('pages.settings.security.twoFactorModalSetTitle'),
  190. description: '',
  191. token: newToken,
  192. type: 'set',
  193. onConfirm: (ok: boolean) => {
  194. if (ok) {
  195. messageApi.success(t('pages.settings.security.twoFactorModalSetSuccess'));
  196. updateSetting({ twoFactorToken: newToken, twoFactorEnable: true });
  197. } else {
  198. updateSetting({ twoFactorEnable: false });
  199. }
  200. },
  201. });
  202. } else {
  203. openTfa({
  204. title: t('pages.settings.security.twoFactorModalDeleteTitle'),
  205. description: t('pages.settings.security.twoFactorModalRemoveStep'),
  206. token: '',
  207. type: 'confirm',
  208. onConfirm: async (ok: boolean, code?: string) => {
  209. if (!ok) return;
  210. const next = {
  211. ...allSetting,
  212. twoFactorEnable: false,
  213. twoFactorToken: '',
  214. twoFactorCode: code || '',
  215. };
  216. const msg = await saveSetting(next) as ApiMsg;
  217. if (msg?.success) {
  218. messageApi.success(t('pages.settings.security.twoFactorModalDeleteSuccess'));
  219. updateSetting({ twoFactorEnable: false, twoFactorToken: '', hasTwoFactorToken: false });
  220. }
  221. },
  222. });
  223. }
  224. }
  225. return (
  226. <>
  227. {messageContextHolder}
  228. {modalContextHolder}
  229. <Tabs defaultActiveKey="1" items={[
  230. {
  231. key: '1',
  232. label: catTabLabel(<UserOutlined />, t('pages.settings.security.admin'), isMobile),
  233. children: (
  234. <>
  235. <SettingListItem paddings="small" title={t('pages.settings.oldUsername')}>
  236. <Input value={user.oldUsername} autoComplete="username"
  237. onChange={(e) => updateUserField('oldUsername', e.target.value)} />
  238. </SettingListItem>
  239. <SettingListItem paddings="small" title={t('pages.settings.currentPassword')}>
  240. <Input.Password value={user.oldPassword} autoComplete="current-password"
  241. onChange={(e) => updateUserField('oldPassword', e.target.value)} />
  242. </SettingListItem>
  243. <SettingListItem paddings="small" title={t('pages.settings.newUsername')}>
  244. <Input value={user.newUsername}
  245. onChange={(e) => updateUserField('newUsername', e.target.value)} />
  246. </SettingListItem>
  247. <SettingListItem paddings="small" title={t('pages.settings.newPassword')}>
  248. <Input.Password value={user.newPassword} autoComplete="new-password"
  249. onChange={(e) => updateUserField('newPassword', e.target.value)} />
  250. </SettingListItem>
  251. <div className="security-actions">
  252. <Space style={{ padding: '0 20px' }}>
  253. <Button type="primary" loading={updating} onClick={onUpdateUserClick}>
  254. {t('confirm')}
  255. </Button>
  256. </Space>
  257. </div>
  258. </>
  259. ),
  260. },
  261. {
  262. key: '2',
  263. label: catTabLabel(<SafetyOutlined />, t('pages.settings.security.twoFactor'), isMobile),
  264. children: (
  265. <SettingListItem
  266. paddings="small"
  267. title={t('pages.settings.security.twoFactorEnable')}
  268. description={t('pages.settings.security.twoFactorEnableDesc')}
  269. >
  270. <Switch checked={allSetting.twoFactorEnable} onClick={toggleTwoFactor} />
  271. </SettingListItem>
  272. ),
  273. },
  274. {
  275. key: '3',
  276. label: catTabLabel(<ApiOutlined />, t('pages.nodes.apiToken'), isMobile),
  277. children: (
  278. <div className="api-token-section">
  279. <div className="api-token-header">
  280. <p className="api-token-hint">{t('pages.nodes.apiTokenHint')}</p>
  281. <Button type="primary" size="small" onClick={openCreateModal}>
  282. + {t('pages.settings.security.apiTokenNew') || 'New token'}
  283. </Button>
  284. </div>
  285. <Spin spinning={apiTokensLoading}>
  286. {!apiTokens.length && !apiTokensLoading && (
  287. <Empty description={t('pages.settings.security.apiTokenEmpty') || 'No tokens yet'} />
  288. )}
  289. {apiTokens.map((row) => (
  290. <div key={row.id} className={`api-token-row${row.enabled ? '' : ' disabled'}`}>
  291. <div className="api-token-row-head">
  292. <div className="api-token-name-wrap">
  293. <span className="api-token-name">{row.name}</span>
  294. <span className="api-token-created">{formatTokenDate(row.createdAt)}</span>
  295. </div>
  296. <div className="api-token-actions">
  297. <Switch size="small" checked={row.enabled} onChange={() => toggleTokenEnabled(row)} />
  298. <Button size="small" danger type="text" onClick={() => confirmDeleteToken(row)}>
  299. {t('delete')}
  300. </Button>
  301. </div>
  302. </div>
  303. </div>
  304. ))}
  305. </Spin>
  306. </div>
  307. ),
  308. },
  309. ]} />
  310. <Modal
  311. open={createOpen}
  312. title={t('pages.settings.security.apiTokenNew') || 'New API token'}
  313. confirmLoading={creating}
  314. okText={t('confirm')}
  315. cancelText={t('cancel')}
  316. onOk={confirmCreateToken}
  317. onCancel={() => setCreateOpen(false)}
  318. >
  319. <Form layout="vertical">
  320. <Form.Item label={t('pages.settings.security.apiTokenName') || 'Name'} required>
  321. <Input
  322. value={createName}
  323. maxLength={64}
  324. placeholder={t('pages.settings.security.apiTokenNamePlaceholder') || 'e.g. central-panel-a'}
  325. onChange={(e) => setCreateName(e.target.value)}
  326. onPressEnter={confirmCreateToken}
  327. />
  328. </Form.Item>
  329. </Form>
  330. </Modal>
  331. <Modal
  332. open={!!createdToken}
  333. title={t('pages.settings.security.apiTokenCreatedTitle') || 'Token created'}
  334. okText={t('done')}
  335. onOk={() => setCreatedToken(null)}
  336. onCancel={() => setCreatedToken(null)}
  337. cancelButtonProps={{ style: { display: 'none' } }}
  338. >
  339. <p className="api-token-created-notice">
  340. {t('pages.settings.security.apiTokenCreatedNotice')
  341. || 'Copy this token now. For security it is not stored in readable form and will not be shown again.'}
  342. </p>
  343. <div className="api-token-value-wrap">
  344. <code className="api-token-value">{createdToken?.token}</code>
  345. <Button size="small" type="primary" onClick={() => createdToken && copyToken(createdToken.token)}>
  346. {t('copy')}
  347. </Button>
  348. </div>
  349. </Modal>
  350. <TwoFactorModal
  351. open={tfa.open}
  352. title={tfa.title}
  353. description={tfa.description}
  354. token={tfa.token}
  355. type={tfa.type}
  356. onConfirm={onTfaConfirm}
  357. onOpenChange={(open) => setTfa((prev) => ({ ...prev, open }))}
  358. />
  359. </>
  360. );
  361. }