SecurityTab.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <script setup>
  2. import { onMounted, reactive, ref } from 'vue';
  3. import { useI18n } from 'vue-i18n';
  4. import { Modal, message } from 'ant-design-vue';
  5. import { HttpUtil, RandomUtil } from '@/utils';
  6. import SettingListItem from '@/components/SettingListItem.vue';
  7. import TwoFactorModal from './TwoFactorModal.vue';
  8. const { t } = useI18n();
  9. const props = defineProps({
  10. allSetting: { type: Object, required: true },
  11. });
  12. // 2FA modal state — both the "set" (enabling) and "confirm" (changing
  13. // password / disabling) flows route through the same component.
  14. const tfa = reactive({
  15. open: false,
  16. title: '',
  17. description: '',
  18. token: '',
  19. type: 'set',
  20. // resolveConfirm is called by the modal's @confirm with the success bool;
  21. // it then routes the value back to whichever flow opened the modal.
  22. resolveConfirm: (_success) => { },
  23. });
  24. function openTfa({ title, description = '', token = '', type, onConfirm }) {
  25. tfa.title = title;
  26. tfa.description = description;
  27. tfa.token = token;
  28. tfa.type = type;
  29. tfa.resolveConfirm = onConfirm;
  30. tfa.open = true;
  31. }
  32. function onTfaConfirm(success) {
  33. tfa.resolveConfirm(success);
  34. }
  35. const user = reactive({
  36. oldUsername: '',
  37. oldPassword: '',
  38. newUsername: '',
  39. newPassword: '',
  40. });
  41. const updating = ref(false);
  42. async function sendUpdateUser() {
  43. updating.value = true;
  44. try {
  45. const msg = await HttpUtil.post('/panel/setting/updateUser', user);
  46. if (msg?.success) {
  47. await HttpUtil.post('/logout');
  48. const basePath = window.X_UI_BASE_PATH || '/';
  49. window.location.replace(basePath);
  50. }
  51. } finally {
  52. updating.value = false;
  53. }
  54. }
  55. function updateUser() {
  56. if (props.allSetting.twoFactorEnable) {
  57. openTfa({
  58. title: t('pages.settings.security.twoFactorModalChangeCredentialsTitle'),
  59. description: t('pages.settings.security.twoFactorModalChangeCredentialsStep'),
  60. token: props.allSetting.twoFactorToken,
  61. type: 'confirm',
  62. onConfirm: (ok) => { if (ok) sendUpdateUser(); },
  63. });
  64. } else {
  65. sendUpdateUser();
  66. }
  67. }
  68. const apiTokens = ref([]);
  69. const apiTokensLoading = ref(false);
  70. const visibleTokenIds = ref(new Set());
  71. const createOpen = ref(false);
  72. const createName = ref('');
  73. const creating = ref(false);
  74. async function loadApiTokens() {
  75. apiTokensLoading.value = true;
  76. try {
  77. const msg = await HttpUtil.get('/panel/setting/apiTokens');
  78. if (msg?.success) apiTokens.value = Array.isArray(msg.obj) ? msg.obj : [];
  79. } finally {
  80. apiTokensLoading.value = false;
  81. }
  82. }
  83. function isTokenVisible(id) {
  84. return visibleTokenIds.value.has(id);
  85. }
  86. function toggleTokenVisibility(id) {
  87. const next = new Set(visibleTokenIds.value);
  88. if (next.has(id)) next.delete(id); else next.add(id);
  89. visibleTokenIds.value = next;
  90. }
  91. async function copyToken(token) {
  92. if (!token) return;
  93. try {
  94. await navigator.clipboard.writeText(token);
  95. message.success(t('copySuccess'));
  96. } catch (_e) {
  97. const ta = document.createElement('textarea');
  98. ta.value = token;
  99. document.body.appendChild(ta);
  100. ta.select();
  101. document.execCommand('copy');
  102. document.body.removeChild(ta);
  103. message.success(t('copySuccess'));
  104. }
  105. }
  106. function openCreateModal() {
  107. createName.value = '';
  108. createOpen.value = true;
  109. }
  110. async function confirmCreateToken() {
  111. const name = createName.value.trim();
  112. if (!name) {
  113. message.error(t('pages.settings.security.apiTokenNameRequired') || 'Name is required');
  114. return;
  115. }
  116. creating.value = true;
  117. try {
  118. const msg = await HttpUtil.post('/panel/setting/apiTokens/create', { name });
  119. if (msg?.success) {
  120. createOpen.value = false;
  121. await loadApiTokens();
  122. if (msg.obj?.id != null) {
  123. const next = new Set(visibleTokenIds.value);
  124. next.add(msg.obj.id);
  125. visibleTokenIds.value = next;
  126. }
  127. }
  128. } finally {
  129. creating.value = false;
  130. }
  131. }
  132. function confirmDeleteToken(row) {
  133. Modal.confirm({
  134. title: `${t('delete')} "${row.name}"?`,
  135. content: t('pages.settings.security.apiTokenDeleteWarning')
  136. || 'Any caller using this token will stop authenticating immediately.',
  137. okText: t('delete'),
  138. cancelText: t('cancel'),
  139. okType: 'danger',
  140. onOk: async () => {
  141. const msg = await HttpUtil.post(`/panel/setting/apiTokens/delete/${row.id}`);
  142. if (msg?.success) await loadApiTokens();
  143. },
  144. });
  145. }
  146. async function toggleTokenEnabled(row) {
  147. const target = !row.enabled;
  148. const msg = await HttpUtil.post(`/panel/setting/apiTokens/setEnabled/${row.id}`, { enabled: target });
  149. if (msg?.success) row.enabled = target;
  150. }
  151. function maskToken(token) {
  152. if (!token) return '';
  153. return '•'.repeat(Math.min(token.length, 24));
  154. }
  155. function formatTokenDate(ts) {
  156. if (!ts) return '';
  157. return new Date(ts * 1000).toLocaleString();
  158. }
  159. onMounted(loadApiTokens);
  160. function toggleTwoFactor() {
  161. // Switch read-only — the actual flip happens after the modal succeeds.
  162. if (!props.allSetting.twoFactorEnable) {
  163. const newToken = RandomUtil.randomBase32String();
  164. openTfa({
  165. title: t('pages.settings.security.twoFactorModalSetTitle'),
  166. token: newToken,
  167. type: 'set',
  168. onConfirm: (ok) => {
  169. if (ok) {
  170. message.success(t('pages.settings.security.twoFactorModalSetSuccess'));
  171. props.allSetting.twoFactorToken = newToken;
  172. }
  173. props.allSetting.twoFactorEnable = ok;
  174. },
  175. });
  176. } else {
  177. openTfa({
  178. title: t('pages.settings.security.twoFactorModalDeleteTitle'),
  179. description: t('pages.settings.security.twoFactorModalRemoveStep'),
  180. token: props.allSetting.twoFactorToken,
  181. type: 'confirm',
  182. onConfirm: (ok) => {
  183. if (!ok) return;
  184. message.success(t('pages.settings.security.twoFactorModalDeleteSuccess'));
  185. props.allSetting.twoFactorEnable = false;
  186. props.allSetting.twoFactorToken = '';
  187. },
  188. });
  189. }
  190. }
  191. </script>
  192. <template>
  193. <a-collapse default-active-key="1">
  194. <a-collapse-panel key="1" :header="t('pages.settings.security.admin')">
  195. <SettingListItem paddings="small">
  196. <template #title>{{ t('pages.settings.oldUsername') }}</template>
  197. <template #control>
  198. <a-input v-model:value="user.oldUsername" autocomplete="username" />
  199. </template>
  200. </SettingListItem>
  201. <SettingListItem paddings="small">
  202. <template #title>{{ t('pages.settings.currentPassword') }}</template>
  203. <template #control>
  204. <a-input-password v-model:value="user.oldPassword" autocomplete="current-password" />
  205. </template>
  206. </SettingListItem>
  207. <SettingListItem paddings="small">
  208. <template #title>{{ t('pages.settings.newUsername') }}</template>
  209. <template #control>
  210. <a-input v-model:value="user.newUsername" />
  211. </template>
  212. </SettingListItem>
  213. <SettingListItem paddings="small">
  214. <template #title>{{ t('pages.settings.newPassword') }}</template>
  215. <template #control>
  216. <a-input-password v-model:value="user.newPassword" autocomplete="new-password" />
  217. </template>
  218. </SettingListItem>
  219. <a-list-item>
  220. <a-space direction="horizontal" :style="{ padding: '0 20px' }">
  221. <a-button type="primary" :loading="updating" @click="updateUser">{{ t('confirm') }}</a-button>
  222. </a-space>
  223. </a-list-item>
  224. </a-collapse-panel>
  225. <a-collapse-panel key="2" :header="t('pages.settings.security.twoFactor')">
  226. <SettingListItem paddings="small">
  227. <template #title>{{ t('pages.settings.security.twoFactorEnable') }}</template>
  228. <template #description>{{ t('pages.settings.security.twoFactorEnableDesc') }}</template>
  229. <template #control>
  230. <a-switch :checked="allSetting.twoFactorEnable" @click="toggleTwoFactor" />
  231. </template>
  232. </SettingListItem>
  233. </a-collapse-panel>
  234. <a-collapse-panel key="3" :header="t('pages.nodes.apiToken')">
  235. <div class="api-token-section">
  236. <div class="api-token-header">
  237. <p class="api-token-hint">{{ t('pages.nodes.apiTokenHint') }}</p>
  238. <a-button type="primary" size="small" @click="openCreateModal">
  239. + {{ t('pages.settings.security.apiTokenNew') || 'New token' }}
  240. </a-button>
  241. </div>
  242. <a-spin :spinning="apiTokensLoading">
  243. <a-empty v-if="!apiTokens.length && !apiTokensLoading"
  244. :description="t('pages.settings.security.apiTokenEmpty') || 'No tokens yet'" />
  245. <div v-for="row in apiTokens" :key="row.id" class="api-token-row" :class="{ disabled: !row.enabled }">
  246. <div class="api-token-row-head">
  247. <div class="api-token-name-wrap">
  248. <span class="api-token-name">{{ row.name }}</span>
  249. <span class="api-token-created">{{ formatTokenDate(row.createdAt) }}</span>
  250. </div>
  251. <div class="api-token-actions">
  252. <a-switch size="small" :checked="row.enabled" @change="toggleTokenEnabled(row)" />
  253. <a-button size="small" danger type="text" @click="confirmDeleteToken(row)">
  254. {{ t('delete') }}
  255. </a-button>
  256. </div>
  257. </div>
  258. <div class="api-token-value-wrap">
  259. <code class="api-token-value">{{ isTokenVisible(row.id) ? row.token : maskToken(row.token) }}</code>
  260. <a-button size="small" @click="toggleTokenVisibility(row.id)">
  261. {{ isTokenVisible(row.id)
  262. ? (t('pages.settings.security.hide') || 'Hide')
  263. : (t('pages.settings.security.show') || 'Show') }}
  264. </a-button>
  265. <a-button size="small" @click="copyToken(row.token)">{{ t('copy') }}</a-button>
  266. </div>
  267. </div>
  268. </a-spin>
  269. </div>
  270. </a-collapse-panel>
  271. </a-collapse>
  272. <a-modal v-model:open="createOpen" :title="t('pages.settings.security.apiTokenNew') || 'New API token'"
  273. :confirm-loading="creating" :ok-text="t('confirm')" :cancel-text="t('cancel')" @ok="confirmCreateToken">
  274. <a-form layout="vertical">
  275. <a-form-item :label="t('pages.settings.security.apiTokenName') || 'Name'" required>
  276. <a-input v-model:value="createName" maxlength="64"
  277. :placeholder="t('pages.settings.security.apiTokenNamePlaceholder') || 'e.g. central-panel-a'"
  278. @keyup.enter="confirmCreateToken" />
  279. </a-form-item>
  280. </a-form>
  281. </a-modal>
  282. <TwoFactorModal v-model:open="tfa.open" :title="tfa.title" :description="tfa.description" :token="tfa.token"
  283. :type="tfa.type" @confirm="onTfaConfirm" />
  284. </template>
  285. <style scoped>
  286. .api-token-section {
  287. padding: 8px 20px 16px;
  288. display: flex;
  289. flex-direction: column;
  290. gap: 12px;
  291. }
  292. .api-token-header {
  293. display: flex;
  294. align-items: center;
  295. justify-content: space-between;
  296. gap: 12px;
  297. flex-wrap: wrap;
  298. }
  299. .api-token-hint {
  300. margin: 0;
  301. font-size: 12.5px;
  302. opacity: 0.7;
  303. flex: 1;
  304. min-width: 200px;
  305. }
  306. .api-token-row {
  307. border: 1px solid rgba(128, 128, 128, 0.18);
  308. border-radius: 8px;
  309. padding: 10px 12px;
  310. display: flex;
  311. flex-direction: column;
  312. gap: 8px;
  313. transition: opacity 0.15s;
  314. }
  315. .api-token-row.disabled {
  316. opacity: 0.55;
  317. }
  318. .api-token-row-head {
  319. display: flex;
  320. align-items: center;
  321. justify-content: space-between;
  322. gap: 8px;
  323. flex-wrap: wrap;
  324. }
  325. .api-token-name-wrap {
  326. display: flex;
  327. flex-direction: column;
  328. gap: 2px;
  329. }
  330. .api-token-name {
  331. font-weight: 600;
  332. font-size: 13.5px;
  333. }
  334. .api-token-created {
  335. font-size: 11px;
  336. opacity: 0.55;
  337. }
  338. .api-token-actions {
  339. display: flex;
  340. align-items: center;
  341. gap: 8px;
  342. }
  343. .api-token-value-wrap {
  344. display: flex;
  345. align-items: center;
  346. gap: 6px;
  347. flex-wrap: wrap;
  348. }
  349. .api-token-value {
  350. flex: 1;
  351. min-width: 0;
  352. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  353. font-size: 12.5px;
  354. padding: 4px 8px;
  355. background: rgba(128, 128, 128, 0.08);
  356. border-radius: 4px;
  357. word-break: break-all;
  358. }
  359. </style>