Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(frontend): migrate profile, 2FA setup, and dashboard sidebar to React (#19861)

Danny Xuc04a8eab99f0
diff --git a/frontend/package.json b/frontend/package.json
index 6af4c385cb..e8afbcda7c 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -72,6 +72,7 @@
"pinia": "3.0.4",
"pouchdb": "^9.0.0",
"pouchdb-find": "^9.0.0",
+ "qrcode.react": "^4.2.0",
"qs": "6.15.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 510e78b888..11f8024fa5 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -165,6 +165,9 @@ importers:
pouchdb-find:
specifier: ^9.0.0
version: 9.0.0
+ qrcode.react:
+ specifier: ^4.2.0
+ version: 4.2.0([email protected])
qs:
specifier: 6.15.0
version: 6.15.0
@@ -995,24 +998,28 @@ packages:
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@biomejs/[email protected]':
resolution: {integrity: sha512-kMLaI7OF5GN1Q8Doymjro1P8rVEoy7BKQALNz6fiR8IC1WKduoNyteBtJlHT7ASIL0Cx2jR6VUOBIbcB1B8pew==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@biomejs/[email protected]':
resolution: {integrity: sha512-C9s98IPDu7DYarjlZNuzJKTjVHN03RUnmHV5htvqsx6vEUXCDSJ59DNwjKVD5XYoSS4N+BYhq3RTBAL8X6svEg==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@biomejs/[email protected]':
resolution: {integrity: sha512-oHXmUFEoH8Lql1xfc3QkFLiC1hGR7qedv5eKNlC185or+o4/4HiaU7vYODAH3peRCfsuLr1g6v2fK9dFFOYdyw==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@biomejs/[email protected]':
resolution: {integrity: sha512-xzThn87Pf3YrOGTEODFGONmqXpTwUNxovQb72iaUOdcw8sBSY3+3WD8Hm9IhMYLnPi0n32s3L3NWU6+eSjfqFg==}
@@ -1914,66 +1921,79 @@ packages:
resolution: {integrity: sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==}
cpu: [loong64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==}
cpu: [loong64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==}
cpu: [ppc64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==}
@@ -2051,24 +2071,28 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-WZA0CHRL/SP1TRbA5mp9htsppSEkWuQ4KsSUumYQnyl8ZdT39ntwqmz4IUHGN6p4XdSlYfJwM4rRzZLShHsGAQ==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-qMFzxI2YlBOLW5PhblzuSWlWfwLHaneBE0xHzLrBgNtqN6mWfs+qYbhryGSXQjFYB1Dzf5w+LN5qbUTPhW7Y5g==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-5r1X2FKnCMUPlXTWRYpHdPYUY6a1Ar/t7P24OuiEdEOmms5lyqjDRvVY1yy9Rmioh+AunQ0rWiOTPE8F9A3v5g==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-MGFB5cVPvshR85MTJkEvqDUnuNoysrsRxd6vnk1Lf2tbiqNlXpHYZqkqOQalydienEWOHHFyyuTSYRsLfxFJ2Q==}
@@ -3686,24 +3710,28 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==}
@@ -4222,6 +4250,11 @@ packages:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==}
engines: {node: '>=0.6'}
@@ -9343,6 +9376,10 @@ snapshots:
+ dependencies:
+ react: 19.2.4
+
dependencies:
side-channel: 1.1.0
diff --git a/frontend/src/components/EmailInput.vue b/frontend/src/components/EmailInput.vue
deleted file mode 100644
index 5bd50047f2..0000000000
--- a/frontend/src/components/EmailInput.vue
+++ /dev/null
@@ -1,138 +0,0 @@
-<template>
- <div class="flex flex-col">
- <NInputGroup v-if="enforceDomain && !disabled">
- <NInput
- v-model:value="state.shortValue"
- :size="size"
- :disabled="disabled"
- :status="hasEmailError ? 'error' : undefined"
- />
- <NInputGroupLabel :size="size"> @ </NInputGroupLabel>
- <NSelect
- :size="size"
- v-model:value="state.domain"
- :options="domainSelectOptions"
- :disabled="disabled"
- />
- </NInputGroup>
- <NInput
- v-else
- v-model:value="state.value"
- :size="size"
- :disabled="disabled"
- :status="hasEmailError ? 'error' : undefined"
- />
- <span v-if="hasEmailError" class="text-error text-sm mt-1">
- {{ t("common.email-ascii-only") }}
- </span>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NInput, NInputGroup, NInputGroupLabel, NSelect } from "naive-ui";
-import { computed, reactive, watch, watchEffect } from "vue";
-import { useI18n } from "vue-i18n";
-import { useSettingV1Store } from "@/store";
-
-const { t } = useI18n();
-
-// WHATWG HTML spec email validation (lowercase only).
-// https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
-const emailRegex =
- /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
-
-const isValidEmail = (email: string): boolean => {
- return emailRegex.test(email);
-};
-
-interface LocalState {
- // The full email value.
- value: string;
- // The short value without the domain.
- shortValue: string;
- domain: string;
-}
-
-const props = withDefaults(
- defineProps<{
- size?: "small" | "medium" | "large";
- value?: string;
- disabled?: boolean;
- domain?: string;
- showDomain?: boolean;
- }>(),
- {
- size: "medium",
- value: "",
- disabled: false,
- showDomain: false,
- }
-);
-
-const emit = defineEmits<{
- (event: "update:value", value: string): void;
-}>();
-
-const state: LocalState = reactive({
- value: props.value,
- shortValue: props.value.split("@")[0],
- domain: props.value.split("@")[1],
-});
-const settingV1Store = useSettingV1Store();
-
-const enforceDomain = computed(() => {
- return (
- settingV1Store.workspaceProfile.enforceIdentityDomain || props.showDomain
- );
-});
-
-const domainSelectOptions = computed(() => {
- if (props.domain) {
- return [
- {
- label: props.domain,
- value: props.domain,
- },
- ];
- }
- const domains = settingV1Store.workspaceProfile.domains.filter(
- (domain) => domain && domain.trim() !== ""
- );
- return domains.map((domain) => {
- const value = domain.trim();
- return {
- label: value,
- value,
- };
- });
-});
-
-const hasEmailError = computed(() => {
- const email = enforceDomain.value
- ? `${state.shortValue}@${state.domain}`
- : state.value;
- if (!email || !email.includes("@")) {
- return false;
- }
- return !isValidEmail(email);
-});
-
-watchEffect(() => {
- if (domainSelectOptions.value.length > 0) {
- if (
- !domainSelectOptions.value.find((option) => option.value === state.domain)
- ) {
- state.domain = domainSelectOptions.value[0].value;
- }
- }
-});
-
-watch([() => state.value, () => state.shortValue, () => state.domain], () => {
- const email = enforceDomain.value
- ? state.shortValue
- ? `${state.shortValue}@${state.domain}`
- : ""
- : state.value;
- emit("update:value", email);
-});
-</script>
diff --git a/frontend/src/components/RecoveryCodesView.vue b/frontend/src/components/RecoveryCodesView.vue
deleted file mode 100644
index 47bedbd939..0000000000
--- a/frontend/src/components/RecoveryCodesView.vue
+++ /dev/null
@@ -1,73 +0,0 @@
-<template>
- <div class="w-full flex flex-col gap-y-4 my-8">
- <BBAttention
- type="info"
- :title="
- $t('two-factor.setup-steps.download-recovery-codes.keep-safe.self')
- "
- >
- <template #default>
- <div class="text-sm">
- <p>
- {{ $t("two-factor.setup-steps.download-recovery-codes.tips") }}
- </p>
- <p>
- {{
- $t(
- "two-factor.setup-steps.download-recovery-codes.keep-safe.description"
- )
- }}
- </p>
- </div>
- </template>
- </BBAttention>
- <div
- class="w-full mx-auto flex flex-col justify-start items-start"
- v-bind="$attrs"
- >
- <ul
- class="w-full grid grid-cols-2 list-disc list-inside mx-auto gap-4 gap-x-24 p-8 px-12 border rounded-md bg-gray-50"
- >
- <li v-for="code in props.recoveryCodes" :key="code">
- <code class="ml-2">{{ code }}</code>
- </li>
- </ul>
- </div>
- <div class="w-full mx-auto flex flex-row justify-end items-center">
- <NButton type="success" @click="downloadRecoveryCodes">
- <template #icon>
- <heroicons-outline:download class="w-5 h-auto text-white" />
- </template>
- {{ $t("common.download") }}
- </NButton>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NButton } from "naive-ui";
-import { BBAttention } from "@/bbkit";
-
-const props = withDefaults(
- defineProps<{
- recoveryCodes: string[];
- }>(),
- {
- recoveryCodes: () => [],
- }
-);
-
-const emit = defineEmits(["download"]);
-
-const downloadRecoveryCodes = () => {
- const content = props.recoveryCodes.join("\n");
- const blob = new Blob([content], { type: "text/plain" });
- const downloadLink = document.createElement("a");
- downloadLink.href = URL.createObjectURL(blob);
- downloadLink.download = "bytebase-recovery-codes.txt";
- document.body.appendChild(downloadLink);
- downloadLink.click();
- URL.revokeObjectURL(downloadLink.href);
- emit("download");
-};
-</script>
diff --git a/frontend/src/components/RegenerateRecoveryCodesView.vue b/frontend/src/components/RegenerateRecoveryCodesView.vue
deleted file mode 100644
index 8e4726ea47..0000000000
--- a/frontend/src/components/RegenerateRecoveryCodesView.vue
+++ /dev/null
@@ -1,89 +0,0 @@
-<template>
- <RecoveryCodesView
- :recovery-codes="props.recoveryCodes"
- @download="state.recoveryCodesDownloaded = true"
- />
- <div class="flex flex-row justify-between items-center mb-8">
- <NButton @click="emit('close')">
- {{ $t("common.cancel") }}
- </NButton>
- <NButton
- type="primary"
- :disabled="!state.recoveryCodesDownloaded"
- @click="regenerateRecoveryCodes"
- >
- {{ $t("two-factor.setup-steps.recovery-codes-saved") }}
- </NButton>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import { NButton } from "naive-ui";
-import { onMounted, reactive } from "vue";
-import { useI18n } from "vue-i18n";
-import { pushNotification, useCurrentUserV1, useUserStore } from "@/store";
-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
-import RecoveryCodesView from "./RecoveryCodesView.vue";
-
-interface LocalState {
- recoveryCodesDownloaded: boolean;
-}
-
-const props = withDefaults(
- defineProps<{
- recoveryCodes: string[];
- }>(),
- {
- recoveryCodes: () => [],
- }
-);
-
-const emit = defineEmits(["close"]);
-
-const { t } = useI18n();
-const userStore = useUserStore();
-const state = reactive<LocalState>({
- recoveryCodesDownloaded: false,
-});
-const currentUser = useCurrentUserV1();
-
-onMounted(() => {
- regenerateTempMfaSecret();
-});
-
-const regenerateTempMfaSecret = async () => {
- await userStore.updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.value.name,
- },
- updateMask: create(FieldMaskSchema, {
- paths: [],
- }),
- regenerateTempMfaSecret: true,
- })
- );
-};
-
-const regenerateRecoveryCodes = async () => {
- await userStore.updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.value.name,
- },
- updateMask: create(FieldMaskSchema, {
- paths: [],
- }),
- regenerateRecoveryCodes: true,
- })
- );
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("two-factor.messages.recovery-codes-regenerated"),
- });
- emit("close");
-};
-</script>
diff --git a/frontend/src/components/TwoFactorSecretModal.vue b/frontend/src/components/TwoFactorSecretModal.vue
deleted file mode 100644
index 17f4385bdd..0000000000
--- a/frontend/src/components/TwoFactorSecretModal.vue
+++ /dev/null
@@ -1,60 +0,0 @@
-<template>
- <BBModal
- :title="$t('two-factor.your-two-factor-secret.self')"
- :subtitle="$t('two-factor.your-two-factor-secret.description')"
- class="outline-solid outline-gray-200"
- @close="dismissModal"
- >
- <div class="w-auto mb-4 py-2">
- <code class="pr-4">{{ props.secret }}</code>
- </div>
- <div class="w-full flex items-center justify-end gap-x-3 pr-1 pb-1">
- <NButton @click="dismissModal">
- {{ $t("common.close") }}
- </NButton>
- <NButton v-if="isSupported" type="primary" @click="copySecret">
- {{ $t("common.copy") }}
- </NButton>
- </div>
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import { useClipboard } from "@vueuse/core";
-import { NButton } from "naive-ui";
-import { useI18n } from "vue-i18n";
-import { BBModal } from "@/bbkit";
-import { pushNotification } from "@/store";
-
-const props = defineProps({
- secret: {
- type: String,
- default: "",
- },
-});
-
-const emit = defineEmits<{
- (event: "close"): void;
-}>();
-
-const { t } = useI18n();
-
-const dismissModal = () => {
- emit("close");
-};
-
-const { copy: copyTextToClipboard, isSupported } = useClipboard({
- legacy: true,
-});
-
-const copySecret = () => {
- copyTextToClipboard(props.secret).then(() => {
- pushNotification({
- module: "bytebase",
- style: "INFO",
- title: t("two-factor.your-two-factor-secret.copy-succeed"),
- });
- });
- dismissModal();
-};
-</script>
diff --git a/frontend/src/react/ReactSidebarMount.vue b/frontend/src/react/ReactSidebarMount.vue
new file mode 100644
index 0000000000..c98c539523
--- /dev/null
+++ b/frontend/src/react/ReactSidebarMount.vue
@@ -0,0 +1,32 @@
+<template>
+ <div ref="container" class="h-full" />
+</template>
+
+<script lang="ts" setup>
+defineOptions({ inheritAttrs: false });
+
+import { onMounted, onUnmounted, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+
+const container = ref<HTMLElement>();
+// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
+let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any
+const { locale } = useI18n();
+
+async function render() {
+ if (!container.value) return;
+ const { mountSidebar, updateSidebarLocale } = await import("./mountSidebar");
+ if (!root) {
+ root = await mountSidebar(container.value, locale.value);
+ } else {
+ await updateSidebarLocale(root, locale.value);
+ }
+}
+
+onMounted(() => render());
+watch(locale, () => render());
+onUnmounted(() => {
+ root?.unmount();
+ root = null;
+});
+</script>
diff --git a/frontend/src/react/components/DashboardSidebar.tsx b/frontend/src/react/components/DashboardSidebar.tsx
new file mode 100644
index 0000000000..17e8d904d5
--- /dev/null
+++ b/frontend/src/react/components/DashboardSidebar.tsx
@@ -0,0 +1,520 @@
+import {
+ ChevronDown,
+ ChevronRight,
+ Database,
+ GalleryHorizontalEnd,
+ Home,
+ Layers,
+ Link,
+ Settings,
+ ShieldCheck,
+ SquareStack,
+ Users,
+ Workflow,
+} from "lucide-react";
+import type { ElementType } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import logoFull from "@/assets/logo-full.svg";
+import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/router";
+import {
+ DATABASE_ROUTE_DASHBOARD,
+ ENVIRONMENT_V1_ROUTE_DASHBOARD,
+ INSTANCE_ROUTE_DASHBOARD,
+ PROJECT_V1_ROUTE_DASHBOARD,
+ WORKSPACE_ROUTE_AUDIT_LOG,
+ WORKSPACE_ROUTE_CUSTOM_APPROVAL,
+ WORKSPACE_ROUTE_DATA_CLASSIFICATION,
+ WORKSPACE_ROUTE_GLOBAL_MASKING,
+ WORKSPACE_ROUTE_GROUPS,
+ WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
+ WORKSPACE_ROUTE_IM,
+ WORKSPACE_ROUTE_LANDING,
+ WORKSPACE_ROUTE_MCP,
+ WORKSPACE_ROUTE_MEMBERS,
+ WORKSPACE_ROUTE_RISK_CENTER,
+ WORKSPACE_ROUTE_ROLES,
+ WORKSPACE_ROUTE_SEMANTIC_TYPES,
+ WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
+ WORKSPACE_ROUTE_SQL_REVIEW,
+ WORKSPACE_ROUTE_USER_PROFILE,
+ WORKSPACE_ROUTE_USERS,
+ WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
+} from "@/router/dashboard/workspaceRoutes";
+import {
+ SETTING_ROUTE_WORKSPACE_GENERAL,
+ SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
+} from "@/router/dashboard/workspaceSetting";
+import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";
+import {
+ useActuatorV1Store,
+ useAppFeature,
+ useWorkspaceV1Store,
+} from "@/store";
+import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
+import { WorkspaceSwitcher } from "./WorkspaceSwitcher";
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+interface SidebarItem {
+ title?: string;
+ name?: string;
+ path?: string;
+ icon?: ElementType;
+ hide?: boolean;
+ type: "route" | "div" | "divider" | "link";
+ expand?: boolean;
+ children?: SidebarItem[];
+}
+
+// ---------------------------------------------------------------------------
+// Active-route detection
+// ---------------------------------------------------------------------------
+
+function getItemClass(item: SidebarItem, currentRouteName: string): string[] {
+ const isActive =
+ item.name === currentRouteName ||
+ currentRouteName.startsWith(`${item.name}.`);
+ if (isActive) {
+ return ["router-link-active", "bg-link-hover"];
+ }
+ if (
+ item.name === WORKSPACE_ROUTE_USERS &&
+ currentRouteName === WORKSPACE_ROUTE_USER_PROFILE
+ ) {
+ return ["router-link-active", "bg-link-hover"];
+ }
+ return [];
+}
+
+// ---------------------------------------------------------------------------
+// Sidebar item list builder
+// ---------------------------------------------------------------------------
+
+function useSidebarItems(): SidebarItem[] {
+ const { t } = useTranslation();
+ const isSaaSMode = useVueState(() => useActuatorV1Store().isSaaSMode);
+
+ return useMemo(
+ (): SidebarItem[] => [
+ {
+ title: t("common.home"),
+ icon: Home,
+ name: WORKSPACE_ROUTE_LANDING,
+ type: "route",
+ },
+ {
+ title: t("common.projects"),
+ icon: GalleryHorizontalEnd,
+ name: PROJECT_V1_ROUTE_DASHBOARD,
+ type: "route",
+ },
+ {
+ title: t("common.instances"),
+ icon: Layers,
+ name: INSTANCE_ROUTE_DASHBOARD,
+ type: "route",
+ },
+ {
+ title: t("common.databases"),
+ icon: Database,
+ name: DATABASE_ROUTE_DASHBOARD,
+ type: "route",
+ },
+ {
+ title: t("common.environments"),
+ icon: SquareStack,
+ name: ENVIRONMENT_V1_ROUTE_DASHBOARD,
+ type: "route",
+ },
+ {
+ type: "divider",
+ name: "",
+ },
+ {
+ title: t("settings.sidebar.iam-and-admin"),
+ icon: Users,
+ type: "div",
+ children: [
+ {
+ title: t("common.users"),
+ name: WORKSPACE_ROUTE_USERS,
+ type: "route",
+ hide: isSaaSMode,
+ },
+ {
+ title: t("settings.members.service-accounts"),
+ name: WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
+ type: "route",
+ hide: isSaaSMode,
+ },
+ {
+ title: t("settings.members.workload-identities"),
+ name: WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
+ type: "route",
+ hide: isSaaSMode,
+ },
+ {
+ title: t("settings.sidebar.members"),
+ name: WORKSPACE_ROUTE_MEMBERS,
+ type: "route",
+ },
+ {
+ title: t("settings.members.groups.self"),
+ name: WORKSPACE_ROUTE_GROUPS,
+ type: "route",
+ },
+ {
+ title: t("settings.sidebar.custom-roles"),
+ name: WORKSPACE_ROUTE_ROLES,
+ type: "route",
+ },
+ {
+ title: t("settings.sidebar.sso"),
+ name: WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
+ type: "route",
+ },
+ {
+ title: t("settings.sidebar.audit-log"),
+ name: WORKSPACE_ROUTE_AUDIT_LOG,
+ type: "route",
+ },
+ ],
+ },
+ {
+ title: "CI/CD",
+ icon: Workflow,
+ type: "div",
+ children: [
+ {
+ title: t("sql-review.title"),
+ name: WORKSPACE_ROUTE_SQL_REVIEW,
+ type: "route",
+ },
+ {
+ title: t("custom-approval.risk.self"),
+ name: WORKSPACE_ROUTE_RISK_CENTER,
+ type: "route",
+ },
+ {
+ title: t("custom-approval.self"),
+ name: WORKSPACE_ROUTE_CUSTOM_APPROVAL,
+ type: "route",
+ },
+ ],
+ },
+ {
+ title: t("settings.sidebar.data-access"),
+ icon: ShieldCheck,
+ type: "div",
+ children: [
+ {
+ title: t("settings.sensitive-data.semantic-types.self"),
+ name: WORKSPACE_ROUTE_SEMANTIC_TYPES,
+ type: "route",
+ },
+ {
+ title: t("settings.sidebar.data-classification"),
+ name: WORKSPACE_ROUTE_DATA_CLASSIFICATION,
+ type: "route",
+ },
+ {
+ title: t("settings.sidebar.global-masking"),
+ name: WORKSPACE_ROUTE_GLOBAL_MASKING,
+ type: "route",
+ },
+ ],
+ },
+ {
+ title: t("settings.sidebar.integration"),
+ icon: Link,
+ type: "div",
+ children: [
+ {
+ title: t("settings.sidebar.im-integration"),
+ name: WORKSPACE_ROUTE_IM,
+ type: "route",
+ },
+ {
+ title: t("settings.sidebar.mcp"),
+ name: WORKSPACE_ROUTE_MCP,
+ type: "route",
+ },
+ ],
+ },
+ {
+ title: t("common.settings"),
+ icon: Settings,
+ type: "div",
+ children: [
+ {
+ title: t("settings.sidebar.general"),
+ name: SETTING_ROUTE_WORKSPACE_GENERAL,
+ type: "route",
+ },
+ {
+ title: t("settings.sidebar.subscription"),
+ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
+ type: "route",
+ },
+ ],
+ },
+ ],
+ [t, isSaaSMode]
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Filter logic (mirrors CommonSidebar.vue filteredSidebarList)
+// ---------------------------------------------------------------------------
+
+function filterSidebarList(items: SidebarItem[]): SidebarItem[] {
+ return items
+ .map((item) => ({
+ ...item,
+ children: (item.children ?? []).filter((child) => !child.hide),
+ }))
+ .filter((item) => {
+ if (item.type === "divider") return true;
+ if (item.hide) return false;
+ if (item.children && item.children.length > 0) return true;
+ if (item.type === "div" || item.type === "link") return !!item.path;
+ return !!item.path || !!item.name;
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+const parentRouteClass =
+ "group flex items-center px-2 py-1.5 leading-normal font-medium rounded-md text-gray-700 outline-item text-sm!";
+const childRouteClass =
+ "group w-full flex items-center pl-9 pr-2 py-1 outline-item mb-0.5 rounded-md";
+
+export function DashboardSidebar() {
+ const rawItems = useSidebarItems();
+ const filteredItems = useMemo(() => filterSidebarList(rawItems), [rawItems]);
+
+ const currentRouteName = useVueState(
+ () => router.currentRoute.value.name?.toString() ?? ""
+ );
+ const databaseChangeMode = useVueState(
+ () => useAppFeature("bb.feature.database-change-mode").value
+ );
+ const customLogo = useVueState(
+ () => useWorkspaceV1Store().currentWorkspace?.logo ?? ""
+ );
+
+ // -- Expand / collapse state -----------------------------------------------
+ const [expandedSet, setExpandedSet] = useState<Set<string>>(new Set());
+ const manualToggledRef = useRef<Set<string>>(new Set());
+ const autoExpandedRef = useRef<Set<string>>(new Set());
+ const prevFilteredRef = useRef<SidebarItem[] | null>(null);
+
+ const expandForActiveRoute = useCallback(
+ (items: SidebarItem[]) => {
+ setExpandedSet((prev) => {
+ const next = new Set(prev);
+
+ // Remove previous auto-expansions
+ for (const key of autoExpandedRef.current) {
+ next.delete(key);
+ }
+ autoExpandedRef.current.clear();
+
+ for (let i = 0; i < items.length; i++) {
+ const item = items[i];
+ const key = `${i}`;
+ if (!item.children || item.children.length === 0) continue;
+ if (manualToggledRef.current.has(key)) continue;
+ if (item.expand) {
+ next.add(key);
+ continue;
+ }
+ const hasActiveChild = item.children.some(
+ (child) => getItemClass(child, currentRouteName).length > 0
+ );
+ if (hasActiveChild && !next.has(key)) {
+ next.add(key);
+ autoExpandedRef.current.add(key);
+ }
+ }
+
+ return next;
+ });
+ },
+ [currentRouteName]
+ );
+
+ // When the filtered item list identity changes, reset manual toggles
+ useEffect(() => {
+ if (prevFilteredRef.current !== filteredItems) {
+ prevFilteredRef.current = filteredItems;
+ manualToggledRef.current.clear();
+ autoExpandedRef.current.clear();
+ // Reset and re-expand
+ setExpandedSet(new Set());
+ }
+ }, [filteredItems]);
+
+ // Re-expand on route change or item list change
+ useEffect(() => {
+ expandForActiveRoute(filteredItems);
+ }, [currentRouteName, filteredItems, expandForActiveRoute]);
+
+ // -- Navigation ------------------------------------------------------------
+
+ const navigateToHome = useCallback(() => {
+ const target =
+ databaseChangeMode === DatabaseChangeMode.EDITOR
+ ? SQL_EDITOR_HOME_MODULE
+ : WORKSPACE_ROUTE_LANDING;
+ router.push({ name: target });
+ }, [databaseChangeMode]);
+
+ const onGroupClick = useCallback((item: SidebarItem, key: string) => {
+ if (item.children && item.children.length > 0) {
+ manualToggledRef.current.add(key);
+ autoExpandedRef.current.delete(key);
+ setExpandedSet((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
+ return next;
+ });
+ }
+ }, []);
+
+ const resolveHref = useCallback(
+ (name: string) => router.resolve({ name }).fullPath,
+ []
+ );
+
+ const handleRouteClick = useCallback((e: React.MouseEvent, name: string) => {
+ // Allow Ctrl/Meta+click to open in new tab naturally
+ if (e.ctrlKey || e.metaKey) return;
+ e.preventDefault();
+ router.push({ name });
+ }, []);
+
+ // -- Logo ------------------------------------------------------------------
+
+ const logoSrc = customLogo || logoFull;
+
+ // -- Render ----------------------------------------------------------------
+
+ const renderChildren = (children: SidebarItem[], parentIndex: number) => {
+ return (
+ <div className="flex flex-col gap-y-1 mt-1">
+ {children.map((child, j) => {
+ const classes = getItemClass(child, currentRouteName);
+ if (child.type === "route" && child.name) {
+ return (
+ <a
+ key={`${parentIndex}-${j}`}
+ href={resolveHref(child.name)}
+ className={`${childRouteClass} cursor-pointer no-underline text-inherit ${classes.join(" ")}`}
+ onClick={(e) => handleRouteClick(e, child.name!)}
+ >
+ {child.title}
+ </a>
+ );
+ }
+ if (child.type === "div") {
+ return (
+ <div
+ key={`${parentIndex}-${j}`}
+ className={`${childRouteClass} cursor-pointer ${classes.join(" ")}`}
+ onClick={() => onGroupClick(child, `${parentIndex}-${j}`)}
+ >
+ {child.title}
+ </div>
+ );
+ }
+ return null;
+ })}
+ </div>
+ );
+ };
+
+ const renderItem = (item: SidebarItem, index: number) => {
+ const key = `${index}`;
+
+ if (item.type === "divider") {
+ return (
+ <div
+ key={index}
+ className="border-t border-gray-300 my-2.5 mr-4 ml-2"
+ />
+ );
+ }
+
+ if (item.type === "route" && item.name) {
+ const classes = getItemClass(item, currentRouteName);
+ const Icon = item.icon;
+ return (
+ <a
+ key={index}
+ href={resolveHref(item.name)}
+ className={`${parentRouteClass} cursor-pointer no-underline text-inherit ${classes.join(" ")}`}
+ onClick={(e) => handleRouteClick(e, item.name!)}
+ >
+ {Icon && <Icon className="mr-2 w-5 h-5 text-gray-500" />}
+ {item.title}
+ </a>
+ );
+ }
+
+ if (item.type === "div") {
+ const classes = getItemClass(item, currentRouteName);
+ const Icon = item.icon;
+ const hasChildren = item.children && item.children.length > 0;
+ const isExpanded = expandedSet.has(key);
+ return (
+ <div key={index}>
+ <div
+ className={`${parentRouteClass} cursor-pointer ${classes.join(" ")}`}
+ onClick={() => onGroupClick(item, key)}
+ >
+ {Icon && <Icon className="mr-2 w-5 h-5 text-gray-500" />}
+ {item.title}
+ {hasChildren && (
+ <div className="ml-auto text-gray-500">
+ {isExpanded ? (
+ <ChevronDown className="w-4 h-4" />
+ ) : (
+ <ChevronRight className="w-4 h-4" />
+ )}
+ </div>
+ )}
+ </div>
+ {hasChildren && isExpanded && renderChildren(item.children!, index)}
+ </div>
+ );
+ }
+
+ return null;
+ };
+
+ return (
+ <nav className="flex-1 flex flex-col overflow-y-hidden border-r border-block-border">
+ <div
+ className="p-2 shrink-0 m-auto cursor-pointer"
+ onClick={navigateToHome}
+ >
+ <img src={logoSrc} alt="Bytebase" className="max-w-44" />
+ </div>
+ <WorkspaceSwitcher />
+ <div className="flex-1 overflow-y-auto px-2.5 flex flex-col gap-y-1">
+ {filteredItems.map((item, i) => renderItem(item, i))}
+ </div>
+ </nav>
+ );
+}
diff --git a/frontend/src/react/components/WorkspaceSwitcher.tsx b/frontend/src/react/components/WorkspaceSwitcher.tsx
new file mode 100644
index 0000000000..b3ffa81578
--- /dev/null
+++ b/frontend/src/react/components/WorkspaceSwitcher.tsx
@@ -0,0 +1,66 @@
+import { Building2, ChevronsUpDown } from "lucide-react";
+import { useCallback, useRef, useState } from "react";
+import { useClickOutside } from "@/react/hooks/useClickOutside";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useWorkspaceV1Store } from "@/store";
+
+export function WorkspaceSwitcher() {
+ const workspaceStore = useWorkspaceV1Store();
+
+ const workspaceList = useVueState(() => workspaceStore.workspaceList);
+ const currentWorkspace = useVueState(() => workspaceStore.currentWorkspace);
+ const currentWorkspaceName = currentWorkspace?.name ?? "";
+
+ const [open, setOpen] = useState(false);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ useClickOutside(
+ containerRef,
+ open,
+ useCallback(() => setOpen(false), [])
+ );
+
+ if (workspaceList.length <= 1) {
+ return null;
+ }
+
+ const onSwitch = (workspaceName: string) => {
+ if (workspaceName === currentWorkspaceName) return;
+ setOpen(false);
+ workspaceStore.switchWorkspace(workspaceName);
+ };
+
+ return (
+ <div ref={containerRef} className="relative px-2.5 pb-2">
+ <button
+ type="button"
+ className="w-full flex items-center gap-x-2 px-2 py-1.5 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-100 cursor-pointer"
+ onClick={() => setOpen(!open)}
+ >
+ <Building2 className="w-4 h-4 text-gray-500 shrink-0" />
+ <span className="truncate flex-1 text-left">
+ {currentWorkspace?.title}
+ </span>
+ <ChevronsUpDown className="w-3.5 h-3.5 text-gray-400 shrink-0" />
+ </button>
+ {open && (
+ <div className="absolute left-2.5 right-2.5 z-10 mt-1 bg-white border border-gray-200 rounded-md shadow-lg py-1">
+ {workspaceList.map((ws) => (
+ <button
+ key={ws.name}
+ type="button"
+ className={`w-full text-left px-3 py-1.5 text-sm hover:bg-gray-100 cursor-pointer ${
+ ws.name === currentWorkspaceName
+ ? "font-medium text-accent"
+ : "text-gray-700"
+ }`}
+ onClick={() => onSwitch(ws.name)}
+ >
+ {ws.title}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/ui/otp-input.tsx b/frontend/src/react/components/ui/otp-input.tsx
new file mode 100644
index 0000000000..2a1f68b635
--- /dev/null
+++ b/frontend/src/react/components/ui/otp-input.tsx
@@ -0,0 +1,91 @@
+import { useCallback, useRef } from "react";
+import { cn } from "@/react/lib/utils";
+
+interface OtpInputProps {
+ value: string[];
+ onChange: (value: string[]) => void;
+ onFinish?: (value: string[]) => void;
+ length?: number;
+ className?: string;
+}
+
+export function OtpInput({
+ value,
+ onChange,
+ onFinish,
+ length = 6,
+ className,
+}: OtpInputProps) {
+ const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
+
+ const handleChange = useCallback(
+ (index: number, digit: string) => {
+ if (digit && !/^\d$/.test(digit)) return;
+ const next = [...value];
+ while (next.length < length) next.push("");
+ next[index] = digit;
+ onChange(next);
+ if (digit && index < length - 1) {
+ inputRefs.current[index + 1]?.focus();
+ }
+ if (digit && next.filter((v) => v).length === length) {
+ onFinish?.(next);
+ }
+ },
+ [value, onChange, onFinish, length]
+ );
+
+ const handleKeyDown = useCallback(
+ (index: number, e: React.KeyboardEvent) => {
+ if (e.key === "Backspace" && !value[index] && index > 0) {
+ inputRefs.current[index - 1]?.focus();
+ }
+ },
+ [value]
+ );
+
+ const handlePaste = useCallback(
+ (e: React.ClipboardEvent) => {
+ e.preventDefault();
+ const pasted = e.clipboardData
+ .getData("text")
+ .replace(/\D/g, "")
+ .slice(0, length);
+ if (!pasted) return;
+ const next = [...value];
+ while (next.length < length) next.push("");
+ for (let i = 0; i < pasted.length; i++) {
+ next[i] = pasted[i];
+ }
+ onChange(next);
+ const focusIndex = Math.min(pasted.length, length - 1);
+ inputRefs.current[focusIndex]?.focus();
+ if (next.filter((v) => v).length === length) {
+ onFinish?.(next);
+ }
+ },
+ [value, onChange, onFinish, length]
+ );
+
+ return (
+ <div className={cn("flex gap-2", className)}>
+ {Array.from({ length }, (_, i) => (
+ <input
+ key={i}
+ ref={(el) => {
+ inputRefs.current[i] = el;
+ }}
+ type="text"
+ inputMode="numeric"
+ maxLength={1}
+ value={value[i] || ""}
+ onChange={(e) => handleChange(i, e.target.value)}
+ onKeyDown={(e) => handleKeyDown(i, e)}
+ onPaste={handlePaste}
+ className="w-10 h-12 text-center text-lg font-mono border border-control-border rounded-xs focus:outline-none focus:ring-2 focus:ring-accent focus:border-accent"
+ autoComplete="one-time-code"
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 4d5575142f..aa23317cf3 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -104,6 +104,7 @@
"deselect-all": "Deselect all",
"disable": "Disable",
"discard-changes": "Discard changes",
+ "download": "Download",
"edit": "Edit",
"email": "Email",
"empty": "Empty",
@@ -124,8 +125,10 @@
"from": "From",
"general": "General",
"groups": "Groups",
+ "home": "Home",
"id": "ID",
"instance": "Instance",
+ "instances": "Instances",
"is-required": "is required",
"items": "items",
"key": "Key",
@@ -149,7 +152,9 @@
"permissions": "Permissions",
"previous": "Previous",
"project": "Project",
+ "projects": "Projects",
"reason": "Reason",
+ "regenerate": "Regenerate",
"release": "Release",
"reorder": "Reorder",
"required-permission": "Required permissions",
@@ -168,6 +173,7 @@
"select-all": "Select all",
"selected": "selected",
"sensitive-placeholder": "Sensitive - write only",
+ "settings": "Settings",
"state": "State",
"statement": "Statement",
"status": "Status",
@@ -188,7 +194,8 @@
"view": "View",
"view-details": "View Details",
"warning": "Warning",
- "you": "you"
+ "you": "you",
+ "email-ascii-only": "Email addresses only support ASCII characters (letters, numbers, and symbols like . _ - +)."
},
"create-db": {
"cluster": "Cluster",
@@ -237,7 +244,8 @@
"risk-level-high": "High risk operations include destructive changes like DROP TABLE, TRUNCATE, or large-scale data modifications.",
"risk-level-low": "Low risk operations include SELECT queries and minor schema changes that are unlikely to cause issues.",
"risk-level-moderate": "Moderate risk operations include standard DDL changes like adding columns or indexes.",
- "risk-levels": "Risk Levels"
+ "risk-levels": "Risk Levels",
+ "self": "Risk Center"
},
"risk-rule": {
"risk": {
@@ -258,7 +266,8 @@
},
"rule": {
"first-match-wins": "Rules are evaluated in order. First matching rule applies."
- }
+ },
+ "self": "Custom Approval"
},
"database": {
"change-database": "Change Database",
@@ -391,10 +400,10 @@
"syncing": "Syncing ..."
},
"issue": {
- "labels": "Issue Labels",
"advanced-search": {
"filter": "Filter"
- }
+ },
+ "labels": "Issue Labels"
},
"label": {
"error": {
@@ -873,6 +882,7 @@
"title": "Title"
},
"n-members": "{{n}} members",
+ "self": "Groups",
"update-group": "Update Group",
"workspace-domain-required": "Please set a workspace domain first."
},
@@ -929,13 +939,16 @@
"workload-identity-tag-hint": "Leave empty to allow all tags"
},
"profile": {
+ "email": "Email",
"password": "Password",
"password-confirm": "Password Confirm",
"password-confirm-placeholder": "Confirm new password",
"password-hint": "Password should follow restriction setting",
"password-mismatch": "New password mismatch",
"phone": "Phone",
- "phone-tips": "Be sure to include the country code +1xxxxxx"
+ "phone-tips": "Be sure to include the country code +1xxxxxx",
+ "role": "Role",
+ "subscription": "(Upgrade to enable role management)"
},
"sensitive-data": {
"algorithms": {
@@ -1004,6 +1017,7 @@
"add-from-template": "Add from template",
"label": "Columns having the same semantic type will use the same masking algorithms.",
"select": "Select semantic type",
+ "self": "Semantic Types",
"table": {
"delete": "Delete this semantic type?",
"description": "Description",
@@ -1021,13 +1035,17 @@
"sidebar": {
"audit-log": "Audit Logs",
"custom-roles": "Custom Roles",
+ "data-access": "Data Access",
"data-classification": "Data Classification",
"general": "General",
"global-masking": "Global Masking",
+ "iam-and-admin": "IAM & Admin",
"im-integration": "IM",
+ "integration": "Integration",
"mcp": "MCP",
"members": "Members",
"members-and-groups": "Members & Groups",
+ "profile": "Profile",
"security-and-policy": "Security & Policy",
"sso": "SSO",
"subscription": "Subscription",
@@ -1261,9 +1279,55 @@
"title": "User count limit",
"upgrade": "Upgrade to get more user quota."
}
- }
+ },
+ "disabled-feature": "Disabled Feature"
},
"two-factor": {
- "enabled": "2FA Enabled"
+ "description": "Two-factor authentication provides an extra layer of security for member accounts. When signing in, you will be required to enter the security code generated by your Authenticator App.",
+ "disable": {
+ "description": "You are about to disable two-factor authentication for your account. You will no longer be required to enter the security code generated by your Authenticator App when signing in.",
+ "self": "Disable Two-factor authentication"
+ },
+ "enabled": "2FA Enabled",
+ "messages": {
+ "2fa-disabled": "Two-factor authentication is disabled.",
+ "2fa-enabled": "Two-factor authentication is enabled.",
+ "cannot-disable": "You cannot disable two-factor authentication because your admin requires it in the workspace.",
+ "recovery-codes-regenerated": "Recovery codes are regenerated."
+ },
+ "recovery-codes": {
+ "description": "Recovery codes can be used to access your account in the event you cannot receive two-factor authentication codes.",
+ "self": "Recovery codes"
+ },
+ "self": "Two-factor authentication",
+ "setup-steps": {
+ "download-recovery-codes": {
+ "keep-safe": {
+ "description": "These codes are the last resort for accessing your account in case you lose your two-factor authentication code. If you cannot find these codes, you will lose access to your account.",
+ "self": "Keep your recovery codes in a safe spot."
+ },
+ "self": "Download your recovery codes",
+ "tips": "Keep your recovery codes as safe as your password. We recommend saving them with a password manager such as Lastpass, 1Password, or Keeper."
+ },
+ "recovery-codes-saved": "I have saved my recovery codes",
+ "setup-auth-app": {
+ "description": "Use a phone app like Google Authenticator, Microsoft Authenticator, or Authy to get 2FA codes when prompted during sign-in.",
+ "expired-notice": "This setup session has expired. Please regenerate to continue.",
+ "regenerate": "Regenerate",
+ "scan-qr-code": {
+ "description": "Use an authenticator app from your phone to scan. If you are unable to scan, {{action}} instead.",
+ "enter-the-text": "enter the text",
+ "self": "Scan the QR code"
+ },
+ "self": "Setup authenticator app",
+ "time-remaining": "Time remaining: {{time}}",
+ "verify-code": "Verify the code from the app"
+ }
+ },
+ "your-two-factor-secret": {
+ "copy-succeed": "Secret copied to clipboard. Paste it into your app.",
+ "description": "Copy the code and enter it in your TOTP app manually.",
+ "self": "Your two-factor secret"
+ }
}
}
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 431d528a8c..e3be2c182f 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -104,10 +104,11 @@
"deselect-all": "Deselect all",
"disable": "Disable",
"discard-changes": "Descartar cambios",
+ "download": "Descargar",
"edit": "Editar",
"email": "Correo electrónico",
"empty": "Empty",
- "enable": "Enable",
+ "enable": "Habilitar",
"enabled": "Enabled",
"environment": "Entorno",
"environment-name": "Nombre del entorno",
@@ -124,8 +125,10 @@
"from": "Desde",
"general": "General",
"groups": "Grupos",
+ "home": "Inicio",
"id": "ID",
"instance": "Instancia",
+ "instances": "Instancias",
"is-required": "is required",
"items": "items",
"key": "Clave",
@@ -149,7 +152,9 @@
"permissions": "Permisos",
"previous": "Previous",
"project": "Proyecto",
+ "projects": "Proyectos",
"reason": "Reason",
+ "regenerate": "Regenerar",
"release": "Versión",
"reorder": "Reordenar",
"required-permission": "Permisos necesarios",
@@ -168,6 +173,7 @@
"select-all": "Seleccionar todo",
"selected": "selected",
"sensitive-placeholder": "Sensible - solo escritura",
+ "settings": "Configuraciones",
"state": "Estado",
"statement": "Declaración",
"status": "Estado",
@@ -188,7 +194,8 @@
"view": "Ver",
"view-details": "Ver Detalles",
"warning": "Advertencia",
- "you": "tu"
+ "you": "tu",
+ "email-ascii-only": "Las direcciones de correo solo admiten caracteres ASCII (letras, números y símbolos como . _ - +)."
},
"create-db": {
"cluster": "Clúster",
@@ -237,7 +244,8 @@
"risk-level-high": "Las operaciones de alto riesgo incluyen cambios destructivos como DROP TABLE, TRUNCATE o modificaciones de datos a gran escala.",
"risk-level-low": "Las operaciones de bajo riesgo incluyen consultas SELECT y cambios menores en el esquema que es poco probable que causen problemas.",
"risk-level-moderate": "Las operaciones de riesgo moderado incluyen cambios DDL estándar como agregar columnas o índices.",
- "risk-levels": "Niveles de Riesgo"
+ "risk-levels": "Niveles de Riesgo",
+ "self": "Centro de Riesgos"
},
"risk-rule": {
"risk": {
@@ -258,7 +266,8 @@
},
"rule": {
"first-match-wins": "Las reglas se evalúan en orden. Se aplica la primera regla coincidente."
- }
+ },
+ "self": "Aprobación personalizada"
},
"database": {
"change-database": "Modificar base de datos",
@@ -391,10 +400,10 @@
"syncing": "Sincronizando..."
},
"issue": {
- "labels": "Etiquetas de problema",
"advanced-search": {
"filter": "Filtrar"
- }
+ },
+ "labels": "Etiquetas de problema"
},
"label": {
"error": {
@@ -873,6 +882,7 @@
"title": "Título"
},
"n-members": "{{n}} miembros",
+ "self": "Grupos",
"update-group": "Grupo de actualización",
"workspace-domain-required": "Primero configure un dominio de espacio de trabajo."
},
@@ -929,13 +939,16 @@
"workload-identity-tag-hint": "Leave empty to allow all tags"
},
"profile": {
+ "email": "Correo electrónico",
"password": "Contraseña",
"password-confirm": "Confirmar contraseña",
"password-confirm-placeholder": "Confirmar nueva contraseña",
"password-hint": "La contraseña debe seguir la configuración de restricción",
"password-mismatch": "Nueva contraseña no coincide",
"phone": "Número de móvil",
- "phone-tips": "Asegúrese de incluir el código del país +1xxxxxx"
+ "phone-tips": "Asegúrese de incluir el código del país +1xxxxxx",
+ "role": "Rol",
+ "subscription": "(Actualice para habilitar la gestión de roles)"
},
"sensitive-data": {
"algorithms": {
@@ -1004,6 +1017,7 @@
"add-from-template": "Agregar desde plantilla",
"label": "Las columnas que tengan el mismo tipo semántico utilizarán los mismos algoritmos de enmascaramiento.",
"select": "Seleccionar tipo semántico",
+ "self": "Tipos Semánticos",
"table": {
"delete": "¿Eliminar este tipo semántico?",
"description": "Descripción",
@@ -1021,13 +1035,17 @@
"sidebar": {
"audit-log": "Registros de auditoría",
"custom-roles": "Roles personalizados",
+ "data-access": "Acceso a datos",
"data-classification": "Clasificación de datos",
"general": "General",
"global-masking": "Enmascaramiento Global",
+ "iam-and-admin": "IAM y administración",
"im-integration": "Integración de IM",
+ "integration": "Integración",
"mcp": "MCP",
"members": "Miembros",
"members-and-groups": "Miembros y grupos",
+ "profile": "Perfil",
"security-and-policy": "Seguridad y Política",
"sso": "SSO",
"subscription": "Suscripción",
@@ -1261,9 +1279,55 @@
"title": "Límite de conteo de usuarios",
"upgrade": "Actualizar para obtener más cuota de usuario."
}
- }
+ },
+ "disabled-feature": "Función deshabilitada"
},
"two-factor": {
- "enabled": "2FA habilitado"
+ "description": "La autenticación de dos factores proporciona una capa adicional de seguridad para las cuentas de los miembros. Al iniciar sesión, se te pedirá que ingreses el código de seguridad generado por tu aplicación de autenticación.",
+ "disable": {
+ "description": "Está a punto de desactivar la autenticación de dos factores para su cuenta. Ya no se le pedirá que ingrese el código de seguridad generado por su aplicación de autenticación cuando inicie sesión.",
+ "self": "Desactivar la autenticación de dos factores"
+ },
+ "enabled": "2FA habilitado",
+ "messages": {
+ "2fa-disabled": "La autenticación de dos factores está desactivada.",
+ "2fa-enabled": "La autenticación de dos factores está activada.",
+ "cannot-disable": "No puede desactivar la autenticación de dos factores porque su administrador la requiere en el espacio de trabajo.",
+ "recovery-codes-regenerated": "Los códigos de recuperación se han regenerado."
+ },
+ "recovery-codes": {
+ "description": "Los códigos de recuperación se pueden utilizar para acceder a su cuenta en caso de que no pueda recibir códigos de autenticación de dos factores.",
+ "self": "Códigos de recuperación"
+ },
+ "self": "Autenticación de dos factores",
+ "setup-steps": {
+ "download-recovery-codes": {
+ "keep-safe": {
+ "description": "Estos códigos son el último recurso para acceder a su cuenta en caso de que pierda su código de autenticación de dos factores. Si no puede encontrar estos códigos, perderá el acceso a su cuenta.",
+ "self": "Mantenga sus códigos de recuperación en un lugar seguro."
+ },
+ "self": "Descarga tus códigos de recuperación",
+ "tips": "Mantenga sus códigos de recuperación tan seguros como su contraseña. Recomendamos guardarlos con un administrador de contraseñas como Lastpass, 1Password o Keeper."
+ },
+ "recovery-codes-saved": "He guardado mis códigos de recuperación",
+ "setup-auth-app": {
+ "description": "Usa una aplicación de teléfono como Google Authenticator, Microsoft Authenticator o Authy para obtener códigos 2FA cuando se te solicite durante el inicio de sesión.",
+ "expired-notice": "Esta sesión de configuración ha expirado. Por favor, regenera para continuar.",
+ "regenerate": "Regenerar",
+ "scan-qr-code": {
+ "description": "Usa una aplicación de autenticación de tu teléfono para escanear. Si no puedes escanear, {{action}} en su lugar.",
+ "enter-the-text": "ingresa el texto",
+ "self": "Escanear el código QR"
+ },
+ "self": "Configurar la aplicación de autenticación",
+ "time-remaining": "Tiempo restante: {{time}}",
+ "verify-code": "Verifica el código de la aplicación"
+ }
+ },
+ "your-two-factor-secret": {
+ "copy-succeed": "Secreto copiado al portapapeles. Péguelo en su aplicación.",
+ "description": "Copie el código e ingréselo manualmente en su aplicación TOTP.",
+ "self": "Su secreto de dos factores"
+ }
}
}
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 7d419e908a..fb3b5a3366 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -104,10 +104,11 @@
"deselect-all": "Deselect all",
"disable": "Disable",
"discard-changes": "変更をキャンセルする",
+ "download": "ダウンロード",
"edit": "編集",
"email": "メールアドレス",
"empty": "Empty",
- "enable": "Enable",
+ "enable": "オンにする",
"enabled": "Enabled",
"environment": "環境",
"environment-name": "環境名",
@@ -124,8 +125,10 @@
"from": "開始",
"general": "全般",
"groups": "グループ",
+ "home": "ホームページ",
"id": "ID",
"instance": "インスタンス",
+ "instances": "インスタンス",
"is-required": "is required",
"items": "items",
"key": "キー",
@@ -149,7 +152,9 @@
"permissions": "権限",
"previous": "Previous",
"project": "プロジェクト",
+ "projects": "プロジェクト",
"reason": "Reason",
+ "regenerate": "再生する",
"release": "リリース",
"reorder": "並び替え",
"required-permission": "必要な権限",
@@ -168,6 +173,7 @@
"select-all": "すべて選択",
"selected": "selected",
"sensitive-placeholder": "機密データ - 書き込みのみ",
+ "settings": "設定",
"state": "ステート",
"statement": "ステートメント",
"status": "ステータス",
@@ -188,7 +194,8 @@
"view": "表示",
"view-details": "詳細を表示",
"warning": "警告する",
- "you": "あなた"
+ "you": "あなた",
+ "email-ascii-only": "メールアドレスは ASCII 文字のみ使用できます(英数字および . _ - + などの記号)。"
},
"create-db": {
"cluster": "集まる",
@@ -237,7 +244,8 @@
"risk-level-high": "高リスクの操作には、DROP TABLE、TRUNCATE、または大規模なデータ変更などの破壊的な変更が含まれます。",
"risk-level-low": "低リスクの操作には、SELECTクエリや問題を引き起こす可能性が低い軽微なスキーマ変更が含まれます。",
"risk-level-moderate": "中リスクの操作には、カラムやインデックスの追加などの標準的なDDL変更が含まれます。",
- "risk-levels": "リスクレベル"
+ "risk-levels": "リスクレベル",
+ "self": "リスクセンター"
},
"risk-rule": {
"risk": {
@@ -258,7 +266,8 @@
},
"rule": {
"first-match-wins": "ルールは順番に評価されます。最初に一致するルールが適用されます。"
- }
+ },
+ "self": "カスタム承認"
},
"database": {
"change-database": "データベースの変更",
@@ -391,10 +400,10 @@
"syncing": "同期中 ..."
},
"issue": {
- "labels": "イシューラベル",
"advanced-search": {
"filter": "フィルター"
- }
+ },
+ "labels": "イシューラベル"
},
"label": {
"error": {
@@ -873,6 +882,7 @@
"title": "タイトル"
},
"n-members": "{{n}} 人のメンバー",
+ "self": "グループ",
"update-group": "更新グループ",
"workspace-domain-required": "まずワークスペースドメインを設定してください。"
},
@@ -929,13 +939,16 @@
"workload-identity-tag-hint": "Leave empty to allow all tags"
},
"profile": {
+ "email": "メールアドレス",
"password": "パスワード",
"password-confirm": "パスワードの確認",
"password-confirm-placeholder": "新しいパスワードを確認します",
"password-hint": "パスワードは制限設定に従う必要があります",
"password-mismatch": "新しいパスワードが一致しません",
"phone": "電話番号",
- "phone-tips": "国コードを必ず含めてください +81xxxxxx"
+ "phone-tips": "国コードを必ず含めてください +81xxxxxx",
+ "role": "ロール",
+ "subscription": "(有料プランにアップグレードするとキャラクター管理が可能になります)"
},
"sensitive-data": {
"algorithms": {
@@ -1004,6 +1017,7 @@
"add-from-template": "テンプレートから追加",
"label": "同じセマンティック タイプの列は、同じマスキング アルゴリズムを使用します。",
"select": "セマンティックタイプの選択",
+ "self": "セマンティックタイプ",
"table": {
"delete": "このセマンティック タイプを削除しますか?",
"description": "説明",
@@ -1021,13 +1035,17 @@
"sidebar": {
"audit-log": "監査ログ",
"custom-roles": "カスタムロール",
+ "data-access": "データアクセス",
"data-classification": "データ分類",
"general": "全般",
"global-masking": "グローバルマスキング",
+ "iam-and-admin": "IAM と管理",
"im-integration": "IM",
+ "integration": "連携",
"mcp": "MCP",
"members": "メンバー",
"members-and-groups": "メンバーとグループ",
+ "profile": "プロフィール",
"security-and-policy": "セキュリティポリシー",
"sso": "SSO",
"subscription": "サブスクリプション",
@@ -1261,9 +1279,55 @@
"title": "ユーザー制限",
"upgrade": "アップグレード でユーザークォータをさらに取得します。"
}
- }
+ },
+ "disabled-feature": "無効な機能"
},
"two-factor": {
- "enabled": "二要素認証がオンになっています"
+ "description": "2 要素認証は、システム メンバーに追加のセキュリティ層を提供します。ログインするとき、ユーザーは認証アプリケーションによって生成されたセキュリティ コードを入力する必要があります。",
+ "disable": {
+ "description": "アカウントの 2 要素認証を無効にしようとしています。ログイン時に認証アプリによって生成されたセキュリティ コードを入力する必要がなくなりました。",
+ "self": "二要素認証を無効にする"
+ },
+ "enabled": "二要素認証がオンになっています",
+ "messages": {
+ "2fa-disabled": "二要素認証が正常に無効になりました",
+ "2fa-enabled": "二要素認証が正常にオンになりました",
+ "cannot-disable": "管理者は、すべてのユーザーに 2 要素認証を設定するよう要求します。 2 要素認証を無効にすることはできません。",
+ "recovery-codes-regenerated": "リカバリコードが再生成されました"
+ },
+ "recovery-codes": {
+ "description": "2 要素認証コードを受信できない場合は、リカバリ コードを使用してアカウントにアクセスできます。",
+ "self": "リカバリーコード"
+ },
+ "self": "二要素認証",
+ "setup-steps": {
+ "download-recovery-codes": {
+ "keep-safe": {
+ "description": "これらのコードは、2 要素認証コードを受信できない場合にアカウントにアクセスするために使用されます。これらのコードが見つからない場合は、アカウントにアクセスできなくなります。",
+ "self": "リカバリ コードは安全な場所に保管してください。"
+ },
+ "self": "リカバリーコードをダウンロード",
+ "tips": "リカバリ コードもパスワードと同じくらい安全に保管してください。 Lastpass、1Password、Keeper などのパスワード マネージャーに保存することをお勧めします。"
+ },
+ "recovery-codes-saved": "リカバリーコードを保存したことを確認してください",
+ "setup-auth-app": {
+ "description": "2 要素認証には、Google Authenticator、Microsoft Authenticator、Authy などのモバイル アプリを使用します。",
+ "expired-notice": "このセットアップセッションは期限切れになりました。続行するには再生成してください。",
+ "regenerate": "再生成",
+ "scan-qr-code": {
+ "description": "携帯電話の認証アプリを使用してスキャンします。スキャンできない場合は、{{action}} を実行できます。",
+ "enter-the-text": "テキストを入力してください",
+ "self": "QRコードをスキャンします"
+ },
+ "self": "認証アプリケーションをセットアップする",
+ "time-remaining": "残り時間: {{time}}",
+ "verify-code": "アプリケーションのコードを検証する"
+ }
+ },
+ "your-two-factor-secret": {
+ "copy-succeed": "正常にコピーされました。申請書に入力してください。",
+ "description": "キーをコピーし、アプリケーションに手動で入力します。",
+ "self": "二要素認証キー"
+ }
}
}
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index a5af883b96..34fe44466e 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -104,10 +104,11 @@
"deselect-all": "Deselect all",
"disable": "Disable",
"discard-changes": "Hủy thay đổi",
+ "download": "Tải xuống",
"edit": "Chỉnh sửa",
"email": "Email",
"empty": "Empty",
- "enable": "Enable",
+ "enable": "Bật",
"enabled": "Enabled",
"environment": "Môi trường",
"environment-name": "Tên môi trường",
@@ -124,8 +125,10 @@
"from": "Từ",
"general": "Chung",
"groups": "Nhóm",
+ "home": "Trang chủ",
"id": "ID",
"instance": "Phiên bản",
+ "instances": "Phiên bản",
"is-required": "is required",
"items": "items",
"key": "Khóa",
@@ -149,7 +152,9 @@
"permissions": "Quyền",
"previous": "Previous",
"project": "Dự án",
+ "projects": "Dự án",
"reason": "Reason",
+ "regenerate": "Tạo lại",
"release": "Phiên bản",
"reorder": "Sắp xếp lại",
"required-permission": "Quyền hạn cần thiết",
@@ -168,6 +173,7 @@
"select-all": "Chọn tất cả",
"selected": "selected",
"sensitive-placeholder": "Nhạy cảm - Chỉ ghi",
+ "settings": "Cài đặt",
"state": "Trạng thái",
"statement": "Câu lệnh",
"status": "Trạng thái",
@@ -188,7 +194,8 @@
"view": "Xem",
"view-details": "Xem Chi tiết",
"warning": "Cảnh báo",
- "you": "bạn"
+ "you": "bạn",
+ "email-ascii-only": "Địa chỉ email chỉ hỗ trợ ký tự ASCII (chữ cái, số và ký hiệu như . _ - +)."
},
"create-db": {
"cluster": "Cụm",
@@ -237,7 +244,8 @@
"risk-level-high": "Các thao tác rủi ro cao bao gồm các thay đổi phá hủy như DROP TABLE, TRUNCATE hoặc sửa đổi dữ liệu quy mô lớn.",
"risk-level-low": "Các thao tác rủi ro thấp bao gồm các truy vấn SELECT và các thay đổi schema nhỏ không có khả năng gây ra sự cố.",
"risk-level-moderate": "Các thao tác rủi ro trung bình bao gồm các thay đổi DDL tiêu chuẩn như thêm cột hoặc chỉ mục.",
- "risk-levels": "Các Mức độ Rủi ro"
+ "risk-levels": "Các Mức độ Rủi ro",
+ "self": "Trung tâm Rủi ro"
},
"risk-rule": {
"risk": {
@@ -258,7 +266,8 @@
},
"rule": {
"first-match-wins": "Các quy tắc được đánh giá theo thứ tự. Quy tắc phù hợp đầu tiên sẽ được áp dụng."
- }
+ },
+ "self": "Phê duyệt tùy chỉnh"
},
"database": {
"change-database": "Thay đổi cơ sở dữ liệu",
@@ -391,10 +400,10 @@
"syncing": "Đang đồng bộ hóa ..."
},
"issue": {
- "labels": "Nhãn vấn đề",
"advanced-search": {
"filter": "Bộ lọc"
- }
+ },
+ "labels": "Nhãn vấn đề"
},
"label": {
"error": {
@@ -873,6 +882,7 @@
"title": "Tiêu đề"
},
"n-members": "{{n}} thành viên",
+ "self": "Nhóm",
"update-group": "Cập nhật nhóm",
"workspace-domain-required": "Vui lòng thiết lập tên miền không gian làm việc trước."
},
@@ -929,13 +939,16 @@
"workload-identity-tag-hint": "Leave empty to allow all tags"
},
"profile": {
+ "email": "Email",
"password": "Mật khẩu",
"password-confirm": "Xác nhận mật khẩu",
"password-confirm-placeholder": "Xác nhận mật khẩu mới",
"password-hint": "Mật khẩu phải theo quy định hạn chế",
"password-mismatch": "Mật khẩu mới không khớp",
"phone": "Điện thoại",
- "phone-tips": "Nhớ bao gồm mã quốc gia +1xxxxxx"
+ "phone-tips": "Nhớ bao gồm mã quốc gia +1xxxxxx",
+ "role": "Vai trò",
+ "subscription": "(Nâng cấp để kích hoạt quản lý vai trò)"
},
"sensitive-data": {
"algorithms": {
@@ -1004,6 +1017,7 @@
"add-from-template": "Thêm từ mẫu",
"label": "Các cột có cùng loại ngữ nghĩa sẽ sử dụng cùng một thuật toán che.",
"select": "Chọn loại ngữ nghĩa",
+ "self": "Loại ngữ nghĩa",
"table": {
"delete": "Xóa loại ngữ nghĩa này?",
"description": "Mô tả",
@@ -1021,13 +1035,17 @@
"sidebar": {
"audit-log": "Nhật ký kiểm tra",
"custom-roles": "Vai trò tùy chỉnh",
+ "data-access": "Truy cập dữ liệu",
"data-classification": "Phân loại dữ liệu",
"general": "Chung",
"global-masking": "Che giấu toàn cục",
+ "iam-and-admin": "IAM & Quản trị",
"im-integration": "Tích hợp",
+ "integration": "Tích hợp",
"mcp": "MCP",
"members": "Thành viên",
"members-and-groups": "Thành viên & Nhóm",
+ "profile": "Hồ sơ",
"security-and-policy": "Bảo mật & Chính sách",
"sso": "SSO",
"subscription": "Gói đăng ký",
@@ -1261,9 +1279,55 @@
"title": "Giới hạn số lượng người dùng",
"upgrade": "Nâng cấp để có thêm hạn ngạch người dùng."
}
- }
+ },
+ "disabled-feature": "Tính năng bị vô hiệu hóa"
},
"two-factor": {
- "enabled": "Đã bật 2FA"
+ "description": "Xác thực hai yếu tố cung cấp một lớp bảo mật bổ sung cho các tài khoản thành viên. Khi đăng nhập, bạn sẽ được yêu cầu nhập mã bảo mật do Ứng dụng xác thực của bạn tạo.",
+ "disable": {
+ "description": "Bạn sắp tắt xác thực hai yếu tố cho tài khoản của mình. Bạn sẽ không còn phải nhập mã bảo mật do Ứng dụng xác thực của bạn tạo khi đăng nhập.",
+ "self": "Tắt xác thực hai yếu tố"
+ },
+ "enabled": "Đã bật 2FA",
+ "messages": {
+ "2fa-disabled": "Xác thực hai yếu tố bị tắt.",
+ "2fa-enabled": "Xác thực hai yếu tố được bật.",
+ "cannot-disable": "Bạn không thể tắt xác thực hai yếu tố vì quản trị viên của bạn yêu cầu nó trong không gian làm việc.",
+ "recovery-codes-regenerated": "Mã khôi phục được tạo lại."
+ },
+ "recovery-codes": {
+ "description": "Mã khôi phục có thể được sử dụng để truy cập tài khoản của bạn trong trường hợp bạn không thể nhận mã xác thực hai yếu tố.",
+ "self": "Mã khôi phục"
+ },
+ "self": "Xác thực hai yếu tố",
+ "setup-steps": {
+ "download-recovery-codes": {
+ "keep-safe": {
+ "description": "Các mã này là phương sách cuối cùng để truy cập tài khoản của bạn trong trường hợp bạn mất mã xác thực hai yếu tố. Nếu bạn không thể tìm thấy các mã này, bạn sẽ mất quyền truy cập vào tài khoản của mình.",
+ "self": "Giữ mã khôi phục của bạn ở một nơi an toàn."
+ },
+ "self": "Tải xuống mã khôi phục của bạn",
+ "tips": "Giữ mã khôi phục của bạn an toàn như mật khẩu của bạn. Chúng tôi khuyên bạn nên lưu chúng bằng trình quản lý mật khẩu như Lastpass, 1Password hoặc Keeper."
+ },
+ "recovery-codes-saved": "Tôi đã lưu mã khôi phục của mình",
+ "setup-auth-app": {
+ "description": "Sử dụng một ứng dụng điện thoại như Google Authenticator, Microsoft Authenticator hoặc Authy để nhận mã 2FA khi được nhắc trong quá trình đăng nhập.",
+ "expired-notice": "Phiên thiết lập này đã hết hạn. Vui lòng tạo lại để tiếp tục.",
+ "regenerate": "Tạo lại",
+ "scan-qr-code": {
+ "description": "Sử dụng ứng dụng xác thực từ điện thoại của bạn để quét. Nếu bạn không thể quét, {{action}} thay thế.",
+ "enter-the-text": "nhập văn bản",
+ "self": "Quét mã QR"
+ },
+ "self": "Thiết lập ứng dụng xác thực",
+ "time-remaining": "Thời gian còn lại: {{time}}",
+ "verify-code": "Xác minh mã từ ứng dụng"
+ }
+ },
+ "your-two-factor-secret": {
+ "copy-succeed": "Bí mật đã được sao chép vào khay nhớ tạm. Dán nó vào ứng dụng của bạn.",
+ "description": "Sao chép mã và nhập nó vào ứng dụng TOTP của bạn theo cách thủ công.",
+ "self": "Bí mật hai yếu tố của bạn"
+ }
}
}
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index fb8a383770..d7a379366b 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -104,10 +104,11 @@
"deselect-all": "Deselect all",
"disable": "禁用",
"discard-changes": "取消修改",
+ "download": "下载",
"edit": "编辑",
"email": "邮箱",
"empty": "Empty",
- "enable": "Enable",
+ "enable": "开启",
"enabled": "开启",
"environment": "环境",
"environment-name": "环境名",
@@ -124,8 +125,10 @@
"from": "从",
"general": "通用",
"groups": "分组",
+ "home": "主页",
"id": "ID",
"instance": "实例",
+ "instances": "实例",
"is-required": "is required",
"items": "items",
"key": "键",
@@ -149,7 +152,9 @@
"permissions": "权限",
"previous": "上一步",
"project": "项目",
+ "projects": "项目",
"reason": "Reason",
+ "regenerate": "重新生成",
"release": "版本",
"reorder": "排序",
"required-permission": "所需权限",
@@ -168,6 +173,7 @@
"select-all": "全选",
"selected": "selected",
"sensitive-placeholder": "敏感数据 - 仅写入",
+ "settings": "设置",
"state": "状态",
"statement": "语句",
"status": "状态",
@@ -188,7 +194,8 @@
"view": "查看",
"view-details": "查看详情",
"warning": "警告",
- "you": "您"
+ "you": "您",
+ "email-ascii-only": "邮箱地址仅支持 ASCII 字符(英文字母、数字及 . _ - + 等符号)。"
},
"create-db": {
"cluster": "集群",
@@ -237,7 +244,8 @@
"risk-level-high": "高风险操作包括破坏性变更,如 DROP TABLE、TRUNCATE 或大规模数据修改。",
"risk-level-low": "低风险操作包括 SELECT 查询和不太可能造成问题的小型模式变更。",
"risk-level-moderate": "中风险操作包括标准 DDL 变更,如添加列或索引。",
- "risk-levels": "风险等级"
+ "risk-levels": "风险等级",
+ "self": "风险中心"
},
"risk-rule": {
"risk": {
@@ -258,7 +266,8 @@
},
"rule": {
"first-match-wins": "规则按顺序评估,第一个匹配的规则将被应用。"
- }
+ },
+ "self": "自定义审批"
},
"database": {
"change-database": "变更数据库",
@@ -391,10 +400,10 @@
"syncing": "同步中 ..."
},
"issue": {
- "labels": "工单标签",
"advanced-search": {
"filter": "过滤"
- }
+ },
+ "labels": "工单标签"
},
"label": {
"error": {
@@ -873,6 +882,7 @@
"title": "名称"
},
"n-members": "{{n}} 位成员",
+ "self": "群组",
"update-group": "更新组",
"workspace-domain-required": "请先设置工作空间的域名。"
},
@@ -929,13 +939,16 @@
"workload-identity-tag-hint": "留空则允许所有标签"
},
"profile": {
+ "email": "邮箱",
"password": "密码",
"password-confirm": "确认密码",
"password-confirm-placeholder": "确认新密码",
"password-hint": "密码应遵循限制设置",
"password-mismatch": "新密码不匹配",
"phone": "手机号",
- "phone-tips": "请包含国家代码前缀 +86xxxxxx"
+ "phone-tips": "请包含国家代码前缀 +86xxxxxx",
+ "role": "角色",
+ "subscription": "(升级到付费方案来解锁角色管理)"
},
"sensitive-data": {
"algorithms": {
@@ -1004,6 +1017,7 @@
"add-from-template": "从模板添加",
"label": "具有相同语义类型的列会使用相同的脱敏算法。",
"select": "选择语义类型",
+ "self": "语义类型",
"table": {
"delete": "删除这个语义类型?",
"description": "描述",
@@ -1021,13 +1035,17 @@
"sidebar": {
"audit-log": "审计日志",
"custom-roles": "自定义角色",
+ "data-access": "数据访问",
"data-classification": "数据分类",
"general": "通用",
"global-masking": "全局数据脱敏",
+ "iam-and-admin": "IAM & 管理",
"im-integration": "IM",
+ "integration": "集成",
"mcp": "MCP",
"members": "成员",
"members-and-groups": "成员和群组",
+ "profile": "个人信息",
"security-and-policy": "安全 & 策略",
"sso": "SSO",
"subscription": "订阅",
@@ -1261,9 +1279,55 @@
"title": "用户数量限制",
"upgrade": "升级来获取更多用户额度。"
}
- }
+ },
+ "disabled-feature": "禁用功能"
},
"two-factor": {
- "enabled": "双重认证已开启"
+ "description": "双重认证为系统成员提供了一个额外的安全层。在登录时,用户需要输入由认证器应用程序生成的安全代码。",
+ "disable": {
+ "description": "您即将禁用您账户的双重认证。您在登录时将不再需要输入由您的 Authenticator 应用程序生成的安全代码。",
+ "self": "禁用双重认证"
+ },
+ "enabled": "双重认证已开启",
+ "messages": {
+ "2fa-disabled": "双重认证禁用成功",
+ "2fa-enabled": "双重认证开启成功",
+ "cannot-disable": "您的管理员要求所有用户配置双重认证。您无法禁用双重认证。",
+ "recovery-codes-regenerated": "恢复码已经重新生成"
+ },
+ "recovery-codes": {
+ "description": "恢复码可以在您无法收到双重认证代码的情况下用于访问您的账户。",
+ "self": "恢复码"
+ },
+ "self": "双重认证",
+ "setup-steps": {
+ "download-recovery-codes": {
+ "keep-safe": {
+ "description": "这些代码是在您无法收到双重认证代码的情况下访问您的账户。如果您找不到这些代码,您将失去对您账户的访问。",
+ "self": "把您的恢复码放在一个安全的地方。"
+ },
+ "self": "下载恢复码",
+ "tips": "保持您的恢复码和您的密码一样安全。建议将它们保存在一个密码管理器中,如 Lastpass、1Password 或 Keeper。"
+ },
+ "recovery-codes-saved": "确定已经保存了我的恢复码",
+ "setup-auth-app": {
+ "description": "使用像 Google Authenticator、Microsoft Authenticator 或 Authy 这样的手机应用程序来进行双重认证操作。",
+ "expired-notice": "此设置会话已过期。请重新生成以继续。",
+ "regenerate": "重新生成",
+ "scan-qr-code": {
+ "description": "使用您手机中的认证器应用程序进行扫描。如果您无法扫描,可以{{action}}。",
+ "enter-the-text": "输入文本",
+ "self": "扫描二维码"
+ },
+ "self": "设置认证器应用程序",
+ "time-remaining": "剩余时间:{{time}}",
+ "verify-code": "验证应用程序的代码"
+ }
+ },
+ "your-two-factor-secret": {
+ "copy-succeed": "复制成功。请输入到您的应用程序中。",
+ "description": "复制密钥并在您的应用程序中手动输入。",
+ "self": "双重认证密钥"
+ }
}
}
diff --git a/frontend/src/react/mountSidebar.ts b/frontend/src/react/mountSidebar.ts
new file mode 100644
index 0000000000..3d624ce2b2
--- /dev/null
+++ b/frontend/src/react/mountSidebar.ts
@@ -0,0 +1,84 @@
+// Use import.meta.glob so vue-tsc does not follow the import into React .tsx files.
+const sidebarLoader = import.meta.glob("./components/DashboardSidebar.tsx");
+
+// biome-ignore lint/suspicious/noExplicitAny: React types conflict with Vue JSX in vue-tsc
+type ReactDeps = any; // eslint-disable-line @typescript-eslint/no-explicit-any
+
+let cachedDeps: ReactDeps | null = null;
+
+async function loadCoreDeps() {
+ if (cachedDeps) return cachedDeps;
+ const [
+ { createElement, StrictMode },
+ { createRoot },
+ { I18nextProvider },
+ i18nModule,
+ ] = await Promise.all([
+ import("react"),
+ import("react-dom/client"),
+ import("react-i18next"),
+ import("@/react/i18n"),
+ ]);
+ await i18nModule.i18nReady;
+ cachedDeps = {
+ createElement,
+ StrictMode,
+ createRoot,
+ I18nextProvider,
+ i18n: i18nModule.default,
+ };
+ return cachedDeps;
+}
+
+async function loadSidebar() {
+ const loader = sidebarLoader["./components/DashboardSidebar.tsx"];
+ if (!loader) throw new Error("DashboardSidebar not found");
+ const mod = (await loader()) as Record<string, unknown>;
+ return mod.DashboardSidebar as ReactDeps;
+}
+
+export async function mountSidebar(container: HTMLElement, locale: string) {
+ const [deps, DashboardSidebar] = await Promise.all([
+ loadCoreDeps(),
+ loadSidebar(),
+ ]);
+ if (deps.i18n.language !== locale) {
+ await deps.i18n.changeLanguage(locale);
+ }
+ const tree = deps.createElement(
+ deps.StrictMode,
+ null,
+ deps.createElement(
+ deps.I18nextProvider,
+ { i18n: deps.i18n },
+ deps.createElement(DashboardSidebar)
+ )
+ );
+ const root = deps.createRoot(container);
+ root.render(tree);
+ return root;
+}
+
+export async function updateSidebarLocale(
+ // biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
+ root: any, // eslint-disable-line @typescript-eslint/no-explicit-any
+ locale: string
+) {
+ const [deps, DashboardSidebar] = await Promise.all([
+ loadCoreDeps(),
+ loadSidebar(),
+ ]);
+ if (deps.i18n.language !== locale) {
+ await deps.i18n.changeLanguage(locale);
+ }
+ const tree = deps.createElement(
+ deps.StrictMode,
+ null,
+ deps.createElement(
+ deps.I18nextProvider,
+ { i18n: deps.i18n },
+ deps.createElement(DashboardSidebar)
+ )
+ );
+ root.render(tree);
+}
diff --git a/frontend/src/react/pages/settings/ProfilePage.tsx b/frontend/src/react/pages/settings/ProfilePage.tsx
new file mode 100644
index 0000000000..cce0bd9bc1
--- /dev/null
+++ b/frontend/src/react/pages/settings/ProfilePage.tsx
@@ -0,0 +1 @@
+export { ProfilePage } from "./profile/ProfilePage";
diff --git a/frontend/src/react/pages/settings/TwoFactorSetupPage.tsx b/frontend/src/react/pages/settings/TwoFactorSetupPage.tsx
new file mode 100644
index 0000000000..af8a36cbef
--- /dev/null
+++ b/frontend/src/react/pages/settings/TwoFactorSetupPage.tsx
@@ -0,0 +1 @@
+export { TwoFactorSetupPage } from "./two-factor/TwoFactorSetupPage";
diff --git a/frontend/src/react/pages/settings/profile/EmailInput.tsx b/frontend/src/react/pages/settings/profile/EmailInput.tsx
new file mode 100644
index 0000000000..a1dbe55a1f
--- /dev/null
+++ b/frontend/src/react/pages/settings/profile/EmailInput.tsx
@@ -0,0 +1,179 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Input } from "@/react/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/react/components/ui/select";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useSettingV1Store } from "@/store";
+
+// WHATWG HTML spec email validation (lowercase only).
+const emailRegex =
+ /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
+
+function isValidEmail(email: string): boolean {
+ return emailRegex.test(email);
+}
+
+interface EmailInputProps {
+ value: string;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+ domain?: string;
+ showDomain?: boolean;
+}
+
+export function EmailInput({
+ value,
+ onChange,
+ disabled = false,
+ domain: domainProp,
+ showDomain = false,
+}: EmailInputProps) {
+ const { t } = useTranslation();
+ const settingV1Store = useSettingV1Store();
+
+ const enforceIdentityDomain = useVueState(
+ () => settingV1Store.workspaceProfile.enforceIdentityDomain
+ );
+ const workspaceDomains = useVueState(
+ () => settingV1Store.workspaceProfile.domains
+ );
+
+ const enforceDomain = enforceIdentityDomain || showDomain;
+
+ const domainSelectOptions = useMemo(() => {
+ if (domainProp) {
+ return [{ label: domainProp, value: domainProp }];
+ }
+ return workspaceDomains
+ .filter((d) => d && d.trim() !== "")
+ .map((d) => {
+ const v = d.trim();
+ return { label: v, value: v };
+ });
+ }, [domainProp, workspaceDomains]);
+
+ const [localPart, setLocalPart] = useState(() => value.split("@")[0] ?? "");
+ const [selectedDomain, setSelectedDomain] = useState(
+ () => value.split("@")[1] ?? ""
+ );
+ const [fullValue, setFullValue] = useState(value);
+
+ // Emit the composed email whenever parts change
+ const emitEmail = useCallback(
+ (lp: string, dom: string, full: string) => {
+ if (enforceDomain) {
+ onChange(lp ? `${lp}@${dom}` : "");
+ } else {
+ onChange(full);
+ }
+ },
+ [enforceDomain, onChange]
+ );
+
+ // Ensure selectedDomain is valid when options change, and sync parent
+ useEffect(() => {
+ if (domainSelectOptions.length > 0) {
+ if (!domainSelectOptions.find((o) => o.value === selectedDomain)) {
+ const newDomain = domainSelectOptions[0].value;
+ setSelectedDomain(newDomain);
+ emitEmail(localPart, newDomain, fullValue);
+ }
+ }
+ }, [domainSelectOptions, selectedDomain, localPart, fullValue, emitEmail]);
+
+ const handleLocalPartChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const v = e.target.value;
+ setLocalPart(v);
+ emitEmail(v, selectedDomain, fullValue);
+ },
+ [selectedDomain, fullValue, emitEmail]
+ );
+
+ const handleDomainChange = useCallback(
+ (val: string | null) => {
+ if (val === null) return;
+ setSelectedDomain(val);
+ emitEmail(localPart, val, fullValue);
+ },
+ [localPart, fullValue, emitEmail]
+ );
+
+ const handleFullChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const v = e.target.value;
+ setFullValue(v);
+ emitEmail(localPart, selectedDomain, v);
+ },
+ [localPart, selectedDomain, emitEmail]
+ );
+
+ const composedEmail = enforceDomain
+ ? `${localPart}@${selectedDomain}`
+ : fullValue;
+ const hasEmailError =
+ composedEmail && composedEmail.includes("@")
+ ? !isValidEmail(composedEmail)
+ : false;
+
+ if (enforceDomain && !disabled) {
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center gap-0">
+ <Input
+ value={localPart}
+ onChange={handleLocalPartChange}
+ disabled={disabled}
+ className={
+ hasEmailError
+ ? "rounded-r-none border-error focus:ring-error"
+ : "rounded-r-none"
+ }
+ />
+ <span className="flex items-center px-2 h-9 border-y border-control-border bg-control-bg text-sm text-control-light">
+ @
+ </span>
+ <Select value={selectedDomain} onValueChange={handleDomainChange}>
+ <SelectTrigger className="rounded-l-none border-l-0 min-w-28">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {domainSelectOptions.map((opt) => (
+ <SelectItem key={opt.value} value={opt.value}>
+ {opt.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ {hasEmailError && (
+ <span className="text-error text-sm mt-1">
+ {t("common.email-ascii-only")}
+ </span>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col">
+ <Input
+ value={fullValue}
+ onChange={handleFullChange}
+ disabled={disabled}
+ className={hasEmailError ? "border-error focus:ring-error" : ""}
+ />
+ {hasEmailError && (
+ <span className="text-error text-sm mt-1">
+ {t("common.email-ascii-only")}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/settings/profile/ProfilePage.tsx b/frontend/src/react/pages/settings/profile/ProfilePage.tsx
new file mode 100644
index 0000000000..21640d3241
--- /dev/null
+++ b/frontend/src/react/pages/settings/profile/ProfilePage.tsx
@@ -0,0 +1,707 @@
+import { create } from "@bufbuild/protobuf";
+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import type { ConnectError } from "@connectrpc/connect";
+import { cloneDeep, isEqual } from "lodash-es";
+import { Ellipsis, ShieldAlert } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { t as vueT } from "@/plugins/i18n";
+import { FeatureBadge } from "@/react/components/FeatureBadge";
+import { Button } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { Input } from "@/react/components/ui/input";
+import { useClickOutside } from "@/react/hooks/useClickOutside";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ getAvatarColor,
+ getInitials,
+} from "@/react/pages/settings/shared/UserAvatar";
+import { RegenerateRecoveryCodesView } from "@/react/pages/settings/two-factor/RegenerateRecoveryCodesView";
+import { router } from "@/router";
+import {
+ WORKSPACE_ROUTE_404,
+ WORKSPACE_ROUTE_USER_PROFILE,
+} from "@/router/dashboard/workspaceRoutes";
+import {
+ SETTING_ROUTE_PROFILE_TWO_FACTOR,
+ SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
+} from "@/router/dashboard/workspaceSetting";
+import {
+ hasFeature,
+ pushNotification,
+ useActuatorV1Store,
+ useAuthStore,
+ useCurrentUserV1,
+ useSettingV1Store,
+ useUserStore,
+ useWorkspaceV1Store,
+} from "@/store";
+import {
+ AccountType,
+ ALL_USERS_USER_EMAIL,
+ getAccountTypeByEmail,
+ isValidUserName,
+ unknownUser,
+} from "@/types";
+import { State } from "@/types/proto-es/v1/common_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import type { User } from "@/types/proto-es/v1/user_service_pb";
+import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import {
+ displayRoleTitle,
+ hasWorkspacePermissionV2,
+ setDocumentTitle,
+ sortRoles,
+} from "@/utils";
+import { migrateUserStorage } from "@/utils/storage-migrate";
+import { EmailInput } from "./EmailInput";
+import { getPasswordErrors, UserPasswordSection } from "./UserPasswordSection";
+
+interface ProfilePageProps {
+ principalEmail?: string;
+}
+
+export function ProfilePage({ principalEmail }: ProfilePageProps) {
+ const { t } = useTranslation();
+
+ const authStore = useAuthStore();
+ const settingV1Store = useSettingV1Store();
+ const userStore = useUserStore();
+ const workspaceStore = useWorkspaceV1Store();
+ const actuatorStore = useActuatorV1Store();
+
+ // --- Reactive Vue state ---
+ const currentUser = useVueState(() => useCurrentUserV1().value);
+
+ const user = useVueState(() => {
+ if (principalEmail) {
+ return userStore.getUserByIdentifier(principalEmail) ?? unknownUser();
+ }
+ return useCurrentUserV1().value;
+ });
+
+ const userRoles = useVueState(() => [
+ ...workspaceStore.getWorkspaceRolesByName(user.name),
+ ]);
+
+ const passwordRestriction = useVueState(
+ () => settingV1Store.workspaceProfile.passwordRestriction
+ );
+
+ const isSaaSMode = useVueState(() => actuatorStore.isSaaSMode);
+
+ const has2FAFeature = useVueState(() =>
+ hasFeature(PlanFeature.FEATURE_TWO_FA)
+ );
+
+ const require2fa = useVueState(
+ () => settingV1Store.workspaceProfile.require2fa
+ );
+
+ const tempRecoveryCodes = useVueState(() => currentUser.tempRecoveryCodes);
+
+ // --- Derived values ---
+ const isSelf = currentUser.name === user.name;
+
+ const allowGet = isSelf || hasWorkspacePermissionV2("bb.users.get");
+
+ const allowEdit = useMemo(() => {
+ if (
+ user.email === ALL_USERS_USER_EMAIL ||
+ getAccountTypeByEmail(user.email) !== AccountType.USER
+ ) {
+ return false;
+ }
+ if (user.state !== State.ACTIVE) {
+ return false;
+ }
+ if (isSelf) {
+ return true;
+ }
+ return !isSaaSMode && hasWorkspacePermissionV2("bb.users.update");
+ }, [user, isSelf, isSaaSMode]);
+
+ const allowEditEmail = hasWorkspacePermissionV2("bb.users.updateEmail");
+
+ const isMFAEnabled = user.mfaEnabled;
+ const showRegenerateRecoveryCodes =
+ isMFAEnabled && user.name === currentUser.name;
+
+ // --- Local state ---
+ const [editing, setEditing] = useState(false);
+ const [editingUser, setEditingUser] = useState<User | undefined>(undefined);
+ const [passwordConfirm, setPasswordConfirm] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [showFeatureModal, setShowFeatureModal] = useState(false);
+ const [showDisable2FAConfirm, setShowDisable2FAConfirm] = useState(false);
+ const [showRegenerateView, setShowRegenerateView] = useState(false);
+ const [showEllipsisMenu, setShowEllipsisMenu] = useState(false);
+
+ const editNameRef = useRef<HTMLInputElement>(null);
+ const ellipsisMenuRef = useRef<HTMLDivElement>(null);
+ useClickOutside(ellipsisMenuRef, showEllipsisMenu, () =>
+ setShowEllipsisMenu(false)
+ );
+
+ // --- Password validity ---
+ const passwordErrors = useMemo(() => {
+ if (!editingUser) return { hasHint: false, hasMismatch: false };
+ return getPasswordErrors(
+ editingUser.password ?? "",
+ passwordConfirm,
+ passwordRestriction
+ );
+ }, [editingUser, passwordConfirm, passwordRestriction]);
+
+ const allowSaveEdit = useMemo(() => {
+ if (!editingUser) return false;
+ return (
+ !isEqual(user, editingUser) &&
+ !passwordErrors.hasHint &&
+ !passwordErrors.hasMismatch
+ );
+ }, [user, editingUser, passwordErrors]);
+
+ // --- Effects ---
+
+ // On mount: validate account type and fetch user
+ useEffect(() => {
+ if (principalEmail) {
+ const userType = getAccountTypeByEmail(principalEmail);
+ if (userType !== AccountType.USER) {
+ router.replace({ name: WORKSPACE_ROUTE_404 });
+ return;
+ }
+ (async () => {
+ const fetched = await userStore.getOrFetchUserByIdentifier({
+ identifier: principalEmail,
+ fallback: false,
+ });
+ if (!isValidUserName(fetched.name)) {
+ router.replace({ name: WORKSPACE_ROUTE_404 });
+ }
+ })();
+ }
+ }, [principalEmail]);
+
+ // Keyboard shortcuts — refs are assigned after callbacks are defined below
+ const saveEditRef = useRef<() => void>(() => {});
+ const cancelEditRef = useRef<() => void>(() => {});
+
+ // Route change guard
+ useEffect(() => {
+ const shouldGuard = editing && allowSaveEdit;
+
+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {
+ if (shouldGuard) {
+ e.preventDefault();
+ e.returnValue = "";
+ }
+ };
+ window.addEventListener("beforeunload", handleBeforeUnload);
+
+ const removeGuard = router.beforeEach((_to, _from, next) => {
+ if (shouldGuard) {
+ if (!window.confirm(vueT("common.leave-without-saving"))) {
+ next(false);
+ return;
+ }
+ }
+ next();
+ });
+
+ return () => {
+ window.removeEventListener("beforeunload", handleBeforeUnload);
+ removeGuard();
+ };
+ }, [editing, allowSaveEdit]);
+
+ // Document title
+ useEffect(() => {
+ setDocumentTitle(user.title);
+ }, [user.title]);
+
+ // --- Actions ---
+ const editUser = useCallback(() => {
+ setEditingUser(cloneDeep(user));
+ setEditing(true);
+ setPasswordConfirm("");
+ setTimeout(() => editNameRef.current?.focus(), 0);
+ }, [user]);
+
+ const cancelEdit = useCallback(() => {
+ setEditingUser(undefined);
+ setEditing(false);
+ }, []);
+
+ const updateEditingUser = useCallback(
+ <K extends keyof User>(field: K, value: User[K]) => {
+ setEditingUser((prev) => {
+ if (!prev) return prev;
+ return { ...prev, [field]: value };
+ });
+ },
+ []
+ );
+
+ const saveEdit = useCallback(async () => {
+ if (!editingUser) return;
+
+ const emailChanged = editingUser.email !== user.email;
+ const updateMaskPaths: string[] = [];
+
+ if (editingUser.title !== user.title) {
+ updateMaskPaths.push("title");
+ }
+ if (editingUser.phone !== user.phone) {
+ updateMaskPaths.push("phone");
+ }
+ if (editingUser.password !== "") {
+ updateMaskPaths.push("password");
+ }
+
+ setSaving(true);
+ try {
+ if (emailChanged) {
+ const oldEmail = user.email;
+ const updatedUser = await userStore.updateEmail(
+ oldEmail,
+ editingUser.email
+ );
+ migrateUserStorage(oldEmail, editingUser.email);
+ if (isSelf) {
+ authStore.updateCurrentUserNameForEmailChange(updatedUser.name);
+ }
+ }
+
+ if (updateMaskPaths.length > 0) {
+ await userStore.updateUser(
+ create(UpdateUserRequestSchema, {
+ user: editingUser,
+ updateMask: create(FieldMaskSchema, {
+ paths: updateMaskPaths,
+ }),
+ regenerateRecoveryCodes: false,
+ regenerateTempMfaSecret: false,
+ })
+ );
+ }
+
+ if (emailChanged || updateMaskPaths.length > 0) {
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ }
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: (error as ConnectError).message || "Failed to update user",
+ });
+ return;
+ } finally {
+ setSaving(false);
+ }
+
+ setEditingUser(undefined);
+ setEditing(false);
+
+ if (emailChanged && principalEmail) {
+ router.replace({
+ name: WORKSPACE_ROUTE_USER_PROFILE,
+ params: { principalEmail: editingUser.email },
+ });
+ }
+ }, [editingUser, user, isSelf, principalEmail, t]);
+
+ // Assign refs for keyboard shortcuts now that callbacks are defined
+ saveEditRef.current = saveEdit;
+ cancelEditRef.current = cancelEdit;
+
+ useEffect(() => {
+ const handler = (e: KeyboardEvent) => {
+ if (e.isComposing) return;
+ if (editing) {
+ if (e.code === "Escape") {
+ cancelEditRef.current();
+ } else if (e.code === "Enter" && e.metaKey) {
+ if (allowSaveEdit) {
+ saveEditRef.current();
+ }
+ }
+ }
+ };
+ document.addEventListener("keydown", handler);
+ return () => document.removeEventListener("keydown", handler);
+ }, [editing, allowSaveEdit]);
+
+ const enable2FA = useCallback(() => {
+ if (!has2FAFeature) {
+ setShowFeatureModal(true);
+ return;
+ }
+ router.push({ name: SETTING_ROUTE_PROFILE_TWO_FACTOR });
+ }, [has2FAFeature]);
+
+ const disable2FA = useCallback(() => {
+ if (require2fa && !hasWorkspacePermissionV2("bb.policies.update")) {
+ pushNotification({
+ module: "bytebase",
+ style: "WARN",
+ title: t("two-factor.messages.cannot-disable"),
+ });
+ } else {
+ setShowDisable2FAConfirm(true);
+ }
+ }, [require2fa, t]);
+
+ const handleDisable2FA = useCallback(async () => {
+ await userStore.updateUser(
+ create(UpdateUserRequestSchema, {
+ user: {
+ name: user.name,
+ mfaEnabled: false,
+ },
+ updateMask: create(FieldMaskSchema, {
+ paths: ["mfa_enabled"],
+ }),
+ })
+ );
+ setShowDisable2FAConfirm(false);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("two-factor.messages.2fa-disabled"),
+ });
+ }, [user.name, t]);
+
+ // --- No permission ---
+ if (!allowGet) {
+ return (
+ <main className="pt-4 flex-1 h-full relative pb-8 focus:outline-hidden xl:order-last px-4">
+ <div
+ role="alert"
+ className="relative w-full rounded-xs border px-4 py-3 text-sm flex gap-x-3 items-start border-error/30 bg-error/5 text-error"
+ >
+ <ShieldAlert className="h-5 w-5 shrink-0 mt-0.5" />
+ <div className="flex flex-col gap-2">
+ <h5 className="font-medium leading-tight">
+ {t("common.missing-required-permission")}
+ </h5>
+ <div>
+ {t("common.required-permission")}
+ <ul className="list-disc pl-4">
+ <li>bb.users.get</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </main>
+ );
+ }
+
+ // --- Main render ---
+ return (
+ <main
+ className="pt-4 flex-1 h-full relative pb-8 focus:outline-hidden xl:order-last"
+ tabIndex={0}
+ >
+ <div>
+ {/* Profile header */}
+ <div>
+ <div className="-mt-4 h-32 bg-accent lg:h-48" />
+ <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
+ <div className="-mt-20 sm:flex sm:items-end sm:gap-x-5">
+ {/* Large avatar */}
+ <div
+ className="rounded-full flex items-center justify-center text-white font-bold shrink-0 h-32 w-32 text-4xl ring-4 ring-white"
+ style={{ backgroundColor: getAvatarColor(user.title) }}
+ >
+ {getInitials(user.title)}
+ </div>
+ <div className="mt-6 sm:flex-1 sm:min-w-0 sm:flex sm:items-center sm:justify-end sm:gap-x-6 sm:pb-1">
+ <div className="mt-6 flex flex-row justify-stretch gap-x-2">
+ {allowEdit && (
+ <>
+ {editing ? (
+ <>
+ <Button
+ variant="ghost"
+ disabled={saving}
+ onClick={cancelEdit}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={!allowSaveEdit || saving}
+ onClick={saveEdit}
+ >
+ {t("common.save")}
+ </Button>
+ </>
+ ) : (
+ <Button variant="outline" onClick={editUser}>
+ {t("common.edit")}
+ </Button>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ <div className="block mt-6 min-w-0 flex-1">
+ {editing ? (
+ <Input
+ ref={editNameRef}
+ autoComplete="off"
+ value={editingUser?.title ?? ""}
+ className="w-64 text-lg"
+ onChange={(e) => updateEditingUser("title", e.target.value)}
+ />
+ ) : (
+ <h1 className="pb-1.5 text-2xl font-bold text-main truncate">
+ {user.title}
+ </h1>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Description list */}
+ <div className="mt-6 mb-2 max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
+ <dl className="grid grid-cols-1 gap-x-4 gap-y-8 sm:grid-cols-3">
+ {/* Role */}
+ <div className="sm:col-span-1">
+ <dt className="text-sm font-medium text-control-light">
+ {t("settings.profile.role")}
+ </dt>
+ <dd className="mt-1 text-sm text-main">
+ <div className="flex flex-row justify-start items-start flex-wrap gap-2">
+ {sortRoles(userRoles).map((role) => (
+ <span
+ key={role}
+ className="inline-flex items-center rounded-full px-3 py-0.5 text-sm font-medium bg-control-bg text-control"
+ >
+ {displayRoleTitle(role)}
+ </span>
+ ))}
+ </div>
+ {!hasFeature(PlanFeature.FEATURE_IAM) && (
+ <a
+ href="#"
+ className="normal-link"
+ onClick={(e) => {
+ e.preventDefault();
+ router.push({
+ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
+ });
+ }}
+ >
+ {t("settings.profile.subscription")}
+ </a>
+ )}
+ </dd>
+ </div>
+
+ {/* Email */}
+ <div className="sm:col-span-1">
+ <dt className="text-sm font-medium text-control-light">
+ {t("settings.profile.email")}
+ </dt>
+ <dd className="mt-1 text-sm text-main">
+ {editing && allowEditEmail ? (
+ <EmailInput
+ value={editingUser?.email ?? ""}
+ onChange={(val) => updateEditingUser("email", val)}
+ />
+ ) : (
+ user.email
+ )}
+ </dd>
+ </div>
+
+ {/* Phone */}
+ {getAccountTypeByEmail(user.email) === AccountType.USER && (
+ <div className="sm:col-span-1">
+ <dt className="text-sm font-medium text-control-light">
+ {t("settings.profile.phone")}
+ </dt>
+ <dd className="mt-1 text-sm text-main">
+ {editing ? (
+ <Input
+ value={editingUser?.phone ?? ""}
+ placeholder={t("settings.profile.phone-tips")}
+ autoComplete="off"
+ type="tel"
+ onChange={(e) =>
+ updateEditingUser("phone", e.target.value)
+ }
+ />
+ ) : (
+ user.phone
+ )}
+ </dd>
+ </div>
+ )}
+
+ {/* Password */}
+ {editing && editingUser && (
+ <div className="col-span-2">
+ <UserPasswordSection
+ password={editingUser.password ?? ""}
+ passwordConfirm={passwordConfirm}
+ onPasswordChange={(val) => updateEditingUser("password", val)}
+ onPasswordConfirmChange={setPasswordConfirm}
+ passwordRestriction={passwordRestriction}
+ />
+ </div>
+ )}
+ </dl>
+ </div>
+
+ {/* 2FA section */}
+ {allowEdit && (
+ <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 border-t mt-16 pt-8 pb-4">
+ <div className="w-full flex flex-row justify-between items-center">
+ <span className="text-lg font-medium flex flex-row justify-start items-center">
+ {t("two-factor.self")}
+ <FeatureBadge
+ feature={PlanFeature.FEATURE_TWO_FA}
+ className="ml-2 text-accent inline-flex"
+ />
+ </span>
+ <div className="flex gap-x-2">
+ {isMFAEnabled && (
+ <Button variant="destructive" onClick={disable2FA}>
+ {t("common.disable")}
+ </Button>
+ )}
+ {user.email === currentUser.email && (
+ <Button variant="outline" onClick={enable2FA}>
+ {isMFAEnabled ? t("common.edit") : t("common.enable")}
+ </Button>
+ )}
+ </div>
+ </div>
+ <p className="mt-4 text-sm text-gray-500">
+ {t("two-factor.description")}{" "}
+ <a
+ href="https://docs.bytebase.com/administration/2fa?source=console"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-accent hover:underline ml-1"
+ >
+ {t("common.learn-more")}
+ </a>
+ </p>
+
+ {showRegenerateRecoveryCodes && (
+ <>
+ <div className="w-full flex flex-row justify-between items-center mt-8">
+ <span className="text-lg font-medium">
+ {t("two-factor.recovery-codes.self")}
+ </span>
+ {!showRegenerateView && (
+ <div className="relative" ref={ellipsisMenuRef}>
+ <button
+ type="button"
+ className="p-1 rounded hover:bg-control-bg"
+ onClick={() => setShowEllipsisMenu((v) => !v)}
+ >
+ <Ellipsis className="w-8" />
+ </button>
+ {showEllipsisMenu && (
+ <div className="absolute right-0 mt-1 z-10 bg-white border border-control-border rounded shadow-md py-1 min-w-36">
+ <button
+ type="button"
+ className="w-full text-left px-3 py-1.5 text-sm hover:bg-control-bg"
+ onClick={() => {
+ setShowRegenerateView(true);
+ setShowEllipsisMenu(false);
+ }}
+ >
+ {t("common.regenerate")}
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ <p className="mt-4 text-sm text-gray-500">
+ {t("two-factor.recovery-codes.description")}
+ </p>
+ {showRegenerateView && (
+ <RegenerateRecoveryCodesView
+ recoveryCodes={tempRecoveryCodes}
+ onClose={() => setShowRegenerateView(false)}
+ />
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Feature modal for 2FA */}
+ <Dialog open={showFeatureModal} onOpenChange={setShowFeatureModal}>
+ <DialogContent className="p-6">
+ <DialogTitle>{t("subscription.disabled-feature")}</DialogTitle>
+ <DialogDescription className="mt-2">
+ {t("subscription.require-subscription", {
+ requiredPlan: t("subscription.plan.enterprise.title"),
+ })}
+ </DialogDescription>
+ <div className="mt-4 flex justify-end gap-x-2">
+ <Button
+ variant="outline"
+ onClick={() => setShowFeatureModal(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ onClick={() => {
+ setShowFeatureModal(false);
+ router.push({
+ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
+ });
+ }}
+ >
+ {t("common.learn-more")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ {/* Disable 2FA confirm dialog */}
+ <Dialog
+ open={showDisable2FAConfirm}
+ onOpenChange={setShowDisable2FAConfirm}
+ >
+ <DialogContent className="p-6">
+ <DialogTitle>{t("two-factor.disable.self")}</DialogTitle>
+ <DialogDescription className="mt-2">
+ {t("two-factor.disable.description")}
+ </DialogDescription>
+ <div className="mt-4 flex justify-end gap-x-2">
+ <Button
+ variant="outline"
+ onClick={() => setShowDisable2FAConfirm(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button variant="destructive" onClick={handleDisable2FA}>
+ {t("common.confirm")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </main>
+ );
+}
diff --git a/frontend/src/react/pages/settings/profile/UserPasswordSection.tsx b/frontend/src/react/pages/settings/profile/UserPasswordSection.tsx
new file mode 100644
index 0000000000..6f8f41f302
--- /dev/null
+++ b/frontend/src/react/pages/settings/profile/UserPasswordSection.tsx
@@ -0,0 +1,228 @@
+import {
+ CircleAlert,
+ CircleCheck,
+ CircleHelp,
+ Eye,
+ EyeOff,
+} from "lucide-react";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Input } from "@/react/components/ui/input";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import type { WorkspaceProfileSetting_PasswordRestriction } from "@/types/proto-es/v1/setting_service_pb";
+
+interface PasswordCheck {
+ text: string;
+ matched: boolean;
+}
+
+/**
+ * Returns a list of password errors. Empty array means valid.
+ * Exported for parent components to check validity without a ref.
+ */
+export function getPasswordErrors(
+ password: string,
+ passwordConfirm: string,
+ restriction?: WorkspaceProfileSetting_PasswordRestriction
+): { hasHint: boolean; hasMismatch: boolean } {
+ if (!password) {
+ return { hasHint: false, hasMismatch: false };
+ }
+
+ const minLength = restriction?.minLength ?? 8;
+ const checks: boolean[] = [password.length >= minLength];
+
+ if (restriction?.requireNumber) {
+ checks.push(/[0-9]+/.test(password));
+ }
+ if (restriction?.requireUppercaseLetter) {
+ checks.push(/[A-Z]+/.test(password));
+ } else if (restriction?.requireLetter) {
+ checks.push(/[a-zA-Z]+/.test(password));
+ }
+ if (restriction?.requireSpecialCharacter) {
+ checks.push(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]+/.test(password));
+ }
+
+ const hasHint = checks.some((c) => !c);
+ const hasMismatch = password !== passwordConfirm;
+ return { hasHint, hasMismatch };
+}
+
+interface UserPasswordSectionProps {
+ password: string;
+ passwordConfirm: string;
+ onPasswordChange: (value: string) => void;
+ onPasswordConfirmChange: (value: string) => void;
+ passwordRestriction?: WorkspaceProfileSetting_PasswordRestriction;
+ disabled?: boolean;
+}
+
+export function UserPasswordSection({
+ password,
+ passwordConfirm,
+ onPasswordChange,
+ onPasswordConfirmChange,
+ passwordRestriction,
+ disabled,
+}: UserPasswordSectionProps) {
+ const { t } = useTranslation();
+ const [showPassword, setShowPassword] = useState(false);
+
+ const passwordChecks = useMemo((): PasswordCheck[] => {
+ const minLength = passwordRestriction?.minLength ?? 8;
+ const checks: PasswordCheck[] = [
+ {
+ text: t("settings.general.workspace.password-restriction.min-length", {
+ min: minLength,
+ }),
+ matched: password.length >= minLength,
+ },
+ ];
+
+ if (passwordRestriction?.requireNumber) {
+ checks.push({
+ text: t(
+ "settings.general.workspace.password-restriction.require-number"
+ ),
+ matched: /[0-9]+/.test(password),
+ });
+ }
+ if (passwordRestriction?.requireUppercaseLetter) {
+ checks.push({
+ text: t(
+ "settings.general.workspace.password-restriction.require-uppercase-letter"
+ ),
+ matched: /[A-Z]+/.test(password),
+ });
+ } else if (passwordRestriction?.requireLetter) {
+ checks.push({
+ text: t(
+ "settings.general.workspace.password-restriction.require-letter"
+ ),
+ matched: /[a-zA-Z]+/.test(password),
+ });
+ }
+ if (passwordRestriction?.requireSpecialCharacter) {
+ checks.push({
+ text: t(
+ "settings.general.workspace.password-restriction.require-special-character"
+ ),
+ matched: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]+/.test(password),
+ });
+ }
+
+ return checks;
+ }, [password, passwordRestriction, t]);
+
+ const passwordHint = password
+ ? passwordChecks.some((c) => !c.matched)
+ : false;
+ const passwordMismatch = password ? password !== passwordConfirm : false;
+
+ const toggleVisibility = () => setShowPassword((v) => !v);
+
+ return (
+ <div className="flex flex-col gap-y-6">
+ {/* Password field */}
+ <div>
+ <div>
+ <label className="block text-sm font-medium leading-5 text-control">
+ {t("settings.profile.password")}{" "}
+ <span className="text-error">*</span>
+ </label>
+ <span
+ className={`flex items-center gap-x-1 text-sm ${
+ passwordHint ? "text-error" : "text-control-light"
+ }`}
+ >
+ {t("settings.profile.password-hint")}
+ <Tooltip
+ content={
+ <ul className="list-disc">
+ {passwordChecks.map((check, i) => (
+ <li key={i} className="flex gap-x-1 items-center">
+ {check.matched ? (
+ <CircleCheck className="w-4 text-green-400" />
+ ) : (
+ <CircleAlert className="w-4 text-red-400" />
+ )}
+ {check.text}
+ </li>
+ ))}
+ </ul>
+ }
+ >
+ <CircleHelp className="w-4" />
+ </Tooltip>
+ </span>
+ </div>
+ <div className="w-full flex flex-col gap-y-1">
+ <div className="mt-1 relative flex flex-row items-center">
+ <Input
+ value={password}
+ type={showPassword ? "text" : "password"}
+ autoComplete="new-password"
+ placeholder={t("common.sensitive-placeholder")}
+ disabled={disabled}
+ className={passwordHint ? "border-error focus:ring-error" : ""}
+ onChange={(e) => onPasswordChange(e.target.value)}
+ />
+ <button
+ type="button"
+ tabIndex={-1}
+ className="hover:cursor-pointer absolute right-3"
+ onClick={toggleVisibility}
+ >
+ {showPassword ? (
+ <Eye className="w-4 h-4" />
+ ) : (
+ <EyeOff className="w-4 h-4" />
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Confirm field */}
+ <div>
+ <label className="block text-sm font-medium leading-5 text-control">
+ {t("settings.profile.password-confirm")}{" "}
+ <span className="text-error">*</span>
+ </label>
+ <div className="w-full mt-1 flex flex-col justify-start items-start">
+ <div className="w-full relative flex flex-row items-center">
+ <Input
+ value={passwordConfirm}
+ type={showPassword ? "text" : "password"}
+ autoComplete="new-password"
+ placeholder={t("settings.profile.password-confirm-placeholder")}
+ disabled={disabled}
+ className={
+ passwordMismatch ? "border-error focus:ring-error" : ""
+ }
+ onChange={(e) => onPasswordConfirmChange(e.target.value)}
+ />
+ <button
+ type="button"
+ tabIndex={-1}
+ className="hover:cursor-pointer absolute right-3"
+ onClick={toggleVisibility}
+ >
+ {showPassword ? (
+ <Eye className="w-4 h-4" />
+ ) : (
+ <EyeOff className="w-4 h-4" />
+ )}
+ </button>
+ </div>
+ {passwordMismatch && (
+ <span className="text-error text-sm mt-1 pl-1">
+ {t("settings.profile.password-mismatch")}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/settings/two-factor/RecoveryCodesView.tsx b/frontend/src/react/pages/settings/two-factor/RecoveryCodesView.tsx
new file mode 100644
index 0000000000..a94f3e4218
--- /dev/null
+++ b/frontend/src/react/pages/settings/two-factor/RecoveryCodesView.tsx
@@ -0,0 +1,65 @@
+import { Download, Info } from "lucide-react";
+import { useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+
+interface RecoveryCodesViewProps {
+ recoveryCodes: string[];
+ onDownload?: () => void;
+}
+
+export function RecoveryCodesView({
+ recoveryCodes,
+ onDownload,
+}: RecoveryCodesViewProps) {
+ const { t } = useTranslation();
+
+ const downloadRecoveryCodes = useCallback(() => {
+ const content = recoveryCodes.join("\n");
+ const blob = new Blob([content], { type: "text/plain" });
+ const downloadLink = document.createElement("a");
+ downloadLink.href = URL.createObjectURL(blob);
+ downloadLink.download = "bytebase-recovery-codes.txt";
+ document.body.appendChild(downloadLink);
+ downloadLink.click();
+ URL.revokeObjectURL(downloadLink.href);
+ document.body.removeChild(downloadLink);
+ onDownload?.();
+ }, [recoveryCodes, onDownload]);
+
+ return (
+ <div className="w-full flex flex-col gap-y-4 my-8">
+ <div className="flex gap-3 rounded-md border border-blue-200 bg-blue-50 p-4">
+ <Info className="w-5 h-5 text-blue-600 shrink-0 mt-0.5" />
+ <div>
+ <p className="text-sm font-medium text-blue-800">
+ {t("two-factor.setup-steps.download-recovery-codes.keep-safe.self")}
+ </p>
+ <div className="text-sm text-blue-700 mt-1">
+ <p>{t("two-factor.setup-steps.download-recovery-codes.tips")}</p>
+ <p>
+ {t(
+ "two-factor.setup-steps.download-recovery-codes.keep-safe.description"
+ )}
+ </p>
+ </div>
+ </div>
+ </div>
+ <div className="w-full mx-auto flex flex-col justify-start items-start">
+ <ul className="w-full grid grid-cols-2 list-disc list-inside mx-auto gap-4 gap-x-24 p-8 px-12 border rounded-md bg-gray-50">
+ {recoveryCodes.map((code) => (
+ <li key={code}>
+ <code className="ml-2">{code}</code>
+ </li>
+ ))}
+ </ul>
+ </div>
+ <div className="w-full mx-auto flex flex-row justify-end items-center">
+ <Button onClick={downloadRecoveryCodes}>
+ <Download className="w-5 h-auto" />
+ {t("common.download")}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/settings/two-factor/RegenerateRecoveryCodesView.tsx b/frontend/src/react/pages/settings/two-factor/RegenerateRecoveryCodesView.tsx
new file mode 100644
index 0000000000..d98c0ca64c
--- /dev/null
+++ b/frontend/src/react/pages/settings/two-factor/RegenerateRecoveryCodesView.tsx
@@ -0,0 +1,78 @@
+import { create } from "@bufbuild/protobuf";
+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { useVueState } from "@/react/hooks/useVueState";
+import { pushNotification, useCurrentUserV1, useUserStore } from "@/store";
+import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import { RecoveryCodesView } from "./RecoveryCodesView";
+
+interface RegenerateRecoveryCodesViewProps {
+ recoveryCodes: string[];
+ onClose: () => void;
+}
+
+export function RegenerateRecoveryCodesView({
+ recoveryCodes,
+ onClose,
+}: RegenerateRecoveryCodesViewProps) {
+ const { t } = useTranslation();
+ const userStore = useUserStore();
+ const currentUser = useVueState(() => useCurrentUserV1().value);
+ const [recoveryCodesDownloaded, setRecoveryCodesDownloaded] = useState(false);
+
+ useEffect(() => {
+ userStore.updateUser(
+ create(UpdateUserRequestSchema, {
+ user: {
+ name: currentUser.name,
+ },
+ updateMask: create(FieldMaskSchema, {
+ paths: [],
+ }),
+ regenerateTempMfaSecret: true,
+ })
+ );
+ }, []);
+
+ const regenerateRecoveryCodes = useCallback(async () => {
+ await userStore.updateUser(
+ create(UpdateUserRequestSchema, {
+ user: {
+ name: currentUser.name,
+ },
+ updateMask: create(FieldMaskSchema, {
+ paths: [],
+ }),
+ regenerateRecoveryCodes: true,
+ })
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("two-factor.messages.recovery-codes-regenerated"),
+ });
+ onClose();
+ }, [currentUser.name, onClose, t, userStore]);
+
+ return (
+ <>
+ <RecoveryCodesView
+ recoveryCodes={recoveryCodes}
+ onDownload={() => setRecoveryCodesDownloaded(true)}
+ />
+ <div className="flex flex-row justify-between items-center mb-8">
+ <Button variant="outline" onClick={onClose}>
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={!recoveryCodesDownloaded}
+ onClick={regenerateRecoveryCodes}
+ >
+ {t("two-factor.setup-steps.recovery-codes-saved")}
+ </Button>
+ </div>
+ </>
+ );
+}
diff --git a/frontend/src/react/pages/settings/two-factor/TwoFactorSecretModal.tsx b/frontend/src/react/pages/settings/two-factor/TwoFactorSecretModal.tsx
new file mode 100644
index 0000000000..7fa70b761d
--- /dev/null
+++ b/frontend/src/react/pages/settings/two-factor/TwoFactorSecretModal.tsx
@@ -0,0 +1,61 @@
+import { Copy } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { pushNotification } from "@/store";
+
+interface TwoFactorSecretModalProps {
+ secret: string;
+ open: boolean;
+ onClose: () => void;
+}
+
+export function TwoFactorSecretModal({
+ secret,
+ open,
+ onClose,
+}: TwoFactorSecretModalProps) {
+ const { t } = useTranslation();
+
+ const copySecret = async () => {
+ try {
+ await navigator.clipboard.writeText(secret);
+ pushNotification({
+ module: "bytebase",
+ style: "INFO",
+ title: t("two-factor.your-two-factor-secret.copy-succeed"),
+ });
+ } catch {
+ // Clipboard API not available
+ }
+ onClose();
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="p-6">
+ <DialogTitle>{t("two-factor.your-two-factor-secret.self")}</DialogTitle>
+ <DialogDescription>
+ {t("two-factor.your-two-factor-secret.description")}
+ </DialogDescription>
+ <div className="my-4 py-2">
+ <code className="pr-4">{secret}</code>
+ </div>
+ <div className="flex items-center justify-end gap-x-2">
+ <Button variant="outline" onClick={onClose}>
+ {t("common.close")}
+ </Button>
+ <Button onClick={copySecret}>
+ <Copy className="w-4 h-4" />
+ {t("common.copy")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx b/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx
new file mode 100644
index 0000000000..82a6c6292c
--- /dev/null
+++ b/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx
@@ -0,0 +1,378 @@
+import { create } from "@bufbuild/protobuf";
+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import type { ConnectError } from "@connectrpc/connect";
+import { Check, ExternalLink } from "lucide-react";
+import { QRCodeSVG } from "qrcode.react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { OtpInput } from "@/react/components/ui/otp-input";
+import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/router";
+import { AUTH_2FA_SETUP_MODULE } from "@/router/auth";
+import { SETTING_ROUTE_PROFILE } from "@/router/dashboard/workspaceSetting";
+import { pushNotification, useCurrentUserV1, useUserStore } from "@/store";
+import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
+import { RecoveryCodesView } from "./RecoveryCodesView";
+import { TwoFactorSecretModal } from "./TwoFactorSecretModal";
+
+const ISSUER_NAME = "Bytebase";
+const DIGITS = 6;
+const MFA_TEMP_SECRET_EXPIRATION = 5 * 60 * 1000; // 5 minutes
+
+const SETUP_AUTH_APP_STEP = 0;
+const DOWNLOAD_RECOVERY_CODES_STEP = 1;
+type Step = typeof SETUP_AUTH_APP_STEP | typeof DOWNLOAD_RECOVERY_CODES_STEP;
+
+interface TwoFactorSetupPageProps {
+ cancelAction?: () => void;
+}
+
+export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {
+ const { t } = useTranslation();
+ const userStore = useUserStore();
+ const currentUser = useVueState(() => useCurrentUserV1().value);
+
+ const [currentStep, setCurrentStep] = useState<Step>(SETUP_AUTH_APP_STEP);
+ const [showSecretModal, setShowSecretModal] = useState(false);
+ const [otpCodes, setOtpCodes] = useState<string[]>([]);
+ const [recoveryCodesDownloaded, setRecoveryCodesDownloaded] = useState(false);
+ const [timeRemaining, setTimeRemaining] = useState("5:00");
+ const [isExpired, setIsExpired] = useState(false);
+ const [isExpiringSoon, setIsExpiringSoon] = useState(false);
+
+ const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ // Keep a ref to currentUser so the interval callback always reads fresh state
+ const currentUserRef = useRef(currentUser);
+ currentUserRef.current = currentUser;
+
+ const stopCountdown = useCallback(() => {
+ if (countdownRef.current) {
+ clearInterval(countdownRef.current);
+ countdownRef.current = null;
+ }
+ }, []);
+
+ const updateCountdown = useCallback(() => {
+ const cu = currentUserRef.current;
+ if (!cu.tempOtpSecretCreatedTime) {
+ setIsExpired(true);
+ setTimeRemaining("0:00");
+ return;
+ }
+
+ const createdAt = Number(cu.tempOtpSecretCreatedTime.seconds) * 1000;
+ const remaining = MFA_TEMP_SECRET_EXPIRATION - (Date.now() - createdAt);
+
+ if (remaining <= 0) {
+ setIsExpired(true);
+ setTimeRemaining("0:00");
+ setIsExpiringSoon(false);
+ stopCountdown();
+ } else {
+ setIsExpired(false);
+ const minutes = Math.floor(remaining / 60000);
+ const seconds = Math.floor((remaining % 60000) / 1000);
+ setTimeRemaining(`${minutes}:${seconds.toString().padStart(2, "0")}`);
+ setIsExpiringSoon(remaining < 60000);
+ }
+ }, [stopCountdown]);
+
+ const startCountdown = useCallback(() => {
+ updateCountdown();
+ stopCountdown();
+ countdownRef.current = setInterval(updateCountdown, 1000);
+ }, [updateCountdown, stopCountdown]);
+
+ const regenerateTempMfaSecret = useCallback(async () => {
+ await userStore.updateUser(
+ create(UpdateUserRequestSchema, {
+ user: {
+ name: currentUser.name,
+ },
+ updateMask: create(FieldMaskSchema, {
+ paths: [],
+ }),
+ regenerateTempMfaSecret: true,
+ })
+ );
+ }, [currentUser.name, userStore]);
+
+ // On mount: regenerate secret and start countdown
+ useEffect(() => {
+ regenerateTempMfaSecret().then(() => {
+ startCountdown();
+ });
+ return stopCountdown;
+ }, [regenerateTempMfaSecret, startCountdown, stopCountdown]);
+
+ const otpauthUrl = `otpauth://totp/${ISSUER_NAME}:${currentUser.email}?algorithm=SHA1&digits=${DIGITS}&issuer=${ISSUER_NAME}&period=30&secret=${currentUser.tempOtpSecret}`;
+
+ const verifyOTPCode = useCallback(
+ async (codes: string[]) => {
+ try {
+ await userStore.updateUser(
+ create(UpdateUserRequestSchema, {
+ user: {
+ name: currentUser.name,
+ },
+ updateMask: create(FieldMaskSchema, {
+ paths: [],
+ }),
+ otpCode: codes.join(""),
+ })
+ );
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: (error as ConnectError).message,
+ });
+ return false;
+ }
+ return true;
+ },
+ [currentUser.name, userStore]
+ );
+
+ const handleOtpFinish = useCallback(
+ async (value: string[]) => {
+ setOtpCodes(value);
+ const result = await verifyOTPCode(value);
+ if (result && currentStep === SETUP_AUTH_APP_STEP) {
+ setCurrentStep(DOWNLOAD_RECOVERY_CODES_STEP);
+ }
+ },
+ [verifyOTPCode, currentStep]
+ );
+
+ const handleNext = useCallback(async () => {
+ const result = await verifyOTPCode(otpCodes);
+ if (result) {
+ setCurrentStep(DOWNLOAD_RECOVERY_CODES_STEP);
+ }
+ }, [verifyOTPCode, otpCodes]);
+
+ const handleBack = useCallback(() => {
+ setOtpCodes([]);
+ setCurrentStep(SETUP_AUTH_APP_STEP);
+ }, []);
+
+ const handleRegenerateSecret = useCallback(async () => {
+ setOtpCodes([]);
+ await regenerateTempMfaSecret();
+ startCountdown();
+ }, [regenerateTempMfaSecret, startCountdown]);
+
+ const cancelSetup = useCallback(() => {
+ if (cancelAction) {
+ cancelAction();
+ } else {
+ router.replace({
+ name: SETTING_ROUTE_PROFILE,
+ });
+ }
+ }, [cancelAction]);
+
+ const tryFinishSetup = useCallback(async () => {
+ await userStore.updateUser(
+ create(UpdateUserRequestSchema, {
+ user: {
+ name: currentUser.name,
+ mfaEnabled: true,
+ },
+ updateMask: create(FieldMaskSchema, {
+ paths: ["mfa_enabled"],
+ }),
+ })
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("two-factor.messages.2fa-enabled"),
+ });
+
+ if (router.currentRoute.value.name === AUTH_2FA_SETUP_MODULE) {
+ router.replace({ path: "/" });
+ } else {
+ router.replace({ name: SETTING_ROUTE_PROFILE });
+ }
+ }, [currentUser.name, t, userStore]);
+
+ const allowNext =
+ currentStep === SETUP_AUTH_APP_STEP
+ ? otpCodes.filter((v) => v).length === DIGITS && !isExpired
+ : recoveryCodesDownloaded;
+
+ const steps = [
+ t("two-factor.setup-steps.setup-auth-app.self"),
+ t("two-factor.setup-steps.download-recovery-codes.self"),
+ ];
+
+ return (
+ <div className="px-4 py-4">
+ <p className="text-sm text-gray-500 mb-4">
+ {t("two-factor.description")}
+ <a
+ href="https://docs.bytebase.com/administration/2fa?source=console"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="ml-1 inline-flex items-center gap-x-0.5 text-accent hover:underline"
+ >
+ {t("common.learn-more")}
+ <ExternalLink className="w-3 h-3" />
+ </a>
+ </p>
+
+ {/* Step indicator */}
+ <div className="flex items-center gap-x-4 mb-8">
+ {steps.map((title, index) => (
+ <div key={index} className="flex items-center gap-x-2">
+ <div
+ className={`flex items-center justify-center w-7 h-7 rounded-full text-sm font-medium ${
+ index < currentStep
+ ? "bg-accent text-white"
+ : index === currentStep
+ ? "bg-accent text-white"
+ : "bg-gray-200 text-gray-600"
+ }`}
+ >
+ {index < currentStep ? <Check className="w-4 h-4" /> : index + 1}
+ </div>
+ <span
+ className={`text-sm font-medium ${
+ index === currentStep ? "text-accent" : "text-gray-500"
+ }`}
+ >
+ {title}
+ </span>
+ {index < steps.length - 1 && (
+ <div className="w-12 h-px bg-gray-300 ml-2" />
+ )}
+ </div>
+ ))}
+ </div>
+
+ {/* Step content */}
+ {currentStep === SETUP_AUTH_APP_STEP && (
+ <div className="w-full max-w-2xl mx-auto flex flex-col justify-start items-start gap-y-4 my-8">
+ <p>{t("two-factor.setup-steps.setup-auth-app.description")}</p>
+ <div
+ className={`w-full border rounded-md p-3 ${
+ isExpired || isExpiringSoon
+ ? "bg-red-50 border-red-200"
+ : "bg-yellow-50 border-yellow-200"
+ }`}
+ >
+ <div className="flex items-center justify-between">
+ <p
+ className={`text-sm ${
+ isExpired || isExpiringSoon
+ ? "text-red-800"
+ : "text-yellow-800"
+ }`}
+ >
+ {isExpired
+ ? t("two-factor.setup-steps.setup-auth-app.expired-notice")
+ : t("two-factor.setup-steps.setup-auth-app.time-remaining", {
+ time: timeRemaining,
+ })}
+ </p>
+ {isExpired && (
+ <button
+ type="button"
+ className="ml-3 px-3 py-1 text-sm font-medium text-white bg-blue-600 rounded-sm hover:bg-blue-700"
+ onClick={handleRegenerateSecret}
+ >
+ {t("two-factor.setup-steps.setup-auth-app.regenerate")}
+ </button>
+ )}
+ </div>
+ </div>
+ <p className="text-2xl">
+ {t("two-factor.setup-steps.setup-auth-app.scan-qr-code.self")}
+ </p>
+ <p>
+ {(() => {
+ const raw = t(
+ "two-factor.setup-steps.setup-auth-app.scan-qr-code.description"
+ );
+ const placeholder = "{{action}}";
+ const idx = raw.indexOf(placeholder);
+ if (idx === -1) return raw;
+ return (
+ <>
+ {raw.slice(0, idx)}
+ <span
+ className={
+ !showSecretModal
+ ? "cursor-pointer text-blue-600"
+ : undefined
+ }
+ onClick={() => setShowSecretModal(true)}
+ >
+ {t(
+ "two-factor.setup-steps.setup-auth-app.scan-qr-code.enter-the-text"
+ )}
+ </span>
+ {raw.slice(idx + placeholder.length)}
+ </>
+ );
+ })()}
+ </p>
+ <div className="w-full flex flex-col justify-center items-center pb-8">
+ <QRCodeSVG value={otpauthUrl} size={150} />
+ <span className="mt-4 mb-2 text-sm font-medium">
+ {t("two-factor.setup-steps.setup-auth-app.verify-code")}
+ </span>
+ <OtpInput
+ value={otpCodes}
+ onChange={setOtpCodes}
+ onFinish={handleOtpFinish}
+ length={DIGITS}
+ />
+ </div>
+ </div>
+ )}
+
+ {currentStep === DOWNLOAD_RECOVERY_CODES_STEP && (
+ <div className="w-full max-w-2xl mx-auto">
+ <RecoveryCodesView
+ recoveryCodes={[...currentUser.tempRecoveryCodes]}
+ onDownload={() => setRecoveryCodesDownloaded(true)}
+ />
+ </div>
+ )}
+
+ {/* Navigation buttons */}
+ <div className="flex items-center justify-between mt-4">
+ <Button variant="outline" onClick={cancelSetup}>
+ {t("common.cancel")}
+ </Button>
+ <div className="flex items-center gap-x-2">
+ {currentStep === DOWNLOAD_RECOVERY_CODES_STEP && (
+ <Button variant="outline" onClick={handleBack}>
+ {t("common.back")}
+ </Button>
+ )}
+ {currentStep === SETUP_AUTH_APP_STEP && (
+ <Button disabled={!allowNext} onClick={handleNext}>
+ {t("common.next")}
+ </Button>
+ )}
+ {currentStep === DOWNLOAD_RECOVERY_CODES_STEP && (
+ <Button disabled={!allowNext} onClick={tryFinishSetup}>
+ {t("two-factor.setup-steps.recovery-codes-saved")}
+ </Button>
+ )}
+ </div>
+ </div>
+
+ <TwoFactorSecretModal
+ secret={currentUser.tempOtpSecret}
+ open={showSecretModal}
+ onClose={() => setShowSecretModal(false)}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/router/dashboard/instance.ts b/frontend/src/router/dashboard/instance.ts
index e0e30b1151..0fcc3401c1 100644
--- a/frontend/src/router/dashboard/instance.ts
+++ b/frontend/src/router/dashboard/instance.ts
@@ -18,7 +18,7 @@ const instanceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/views/CreateInstancePage.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: { content: true },
},
@@ -26,7 +26,7 @@ const instanceRoutes: RouteRecordRaw[] = [
path: "instances/:instanceId",
components: {
content: InstanceLayout,
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
meta: {
title: () => t("common.instance"),
diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.ts
index 3424948e0c..7dcb195f9e 100644
--- a/frontend/src/router/dashboard/workspace.ts
+++ b/frontend/src/router/dashboard/workspace.ts
@@ -50,7 +50,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/react/LandingPageMount.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
},
{
@@ -61,7 +61,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: () => ({ page: "ProjectsPage" }),
@@ -77,7 +77,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: () => ({ page: "InstancesPage" }),
@@ -93,7 +93,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: () => ({ page: "DatabasesPage" }),
@@ -109,7 +109,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: () => ({ page: "EnvironmentsPage" }),
@@ -120,10 +120,16 @@ const workspaceRoutes: RouteRecordRaw[] = [
path: "users/:principalEmail",
name: WORKSPACE_ROUTE_USER_PROFILE,
components: {
- content: () => import("@/views/ProfileDashboard.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ content: () => import("@/react/ReactPageMount.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
+ },
+ props: {
+ content: (route: RouteLocationNormalized) => ({
+ page: "ProfilePage",
+ principalEmail: route.params.principalEmail,
+ }),
+ leftSidebar: true,
},
- props: true,
},
{
path: "403",
@@ -133,7 +139,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/views/Page403.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: true,
@@ -148,7 +154,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/views/Page404.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: true,
@@ -163,7 +169,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/layouts/SettingLayout.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: true,
@@ -220,7 +226,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/layouts/SettingLayout.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: true,
@@ -248,7 +254,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/layouts/SettingLayout.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: true,
children: [
@@ -381,7 +387,7 @@ const workspaceRoutes: RouteRecordRaw[] = [
},
components: {
content: () => import("@/layouts/SettingLayout.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: true,
diff --git a/frontend/src/router/dashboard/workspaceSetting.ts b/frontend/src/router/dashboard/workspaceSetting.ts
index 6f361bfdd6..86431251bc 100644
--- a/frontend/src/router/dashboard/workspaceSetting.ts
+++ b/frontend/src/router/dashboard/workspaceSetting.ts
@@ -15,7 +15,7 @@ const workspaceSettingRoutes: RouteRecordRaw[] = [
meta: { title: () => t("common.settings") },
components: {
content: () => import("@/layouts/SettingLayout.vue"),
- leftSidebar: () => import("@/views/DashboardSidebar.vue"),
+ leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
},
props: {
content: true,
@@ -26,15 +26,15 @@ const workspaceSettingRoutes: RouteRecordRaw[] = [
path: "profile",
name: SETTING_ROUTE_PROFILE,
meta: { title: () => t("settings.sidebar.profile") },
- component: () => import("@/views/ProfileDashboard.vue"),
- props: true,
+ component: () => import("@/react/ReactPageMount.vue"),
+ props: () => ({ page: "ProfilePage" }),
},
{
path: "profile/two-factor",
name: SETTING_ROUTE_PROFILE_TWO_FACTOR,
meta: { title: () => t("two-factor.self") },
- component: () => import("@/views/TwoFactorSetup.vue"),
- props: true,
+ component: () => import("@/react/ReactPageMount.vue"),
+ props: () => ({ page: "TwoFactorSetupPage" }),
},
{
path: "general",
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 831a78a014..b4ae2ca79a 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -19,7 +19,6 @@ export * from "./workspaceApprovalSetting";
export * from "./TinyTimer";
export * from "./sheet";
export * from "./naive-ui";
-export * from "./useDashboardSidebar";
export * from "./workloadIdentity";
export * from "./v1";
diff --git a/frontend/src/utils/useDashboardSidebar.ts b/frontend/src/utils/useDashboardSidebar.ts
deleted file mode 100644
index de6cbeaecf..0000000000
--- a/frontend/src/utils/useDashboardSidebar.ts
+++ /dev/null
@@ -1,261 +0,0 @@
-import {
- DatabaseIcon,
- GalleryHorizontalEndIcon,
- HomeIcon,
- LayersIcon,
- LinkIcon,
- SettingsIcon,
- ShieldCheck,
- SquareStackIcon,
- UsersIcon,
- WorkflowIcon,
-} from "lucide-vue-next";
-import { computed, h } from "vue";
-import { useRoute } from "vue-router";
-import type { SidebarItem } from "@/components/v2/Sidebar/type";
-import { t } from "@/plugins/i18n";
-import {
- DATABASE_ROUTE_DASHBOARD,
- ENVIRONMENT_V1_ROUTE_DASHBOARD,
- INSTANCE_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_DASHBOARD,
- WORKSPACE_ROUTE_AUDIT_LOG,
- WORKSPACE_ROUTE_CUSTOM_APPROVAL,
- WORKSPACE_ROUTE_DATA_CLASSIFICATION,
- WORKSPACE_ROUTE_GLOBAL_MASKING,
- WORKSPACE_ROUTE_GROUPS,
- WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
- WORKSPACE_ROUTE_IM,
- WORKSPACE_ROUTE_LANDING,
- WORKSPACE_ROUTE_MCP,
- WORKSPACE_ROUTE_MEMBERS,
- WORKSPACE_ROUTE_RISK_CENTER,
- WORKSPACE_ROUTE_ROLES,
- WORKSPACE_ROUTE_SEMANTIC_TYPES,
- WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
- WORKSPACE_ROUTE_SQL_REVIEW,
- WORKSPACE_ROUTE_USER_PROFILE,
- WORKSPACE_ROUTE_USERS,
- WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
-} from "@/router/dashboard/workspaceRoutes";
-import {
- SETTING_ROUTE_WORKSPACE_GENERAL,
- SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
-} from "@/router/dashboard/workspaceSetting";
-import { useActuatorV1Store } from "@/store";
-
-export interface DashboardSidebarItem extends SidebarItem {
- navigationId?: string;
- shortcuts?: string[];
- hide?: boolean;
- children?: DashboardSidebarItem[];
-}
-
-export const useDashboardSidebar = () => {
- const route = useRoute();
-
- const getItemClass = (item: SidebarItem): string[] => {
- const { name: current } = route;
- const isActiveRoute =
- item.name === current?.toString() ||
- current?.toString().startsWith(`${item.name}.`);
- const classes: string[] = [];
- if (isActiveRoute) {
- classes.push("router-link-active", "bg-link-hover");
- return classes;
- }
- if (
- item.name === WORKSPACE_ROUTE_USERS &&
- current?.toString() === WORKSPACE_ROUTE_USER_PROFILE
- ) {
- classes.push("router-link-active", "bg-link-hover");
- return classes;
- }
- return classes;
- };
-
- const dashboardSidebarItemList = computed((): DashboardSidebarItem[] => {
- const actuatorStore = useActuatorV1Store();
- const sidebarList: DashboardSidebarItem[] = [
- {
- navigationId: "bb.navigation.home",
- title: t("common.home"),
- icon: () => h(HomeIcon),
- name: WORKSPACE_ROUTE_LANDING,
- type: "route",
- shortcuts: ["g", "h"],
- },
- {
- navigationId: "bb.navigation.projects",
- title: t("common.projects"),
- icon: () => h(GalleryHorizontalEndIcon),
- name: PROJECT_V1_ROUTE_DASHBOARD,
- type: "route",
- shortcuts: ["g", "p"],
- },
- {
- navigationId: "bb.navigation.instances",
- title: t("common.instances"),
- icon: () => h(LayersIcon),
- name: INSTANCE_ROUTE_DASHBOARD,
- type: "route",
- shortcuts: ["g", "i"],
- },
- {
- navigationId: "bb.navigation.databases",
- title: t("common.databases"),
- icon: () => h(DatabaseIcon),
- name: DATABASE_ROUTE_DASHBOARD,
- type: "route",
- shortcuts: ["g", "d"],
- },
- {
- navigationId: "bb.navigation.environments",
- title: t("common.environments"),
- icon: () => h(SquareStackIcon),
- name: ENVIRONMENT_V1_ROUTE_DASHBOARD,
- type: "route",
- shortcuts: ["g", "e"],
- },
- {
- type: "divider",
- name: "",
- },
- {
- title: t("settings.sidebar.iam-and-admin"),
- icon: () => h(UsersIcon),
- type: "div",
- children: [
- {
- title: t("common.users"),
- name: WORKSPACE_ROUTE_USERS,
- type: "route",
- hide: actuatorStore.isSaaSMode,
- },
- {
- title: t("settings.members.service-accounts"),
- name: WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
- type: "route",
- hide: actuatorStore.isSaaSMode,
- },
- {
- title: t("settings.members.workload-identities"),
- name: WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
- type: "route",
- hide: actuatorStore.isSaaSMode,
- },
- {
- title: t("settings.sidebar.members"),
- name: WORKSPACE_ROUTE_MEMBERS,
- type: "route",
- },
- {
- title: t("settings.members.groups.self"),
- name: WORKSPACE_ROUTE_GROUPS,
- type: "route",
- },
- {
- title: t("settings.sidebar.custom-roles"),
- name: WORKSPACE_ROUTE_ROLES,
- type: "route",
- },
- {
- title: t("settings.sidebar.sso"),
- name: WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
- type: "route",
- },
- {
- title: t("settings.sidebar.audit-log"),
- name: WORKSPACE_ROUTE_AUDIT_LOG,
- type: "route",
- },
- ],
- },
- {
- title: "CI/CD",
- icon: () => h(WorkflowIcon),
- type: "div",
- children: [
- {
- title: t("sql-review.title"),
- name: WORKSPACE_ROUTE_SQL_REVIEW,
- type: "route",
- },
- {
- title: t("custom-approval.risk.self"),
- name: WORKSPACE_ROUTE_RISK_CENTER,
- type: "route",
- },
- {
- title: t("custom-approval.self"),
- name: WORKSPACE_ROUTE_CUSTOM_APPROVAL,
- type: "route",
- },
- ],
- },
- {
- title: t("settings.sidebar.data-access"),
- icon: () => h(ShieldCheck),
- type: "div",
- children: [
- {
- title: t("settings.sensitive-data.semantic-types.self"),
- name: WORKSPACE_ROUTE_SEMANTIC_TYPES,
- type: "route",
- },
- {
- title: t("settings.sidebar.data-classification"),
- name: WORKSPACE_ROUTE_DATA_CLASSIFICATION,
- type: "route",
- },
- {
- title: t("settings.sidebar.global-masking"),
- name: WORKSPACE_ROUTE_GLOBAL_MASKING,
- type: "route",
- },
- ],
- },
- {
- title: t("settings.sidebar.integration"),
- icon: () => h(LinkIcon),
- type: "div",
- children: [
- {
- title: t("settings.sidebar.im-integration"),
- name: WORKSPACE_ROUTE_IM,
- type: "route",
- },
- {
- title: t("settings.sidebar.mcp"),
- name: WORKSPACE_ROUTE_MCP,
- type: "route",
- },
- ],
- },
- {
- title: t("common.settings"),
- icon: () => h(SettingsIcon),
- type: "div",
- children: [
- {
- title: t("settings.sidebar.general"),
- name: SETTING_ROUTE_WORKSPACE_GENERAL,
- type: "route",
- },
- {
- title: t("settings.sidebar.subscription"),
- name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
- type: "route",
- },
- ],
- },
- ];
-
- return sidebarList;
- });
-
- return {
- getItemClass,
- dashboardSidebarItemList,
- };
-};
diff --git a/frontend/src/views/DashboardSidebar.vue b/frontend/src/views/DashboardSidebar.vue
deleted file mode 100644
index 09c6aab829..0000000000
--- a/frontend/src/views/DashboardSidebar.vue
+++ /dev/null
@@ -1,34 +0,0 @@
-<template>
- <!-- Navigation -->
- <CommonSidebar
- :key="'dashboard'"
- :item-list="dashboardSidebarItemList"
- :get-item-class="getItemClass"
- :logo-redirect="logoRedirect"
- >
- <template #prefix>
- <WorkspaceSwitcher />
- </template>
- </CommonSidebar>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import CommonSidebar from "@/components/v2/Sidebar/CommonSidebar.vue";
-import WorkspaceSwitcher from "@/components/v2/Sidebar/WorkspaceSwitcher.vue";
-import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";
-import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";
-import { useAppFeature } from "@/store";
-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
-import { useDashboardSidebar } from "@/utils";
-
-const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");
-const { getItemClass, dashboardSidebarItemList } = useDashboardSidebar();
-
-const logoRedirect = computed(() => {
- if (databaseChangeMode.value === DatabaseChangeMode.EDITOR) {
- return SQL_EDITOR_HOME_MODULE;
- }
- return WORKSPACE_ROUTE_LANDING;
-});
-</script>
diff --git a/frontend/src/views/ProfileDashboard.vue b/frontend/src/views/ProfileDashboard.vue
deleted file mode 100644
index 1bec8d659d..0000000000
--- a/frontend/src/views/ProfileDashboard.vue
+++ /dev/null
@@ -1,585 +0,0 @@
-<template>
- <main
- class="pt-4 flex-1 h-full relative pb-8 focus:outline-hidden xl:order-last"
- tabindex="0"
- >
- <NoPermissionPlaceholder
- v-if="!allowGet"
- class="px-4"
- :permissions="['bb.users.get']"
- />
- <div v-else>
- <!-- Profile header -->
- <div>
- <div class="-mt-4 h-32 bg-accent lg:h-48"></div>
- <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
- <div class="-mt-20 sm:flex sm:items-end sm:gap-x-5">
- <UserAvatar :user="user" size="HUGE" />
- <div
- class="mt-6 sm:flex-1 sm:min-w-0 sm:flex sm:items-center sm:justify-end sm:gap-x-6 sm:pb-1"
- >
- <div class="mt-6 flex flex-row justify-stretch gap-x-2">
- <template v-if="allowEdit">
- <template v-if="state.editing">
- <NButton quaternary :disabled="state.saving" @click.prevent="cancelEdit">
- {{ $t("common.cancel") }}
- </NButton>
- <NButton
- type="primary"
- :disabled="!allowSaveEdit"
- :loading="state.saving"
- @click.prevent="saveEdit"
- >
- {{ $t("common.save") }}
- </NButton>
- </template>
- <NButton v-else @click.prevent="editUser">
- {{ $t("common.edit") }}
- </NButton>
- </template>
- </div>
- </div>
- </div>
- <div class="block mt-6 min-w-0 flex-1">
- <NInput
- v-if="state.editing"
- ref="editNameTextField"
- :input-props="{ autocomplete: 'off' }"
- :value="state.editingUser?.title"
- style="width: 16rem"
- size="large"
- @update:value="updateUser('title', $event)"
- />
- <h1 v-else class="pb-1.5 text-2xl font-bold text-main truncate">
- {{ user.title }}
- </h1>
- </div>
- </div>
- </div>
-
- <!-- Description list -->
- <div class="mt-6 mb-2 max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
- <dl class="grid grid-cols-1 gap-x-4 gap-y-8 sm:grid-cols-3">
- <div class="sm:col-span-1">
- <dt class="text-sm font-medium text-control-light">
- {{ $t("settings.profile.role") }}
- </dt>
- <dd class="mt-1 text-sm text-main">
- <div
- class="flex flex-row justify-start items-start flex-wrap gap-2"
- >
- <NTag
- v-for="role in sortRoles(userRoles)"
- :key="role"
- size="large"
- >
- {{ displayRoleTitle(role) }}
- </NTag>
- </div>
- <router-link
- v-if="!hasFeature(PlanFeature.FEATURE_IAM)"
- :to="{
- name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
- }"
- class="normal-link"
- >
- {{ $t("settings.profile.subscription") }}
- </router-link>
- </dd>
- </div>
-
- <div class="sm:col-span-1">
- <dt class="text-sm font-medium text-control-light">
- {{ $t("settings.profile.email") }}
- </dt>
- <dd class="mt-1 text-sm text-main">
- <EmailInput
- v-if="state.editing && allowEditEmail"
- v-model:value="state.editingUser!.email"
- />
- <template v-else>
- {{ user.email }}
- </template>
- </dd>
- </div>
-
- <div v-if="getAccountTypeByEmail(user.email) === AccountType.USER" class="sm:col-span-1">
- <dt class="text-sm font-medium text-control-light">
- {{ $t("settings.profile.phone") }}
- </dt>
- <dd class="mt-1 text-sm text-main">
- <NInput
- v-if="state.editing"
- :value="state.editingUser?.phone"
- :placeholder="$t('settings.profile.phone-tips')"
- :input-props="{ autocomplete: 'off', type: 'tel' }"
- @update:value="updateUser('phone', $event)"
- />
- <template v-else>
- {{ user.phone }}
- </template>
- </dd>
- </div>
-
- <div v-if="state.editing" class="col-span-2">
- <UserPassword
- v-if="state.editingUser"
- ref="userPasswordRef"
- v-model:password="state.editingUser!.password"
- v-model:password-confirm="state.passwordConfirm"
- :password-restriction="passwordRestrictionSetting"
- />
- </div>
- </dl>
- </div>
-
- <!-- 2FA setting section -->
- <div
- v-if="allowEdit"
- class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 border-t mt-16 pt-8 pb-4"
- >
- <div class="w-full flex flex-row justify-between items-center">
- <span
- class="text-lg font-medium flex flex-row justify-start items-center"
- >
- {{ $t("two-factor.self") }}
- <FeatureBadge :feature="PlanFeature.FEATURE_TWO_FA" class="ml-2" />
- </span>
- <div class="flex gap-x-2">
- <NButton v-if="isMFAEnabled" type="error" @click="disable2FA">
- {{ $t("common.disable") }}
- </NButton>
- <NButton v-if="user.email === currentUser.email" @click="enable2FA">
- {{ isMFAEnabled ? $t("common.edit") : $t("common.enable") }}
- </NButton>
- </div>
- </div>
- <p class="mt-4 text-sm text-gray-500">
- {{ $t("two-factor.description") }}
- <LearnMoreLink
- class="ml-1"
- url="https://docs.bytebase.com/administration/2fa?source=console"
- />
- </p>
- <template v-if="showRegenerateRecoveryCodes">
- <div class="w-full flex flex-row justify-between items-center mt-8">
- <span class="text-lg font-medium">
- {{ $t("two-factor.recovery-codes.self") }}
- </span>
- <div v-if="!state.showRegenerateRecoveryCodesView" class="relative">
- <NDropdown
- trigger="click"
- :options="dropDownOptions"
- placement="bottom-end"
- >
- <MiniActionButton size="small">
- <EllipsisIcon class="w-8" />
- </MiniActionButton>
- </NDropdown>
- </div>
- </div>
- <p class="mt-4 text-sm text-gray-500">
- {{ $t("two-factor.recovery-codes.description") }}
- </p>
- <RegenerateRecoveryCodesView
- v-if="state.showRegenerateRecoveryCodesView"
- :recovery-codes="currentUser.tempRecoveryCodes"
- @close="state.showRegenerateRecoveryCodesView = false"
- />
- </template>
- </div>
- </div>
- </main>
-
- <FeatureModal
- :feature="PlanFeature.FEATURE_TWO_FA"
- :open="state.showFeatureModal"
- @cancel="state.showFeatureModal = false"
- />
-
- <!-- Close modal confirm dialog -->
- <ActionConfirmModal
- v-model:show="state.showDisable2FAConfirmModal"
- :title="$t('two-factor.disable.self')"
- :description="$t('two-factor.disable.description')"
- :positive-button-props="{
- type: 'error',
- }"
- @confirm="handleDisable2FA"
- />
-</template>
-
-<script lang="ts" setup>
-import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import type { ConnectError } from "@connectrpc/connect";
-import { cloneDeep, isEqual } from "lodash-es";
-import { EllipsisIcon } from "lucide-vue-next";
-import type { DropdownOption } from "naive-ui";
-import { NButton, NDropdown, NInput, NTag } from "naive-ui";
-import {
- computed,
- nextTick,
- onBeforeMount,
- onMounted,
- onUnmounted,
- reactive,
- ref,
- watch,
-} from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import EmailInput from "@/components/EmailInput.vue";
-import { FeatureModal } from "@/components/FeatureGuard";
-import FeatureBadge from "@/components/FeatureGuard/FeatureBadge.vue";
-import LearnMoreLink from "@/components/LearnMoreLink.vue";
-import NoPermissionPlaceholder from "@/components/Permission/NoPermissionPlaceholder.vue";
-import RegenerateRecoveryCodesView from "@/components/RegenerateRecoveryCodesView.vue";
-import { ActionConfirmModal } from "@/components/SchemaEditorLite";
-import UserPassword from "@/components/User/Settings/UserPassword.vue";
-import UserAvatar from "@/components/User/UserAvatar.vue";
-import { MiniActionButton } from "@/components/v2";
-import { useRouteChangeGuard } from "@/composables/useRouteChangeGuard";
-import {
- WORKSPACE_ROUTE_404,
- WORKSPACE_ROUTE_USER_PROFILE,
-} from "@/router/dashboard/workspaceRoutes";
-import {
- SETTING_ROUTE_PROFILE_TWO_FACTOR,
- SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
-} from "@/router/dashboard/workspaceSetting";
-import {
- featureToRef,
- hasFeature,
- pushNotification,
- useActuatorV1Store,
- useAuthStore,
- useCurrentUserV1,
- useSettingV1Store,
- useUserStore,
- useWorkspaceV1Store,
-} from "@/store";
-import {
- AccountType,
- ALL_USERS_USER_EMAIL,
- getAccountTypeByEmail,
- isValidUserName,
- unknownUser,
-} from "@/types";
-import { State } from "@/types/proto-es/v1/common_pb";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import type { User } from "@/types/proto-es/v1/user_service_pb";
-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
-import {
- displayRoleTitle,
- hasWorkspacePermissionV2,
- setDocumentTitle,
- sortRoles,
-} from "@/utils";
-import { migrateUserStorage } from "@/utils/storage-migrate";
-
-interface LocalState {
- editing: boolean;
- editingUser?: User;
- passwordConfirm: string;
- saving: boolean;
- showFeatureModal: boolean;
- showDisable2FAConfirmModal: boolean;
- showRegenerateRecoveryCodesView: boolean;
-}
-
-const props = defineProps<{
- principalEmail?: string;
-}>();
-
-const { t } = useI18n();
-const router = useRouter();
-const authStore = useAuthStore();
-const settingV1Store = useSettingV1Store();
-const currentUser = useCurrentUserV1();
-const userStore = useUserStore();
-const workspaceStore = useWorkspaceV1Store();
-const actuatorStore = useActuatorV1Store();
-
-const state = reactive<LocalState>({
- editing: false,
- passwordConfirm: "",
- saving: false,
- showFeatureModal: false,
- showDisable2FAConfirmModal: false,
- showRegenerateRecoveryCodesView: false,
-});
-
-onBeforeMount(() => {
- if (props.principalEmail) {
- const userType = getAccountTypeByEmail(props.principalEmail);
- if (userType !== AccountType.USER) {
- router.replace({
- name: WORKSPACE_ROUTE_404,
- });
- }
- }
-});
-
-const editNameTextField = ref<InstanceType<typeof NInput>>();
-const userPasswordRef = ref<InstanceType<typeof UserPassword>>();
-
-const passwordRestrictionSetting = computed(
- () => settingV1Store.workspaceProfile.passwordRestriction
-);
-
-const keyboardHandler = (e: KeyboardEvent) => {
- if (e.isComposing) return;
- if (state.editing) {
- if (e.code === "Escape") {
- cancelEdit();
- } else if (e.code === "Enter" && e.metaKey) {
- if (allowSaveEdit.value) {
- saveEdit();
- }
- }
- }
-};
-
-onMounted(async () => {
- document.addEventListener("keydown", keyboardHandler);
- if (props.principalEmail) {
- const user = await userStore.getOrFetchUserByIdentifier({
- identifier: props.principalEmail,
- fallback: false,
- });
- if (!isValidUserName(user.name)) {
- router.replace({
- name: WORKSPACE_ROUTE_404,
- });
- }
- }
-});
-
-onUnmounted(() => {
- document.removeEventListener("keydown", keyboardHandler);
-});
-
-const has2FAFeature = featureToRef(PlanFeature.FEATURE_TWO_FA);
-
-const isMFAEnabled = computed(() => {
- return user.value.mfaEnabled;
-});
-
-// only user can regenerate their recovery-codes.
-const showRegenerateRecoveryCodes = computed(() => {
- return user.value.mfaEnabled && user.value.name === currentUser.value.name;
-});
-
-const user = computed(() => {
- if (props.principalEmail) {
- return userStore.getUserByIdentifier(props.principalEmail) ?? unknownUser();
- }
- return currentUser.value;
-});
-
-const userRoles = computed(() => {
- return [...workspaceStore.getWorkspaceRolesByName(user.value.name)];
-});
-
-const isSelf = computed(() => currentUser.value.name === user.value.name);
-
-const allowGet = computed(
- () => isSelf.value || hasWorkspacePermissionV2("bb.users.get")
-);
-
-// User can change her own info.
-// Besides, owner can also change anyone's info. This is for resetting password in case user forgets.
-const allowEdit = computed(() => {
- if (
- user.value.email === ALL_USERS_USER_EMAIL ||
- getAccountTypeByEmail(user.value.email) !== AccountType.USER
- ) {
- return false;
- }
- if (user.value.state !== State.ACTIVE) {
- return false;
- }
- if (isSelf.value) {
- return true;
- }
- return (
- !actuatorStore.isSaaSMode && hasWorkspacePermissionV2("bb.users.update")
- );
-});
-
-// Only users with bb.users.updateEmail permission can change email.
-const allowEditEmail = computed(() => {
- return hasWorkspacePermissionV2("bb.users.updateEmail");
-});
-
-const allowSaveEdit = computed(() => {
- return (
- !isEqual(user.value, state.editingUser) &&
- !userPasswordRef.value?.passwordHint &&
- !userPasswordRef.value?.passwordMismatch
- );
-});
-
-useRouteChangeGuard(computed(() => state.editing && allowSaveEdit.value));
-
-const updateUser = <K extends keyof User>(field: K, value: User[K]) => {
- if (!state.editingUser) return;
-
- state.editingUser[field] = value;
-};
-
-const editUser = () => {
- state.editingUser = cloneDeep(user.value);
- state.editing = true;
- state.passwordConfirm = "";
-
- nextTick(() => editNameTextField.value?.focus());
-};
-
-const cancelEdit = () => {
- state.editingUser = undefined;
- state.editing = false;
-};
-
-const saveEdit = async () => {
- const userPatch = state.editingUser;
- if (!userPatch) return;
-
- const emailChanged = userPatch.email !== user.value.email;
- const updateMaskPaths: string[] = [];
-
- if (userPatch.title !== user.value.title) {
- updateMaskPaths.push("title");
- }
- if (userPatch.phone !== user.value.phone) {
- updateMaskPaths.push("phone");
- }
- if (userPatch.password !== "") {
- updateMaskPaths.push("password");
- }
-
- state.saving = true;
- try {
- // Update email using dedicated UpdateEmail API if changed
- if (emailChanged) {
- const oldEmail = user.value.email;
- const updatedUser = await userStore.updateEmail(
- oldEmail,
- userPatch.email
- );
- migrateUserStorage(oldEmail, userPatch.email);
- if (isSelf.value) {
- authStore.updateCurrentUserNameForEmailChange(updatedUser.name);
- }
- }
-
- // Update other fields using UpdateUser API if any changed
- if (updateMaskPaths.length > 0) {
- await userStore.updateUser(
- create(UpdateUserRequestSchema, {
- user: userPatch,
- updateMask: create(FieldMaskSchema, {
- paths: updateMaskPaths,
- }),
- regenerateRecoveryCodes: false,
- regenerateTempMfaSecret: false,
- })
- );
- }
-
- if (emailChanged || updateMaskPaths.length > 0) {
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- }
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: (error as ConnectError).message || "Failed to update user",
- });
- return;
- } finally {
- state.saving = false;
- }
-
- state.editingUser = undefined;
- state.editing = false;
-
- // If we update email, we need to redirect to the new email.
- if (emailChanged && props.principalEmail) {
- router.replace({
- name: WORKSPACE_ROUTE_USER_PROFILE,
- params: {
- principalEmail: userPatch.email,
- },
- });
- }
-};
-
-const enable2FA = () => {
- if (!has2FAFeature.value) {
- state.showFeatureModal = true;
- return;
- }
- router.push({ name: SETTING_ROUTE_PROFILE_TWO_FACTOR });
-};
-
-const disable2FA = () => {
- if (
- settingV1Store.workspaceProfile.require2fa &&
- !hasWorkspacePermissionV2("bb.policies.update")
- ) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: t("two-factor.messages.cannot-disable"),
- });
- } else {
- state.showDisable2FAConfirmModal = true;
- }
-};
-
-const handleDisable2FA = async () => {
- await userStore.updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: user.value.name,
- mfaEnabled: false,
- },
- updateMask: create(FieldMaskSchema, {
- paths: ["mfa_enabled"],
- }),
- })
- );
- state.showDisable2FAConfirmModal = false;
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("two-factor.messages.2fa-disabled"),
- });
-};
-
-const dropDownOptions = computed((): DropdownOption[] => [
- {
- label: t("common.regenerate"),
- key: "regenerate",
- props: {
- onClick: () => {
- state.showRegenerateRecoveryCodesView = true;
- },
- },
- },
-]);
-
-watch(
- () => user.value.title,
- (title) => {
- setDocumentTitle(title);
- },
- { immediate: true }
-);
-</script>
diff --git a/frontend/src/views/TwoFactorRequired.vue b/frontend/src/views/TwoFactorRequired.vue
index f3a12903e0..f9359680f5 100644
--- a/frontend/src/views/TwoFactorRequired.vue
+++ b/frontend/src/views/TwoFactorRequired.vue
@@ -4,19 +4,31 @@
{{ $t("two-factor.messages.2fa-required") }}
</BBAttention>
<div class="w-full p-2 sm:p-8 sm:px-16">
- <TwoFactorSetup :cancel-action="handleSetupCancel" />
+ <div ref="container" />
</div>
</div>
</template>
<script lang="ts" setup>
+import { onMounted, onUnmounted, ref } from "vue";
import { BBAttention } from "@/bbkit";
import { useAuthStore } from "@/store";
-import TwoFactorSetup from "./TwoFactorSetup.vue";
const authStore = useAuthStore();
+const container = ref<HTMLElement>();
+// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
+let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any
-const handleSetupCancel = () => {
- authStore.logout();
-};
+onMounted(async () => {
+ if (!container.value) return;
+ const { mountReactPage } = await import("@/react/mount");
+ root = await mountReactPage(container.value, "TwoFactorSetupPage", {
+ cancelAction: () => authStore.logout(),
+ });
+});
+
+onUnmounted(() => {
+ root?.unmount();
+ root = null;
+});
</script>
diff --git a/frontend/src/views/TwoFactorSetup.vue b/frontend/src/views/TwoFactorSetup.vue
deleted file mode 100644
index e31c3656f0..0000000000
--- a/frontend/src/views/TwoFactorSetup.vue
+++ /dev/null
@@ -1,351 +0,0 @@
-<template>
- <div class="px-4 py-4">
- <p class="text-sm text-gray-500 mb-4">
- {{ $t("two-factor.description") }}
- <LearnMoreLink
- url="https://docs.bytebase.com/administration/2fa?source=console"
- />
- </p>
- <StepTab
- class="mb-8"
- :step-list="stepTabList"
- :allow-next="allowNext"
- :finish-title="$t('two-factor.setup-steps.recovery-codes-saved')"
- :current-index="state.currentStep"
- @update:current-index="tryChangeStep"
- @finish="tryFinishSetup"
- @cancel="cancelSetup"
- >
- <template #0>
- <div
- class="w-full max-w-2xl mx-auto flex flex-col justify-start items-start gap-y-4 my-8"
- >
- <p>
- {{ $t("two-factor.setup-steps.setup-auth-app.description") }}
- </p>
- <div
- :class="[
- 'w-full border rounded-md p-3',
- state.isExpired || state.isExpiringSoon
- ? 'bg-red-50 border-red-200'
- : 'bg-yellow-50 border-yellow-200',
- ]"
- >
- <div class="flex items-center justify-between">
- <p
- :class="[
- 'text-sm',
- state.isExpired || state.isExpiringSoon
- ? 'text-red-800'
- : 'text-yellow-800',
- ]"
- >
- ⏱️
- {{
- state.isExpired
- ? $t("two-factor.setup-steps.setup-auth-app.expired-notice")
- : $t("two-factor.setup-steps.setup-auth-app.time-remaining", {
- time: state.timeRemaining,
- })
- }}
- </p>
- <button
- v-if="state.isExpired"
- type="button"
- class="ml-3 px-3 py-1 text-sm font-medium text-white bg-blue-600 rounded-sm hover:bg-blue-700"
- @click="handleRegenerateSecret"
- >
- {{ $t("two-factor.setup-steps.setup-auth-app.regenerate") }}
- </button>
- </div>
- </div>
- <p class="text-2xl">
- {{ $t("two-factor.setup-steps.setup-auth-app.scan-qr-code.self") }}
- </p>
- <p>
- <i18n-t
- keypath="two-factor.setup-steps.setup-auth-app.scan-qr-code.description"
- >
- <template #action>
- <span
- :class="
- !state.showSecretModal && 'cursor-pointer text-blue-600'
- "
- @click="state.showSecretModal = true"
- >{{
- $t(
- "two-factor.setup-steps.setup-auth-app.scan-qr-code.enter-the-text"
- )
- }}</span
- >
- </template>
- </i18n-t>
- </p>
- <div class="w-full flex flex-col justify-center items-center pb-8">
- <NQrCode :value="otpauthUrl" :size="150" :padding="0" />
- <span class="mt-4 mb-2 text-sm font-medium">{{
- $t("two-factor.setup-steps.setup-auth-app.verify-code")
- }}</span>
- <NInputOtp
- v-model:value="state.otpCodes"
- @finish="onOtpCodeFinish"
- />
- </div>
- </div>
- </template>
- <template #1>
- <div class="w-full max-w-2xl mx-auto">
- <RecoveryCodesView
- :recovery-codes="currentUser.tempRecoveryCodes"
- @download="state.recoveryCodesDownloaded = true"
- />
- </div>
- </template>
- </StepTab>
-
- <TwoFactorSecretModal
- v-if="state.showSecretModal"
- :secret="currentUser.tempOtpSecret"
- @close="state.showSecretModal = false"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import type { ConnectError } from "@connectrpc/connect";
-import { NInputOtp, NQrCode } from "naive-ui";
-import { computed, onMounted, onUnmounted, reactive } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import LearnMoreLink from "@/components/LearnMoreLink.vue";
-import RecoveryCodesView from "@/components/RecoveryCodesView.vue";
-import TwoFactorSecretModal from "@/components/TwoFactorSecretModal.vue";
-import { StepTab } from "@/components/v2";
-import { AUTH_2FA_SETUP_MODULE } from "@/router/auth";
-import { SETTING_ROUTE_PROFILE } from "@/router/dashboard/workspaceSetting";
-import { pushNotification, useCurrentUserV1, useUserStore } from "@/store";
-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
-
-const issuerName = "Bytebase";
-const digits = 6;
-
-const SETUP_AUTH_APP_STEP = 0;
-const DOWNLOAD_RECOVERY_CODES_STEP = 1;
-
-type Step = typeof SETUP_AUTH_APP_STEP | typeof DOWNLOAD_RECOVERY_CODES_STEP;
-
-interface LocalState {
- currentStep: Step;
- showSecretModal: boolean;
- otpCodes: string[];
- recoveryCodesDownloaded: boolean;
- timeRemaining: string;
- isExpired: boolean;
- isExpiringSoon: boolean;
-}
-
-const props = defineProps<{
- cancelAction?: () => void;
-}>();
-
-const { t } = useI18n();
-const router = useRouter();
-const userStore = useUserStore();
-const state = reactive<LocalState>({
- currentStep: SETUP_AUTH_APP_STEP,
- showSecretModal: false,
- otpCodes: [],
- recoveryCodesDownloaded: false,
- timeRemaining: "5:00",
- isExpired: false,
- isExpiringSoon: false,
-});
-const currentUser = useCurrentUserV1();
-const MFA_TEMP_SECRET_EXPIRATION = 5 * 60 * 1000; // 5 minutes in milliseconds
-let countdownInterval: ReturnType<typeof setInterval> | null = null;
-
-const stepTabList = computed(() => {
- return [
- { title: t("two-factor.setup-steps.setup-auth-app.self") },
- { title: t("two-factor.setup-steps.download-recovery-codes.self") },
- ];
-});
-
-const allowNext = computed(() => {
- if (state.currentStep === SETUP_AUTH_APP_STEP) {
- return (
- state.otpCodes.filter((v) => v).length === digits && !state.isExpired
- );
- } else {
- return state.recoveryCodesDownloaded;
- }
-});
-
-const updateCountdown = () => {
- if (!currentUser.value.tempOtpSecretCreatedTime) {
- state.isExpired = true;
- state.timeRemaining = "0:00";
- return;
- }
-
- const createdAt =
- Number(currentUser.value.tempOtpSecretCreatedTime.seconds) * 1000;
- const now = Date.now();
- const elapsed = now - createdAt;
- const remaining = MFA_TEMP_SECRET_EXPIRATION - elapsed;
-
- if (remaining <= 0) {
- state.isExpired = true;
- state.timeRemaining = "0:00";
- state.isExpiringSoon = false;
- if (countdownInterval) {
- clearInterval(countdownInterval);
- countdownInterval = null;
- }
- } else {
- state.isExpired = false;
- const minutes = Math.floor(remaining / 60000);
- const seconds = Math.floor((remaining % 60000) / 1000);
- state.timeRemaining = `${minutes}:${seconds.toString().padStart(2, "0")}`;
- state.isExpiringSoon = remaining < 60000; // Less than 1 minute
- }
-};
-
-const startCountdown = () => {
- updateCountdown();
- if (countdownInterval) {
- clearInterval(countdownInterval);
- }
- countdownInterval = setInterval(updateCountdown, 1000);
-};
-
-const handleRegenerateSecret = async () => {
- state.otpCodes = [];
- await regenerateTempMfaSecret();
- startCountdown();
-};
-
-onMounted(async () => {
- await regenerateTempMfaSecret();
- startCountdown();
-});
-
-onUnmounted(() => {
- if (countdownInterval) {
- clearInterval(countdownInterval);
- countdownInterval = null;
- }
-});
-
-const regenerateTempMfaSecret = async () => {
- await userStore.updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.value.name,
- },
- updateMask: create(FieldMaskSchema, {
- paths: [],
- }),
- regenerateTempMfaSecret: true,
- })
- );
-};
-
-const verifyOTPCode = async () => {
- try {
- await userStore.updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.value.name,
- },
- updateMask: create(FieldMaskSchema, {
- paths: [],
- }),
- otpCode: state.otpCodes.join(""),
- })
- );
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: (error as ConnectError).message,
- });
- return false;
- }
- return true;
-};
-
-const cancelSetup = () => {
- if (props.cancelAction) {
- props.cancelAction();
- } else {
- router.replace({
- name: SETTING_ROUTE_PROFILE,
- });
- }
-};
-
-const onOtpCodeFinish = async (value: string[]) => {
- state.otpCodes = value;
- const result = await verifyOTPCode();
- if (result && state.currentStep === SETUP_AUTH_APP_STEP) {
- state.currentStep++;
- }
-};
-
-const tryChangeStep = async (nextStepIndex: number) => {
- switch (nextStepIndex) {
- case DOWNLOAD_RECOVERY_CODES_STEP: {
- const result = await verifyOTPCode();
- if (!result) {
- return;
- }
- break;
- }
- case SETUP_AUTH_APP_STEP:
- state.otpCodes = [];
- break;
- default:
- break;
- }
- state.currentStep = nextStepIndex as Step;
-};
-
-const tryFinishSetup = async () => {
- await userStore.updateUser(
- create(UpdateUserRequestSchema, {
- user: {
- name: currentUser.value.name,
- mfaEnabled: true,
- },
- updateMask: create(FieldMaskSchema, {
- paths: ["mfa_enabled"],
- }),
- })
- );
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("two-factor.messages.2fa-enabled"),
- });
-
- // When user is on the 2fa.setup page, we'd like to redirect to the home page.
- // Only happens when the workspace level 2fa-setup is enabled.
- if (router.currentRoute.value.name === AUTH_2FA_SETUP_MODULE) {
- router.replace({
- path: "/",
- });
- } else {
- router.replace({
- name: SETTING_ROUTE_PROFILE,
- });
- }
-};
-
-const otpauthUrl = computed(
- () =>
- `otpauth://totp/${issuerName}:${currentUser.value.email}?algorithm=SHA1&digits=${digits}&issuer=${issuerName}&period=30&secret=${currentUser.value.tempOtpSecret}`
-);
-</script>