Skip to content

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

feat(frontend): workspace settings for access control feature (#3633)

Liu Jib95e41c80eb4
diff --git a/frontend/src/components/AccessControl/AddRuleForm.vue b/frontend/src/components/AccessControl/AddRuleForm.vue
new file mode 100644
index 0000000000..1f773d2d6a
--- /dev/null
+++ b/frontend/src/components/AccessControl/AddRuleForm.vue
@@ -0,0 +1,227 @@
+<template>
+ <div class="w-160 space-y-2 relative">
+ <div>
+ <BBTableSearch
+ class="w-60"
+ :placeholder="$t('database.search-database-name')"
+ @change-text="(text: string) => (state.searchText = text)"
+ />
+ </div>
+
+ <DatabaseTable
+ mode="ALL_TINY"
+ :bordered="true"
+ :custom-click="true"
+ :database-list="databaseList"
+ :show-selection-column="true"
+ @select-database="
+ (db: Database) => toggleDatabaseSelection(db, !isDatabaseSelected(db))
+ "
+ >
+ <template #selection-all="{ databaseList: renderedDatabaseList }">
+ <input
+ v-if="renderedDatabaseList.length > 0"
+ type="checkbox"
+ class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
+ v-bind="getAllSelectionState(renderedDatabaseList)"
+ @input="
+ toggleAllDatabasesSelection(
+ renderedDatabaseList,
+ ($event.target as HTMLInputElement).checked
+ )
+ "
+ />
+ </template>
+ <template #selection="{ database }">
+ <input
+ type="checkbox"
+ class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
+ :checked="isDatabaseSelected(database)"
+ @input="(e: any) => toggleDatabaseSelection(database, e.target.checked)"
+ />
+ </template>
+ </DatabaseTable>
+
+ <div
+ v-if="!state.isLoading && databaseList.length === 0"
+ class="w-full flex flex-col py-6 justify-start items-center"
+ >
+ <heroicons-outline:inbox class="w-12 h-auto text-gray-500" />
+ <span class="text-sm leading-6 text-gray-500">{{
+ $t("common.no-data")
+ }}</span>
+ </div>
+
+ <div class="flex items-center justify-between">
+ <div class="textinfolabel">
+ <template v-if="state.selectedDatabaseIdList.size > 0">
+ {{
+ $t("database.selected-n-databases", {
+ n: state.selectedDatabaseIdList.size,
+ })
+ }}
+ </template>
+ </div>
+ <div class="flex items-center gap-x-2">
+ <button class="btn-normal" @click="$emit('cancel')">
+ {{ $t("common.cancel") }}
+ </button>
+ <button class="btn-primary" :disabled="!allowAdd" @click="tryAdd">
+ {{ $t("common.add") }}
+ </button>
+ </div>
+ </div>
+
+ <div
+ v-if="state.isLoading"
+ class="absolute w-full h-full inset-0 bg-white/50 flex flex-col items-center justify-center"
+ >
+ <BBSpin />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, PropType, reactive } from "vue";
+
+import type { Database, DatabaseId, Policy } from "@/types";
+import {
+ useDatabaseStore,
+ useEnvironmentStore,
+ useInstanceStore,
+} from "@/store";
+import { flatten } from "lodash-es";
+
+type LocalState = {
+ isLoading: boolean;
+ searchText: string;
+ databaseList: Database[];
+ selectedDatabaseIdList: Set<DatabaseId>;
+};
+
+const props = defineProps({
+ policyList: {
+ type: Array as PropType<Policy[]>,
+ default: () => [],
+ },
+});
+
+const emit = defineEmits<{
+ (e: "cancel"): void;
+ (e: "add", databaseList: Database[]): void;
+}>();
+
+const state = reactive<LocalState>({
+ isLoading: false,
+ searchText: "",
+ databaseList: [],
+ selectedDatabaseIdList: new Set(),
+});
+
+const environmentStore = useEnvironmentStore();
+const instanceStore = useInstanceStore();
+const databaseStore = useDatabaseStore();
+
+const prepareList = async () => {
+ state.isLoading = true;
+
+ // TODO: the server-side can't return all database list while calling
+ // [GET] /api/database
+ // So we need to call /api/database?instance={instance_id}
+ // for each instance in all protected environments
+ // respectively and combine the results.
+
+ const environmentList = environmentStore
+ .getEnvironmentList()
+ .filter((env) => env.tier === "PROTECTED");
+
+ await instanceStore.fetchInstanceList();
+ const instanceList = environmentList.flatMap((env) =>
+ instanceStore.getInstanceListByEnvironmentId(env.id)
+ );
+
+ const allDatabaseList = await Promise.all(
+ instanceList.map((instance) => {
+ return databaseStore.fetchDatabaseListByInstanceId(instance.id);
+ })
+ );
+ state.databaseList = flatten(allDatabaseList).filter(
+ (db) => db.instance.environment.tier === "PROTECTED"
+ );
+ state.isLoading = false;
+};
+
+const presetDatabaseIdList = computed(() => {
+ const databaseIdList = props.policyList.map(
+ (policy) => policy.resourceId as DatabaseId
+ );
+ return new Set(databaseIdList);
+});
+
+const databaseList = computed(() => {
+ // Don't show the databases already have access control policy.
+ let list = state.databaseList.filter(
+ (db) => !presetDatabaseIdList.value.has(db.id)
+ );
+
+ const keyword = state.searchText.trim();
+ if (keyword) {
+ list = list.filter((db) => db.name.toLowerCase().includes(keyword));
+ }
+ return list;
+});
+
+const allowAdd = computed(() => {
+ return state.selectedDatabaseIdList.size > 0;
+});
+
+const tryAdd = () => {
+ const selectedDatabaseList = databaseList.value.filter((db) =>
+ isDatabaseSelected(db)
+ );
+ emit("add", selectedDatabaseList);
+};
+
+const toggleDatabaseSelection = (database: Database, on: boolean) => {
+ if (on) {
+ state.selectedDatabaseIdList.add(database.id);
+ } else {
+ state.selectedDatabaseIdList.delete(database.id);
+ }
+};
+
+const isDatabaseSelected = (database: Database) => {
+ return state.selectedDatabaseIdList.has(database.id);
+};
+
+const getAllSelectionState = (
+ databaseList: Database[]
+): { checked: boolean; indeterminate: boolean } => {
+ const checked = databaseList.every((db) => isDatabaseSelected(db));
+ const indeterminate =
+ !checked && databaseList.some((db) => isDatabaseSelected(db));
+
+ return {
+ checked,
+ indeterminate,
+ };
+};
+
+const toggleAllDatabasesSelection = (
+ databaseList: Database[],
+ on: boolean
+): void => {
+ const set = state.selectedDatabaseIdList;
+ if (on) {
+ databaseList.forEach((db) => {
+ set.add(db.id);
+ });
+ } else {
+ databaseList.forEach((db) => {
+ set.delete(db.id);
+ });
+ }
+};
+
+prepareList();
+</script>
diff --git a/frontend/src/components/DatabaseTable.vue b/frontend/src/components/DatabaseTable.vue
index 8930b294ab..ee6e20036b 100644
--- a/frontend/src/components/DatabaseTable.vue
+++ b/frontend/src/components/DatabaseTable.vue
@@ -77,7 +77,7 @@
</NTooltip>
</div>
</BBTableCell>
- <BBTableCell class="w-[10%]">
+ <BBTableCell v-if="showSchemaVersionColumn" class="w-[10%]">
{{ database.schemaVersion }}
</BBTableCell>
<BBTableCell v-if="showProjectColumn" class="w-[15%]">
@@ -236,7 +236,13 @@ import { BBTableColumn } from "../bbkit/types";
import InstanceEngineIcon from "./InstanceEngineIcon.vue";
import TenantIcon from "./TenantIcon.vue";
-type Mode = "ALL" | "ALL_SHORT" | "INSTANCE" | "PROJECT" | "PROJECT_SHORT";
+type Mode =
+ | "ALL"
+ | "ALL_SHORT"
+ | "ALL_TINY"
+ | "INSTANCE"
+ | "PROJECT"
+ | "PROJECT_SHORT";
interface State {
showIncorrectProjectModal: boolean;
@@ -363,6 +369,23 @@ const columnListMap = computed(() => {
},
],
],
+ [
+ "ALL_TINY",
+ [
+ {
+ title: t("common.name"),
+ },
+ {
+ title: t("common.project"),
+ },
+ {
+ title: t("common.environment"),
+ },
+ {
+ title: t("common.instance"),
+ },
+ ],
+ ],
[
"INSTANCE",
[
@@ -422,6 +445,10 @@ const columnListMap = computed(() => {
]);
});
+const showSchemaVersionColumn = computed(() => {
+ return props.mode !== "ALL_TINY";
+});
+
const showInstanceColumn = computed(() => {
return props.mode != "INSTANCE";
});
@@ -435,7 +462,14 @@ const showEnvironmentColumn = computed(() => {
});
const showMiscColumn = computed(() => {
- return props.mode != "ALL_SHORT" && props.mode != "PROJECT_SHORT";
+ if (
+ props.mode === "ALL_SHORT" ||
+ props.mode === "ALL_TINY" ||
+ props.mode === "PROJECT_SHORT"
+ ) {
+ return false;
+ }
+ return true;
});
const columnList = computed(() => {
@@ -447,7 +481,11 @@ const columnList = computed(() => {
});
const showSQLEditorLink = computed(() => {
- if (props.mode == "ALL_SHORT" || props.mode == "PROJECT_SHORT") {
+ if (
+ props.mode === "ALL_SHORT" ||
+ props.mode === "ALL_TINY" ||
+ props.mode === "PROJECT_SHORT"
+ ) {
return false;
}
return true;
diff --git a/frontend/src/components/EnvironmentForm.vue b/frontend/src/components/EnvironmentForm.vue
index 57840122ef..5620dcb9ac 100644
--- a/frontend/src/components/EnvironmentForm.vue
+++ b/frontend/src/components/EnvironmentForm.vue
@@ -25,10 +25,12 @@
class="text-accent"
/>
</label>
- <p class="mt-2 text-sm flex items-center text-gray-600">
- {{ $t("policy.environment-tier.description") }}
+ <p class="mt-2 text-sm text-gray-600">
+ <i18n-t tag="span" keypath="policy.environment-tier.description">
+ <template #newline><br /></template>
+ </i18n-t>
<a
- class="flex items-center text-blue-600 ml-1 hover:underline"
+ class="inline-flex items-center text-blue-600 ml-1 hover:underline"
href="https://www.bytebase.com/docs/administration/environment-policy/tier"
target="_blank"
>{{ $t("common.learn-more")
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 8869e72a4d..f5a82099da 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -332,7 +332,8 @@
"subscription": "Subscription",
"labels": "Labels",
"debug-log": "Debug Log",
- "sensitive-data": "Sensitive Data"
+ "sensitive-data": "Sensitive Data",
+ "access-control": "Access Control"
},
"profile": {
"email": "Email",
@@ -413,6 +414,11 @@
"sensitive-data": {
"description": "The query result of the following columns is displayed as \"******\". \nYou can mark more columns as sensitive data on the table details page.",
"remove-sensitive-column-tips": "Expose this column?"
+ },
+ "access-control": {
+ "description": "Allow developers to execute queries for the following databases in the protected environments from SQL Editor.",
+ "add-rule": "Add rule",
+ "remove-policy-tips": "Remove this rule?"
}
},
"activity": {
@@ -804,7 +810,7 @@
},
"environment-tier": {
"name": "Environment tier",
- "description": "The environment will appear differently from other environments.",
+ "description": "The environment will appear differently from other environments.{newline}Developers cannot execute any query on this environment's databases \nusing SQL Editor by default. ",
"mark-env-as-protected": "Mark as protected environment"
}
},
@@ -1468,6 +1474,10 @@
"title": "Sensitive data",
"desc": "Mark table columns as sensitive data and the query result of them will be displayed as \"******\"."
},
+ "bb-feature-access-control": {
+ "title": "Access control",
+ "desc": "Change query permission for databases in the protected environments."
+ },
"bb-feature-lgtm": {
"title": "LGTM check",
"desc": "Check if the issue has an \"LGTM\" comment."
diff --git a/frontend/src/locales/subscription/en-US.json b/frontend/src/locales/subscription/en-US.json
index cdf1bbf5e5..6e3da7ffdf 100644
--- a/frontend/src/locales/subscription/en-US.json
+++ b/frontend/src/locales/subscription/en-US.json
@@ -108,7 +108,8 @@
"dba-workflow": "DBA workflow",
"dba-workflow-tooltip": "Only allow DBA and Owner to create or transfer database",
"environment-tier": "Environment tier",
- "sensitive-data": "Sensitive data masking"
+ "sensitive-data": "Sensitive data masking",
+ "access-control": "Access control"
}
},
"branding": {
diff --git a/frontend/src/locales/subscription/zh-CN.json b/frontend/src/locales/subscription/zh-CN.json
index 240a512455..7a42d279f4 100644
--- a/frontend/src/locales/subscription/zh-CN.json
+++ b/frontend/src/locales/subscription/zh-CN.json
@@ -108,7 +108,8 @@
"dba-workflow": "DBA 工作流",
"dba-workflow-tooltip": "仅允许 DBA 和所有者创建或者转移数据库",
"environment-tier": "环境分级",
- "sensitive-data": "数据脱敏"
+ "sensitive-data": "数据脱敏",
+ "access-control": "访问控制"
}
},
"branding": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index f3a7965fa2..a05e212d94 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -332,7 +332,8 @@
"subscription": "订阅",
"labels": "标签",
"debug-log": "Debug 日志",
- "sensitive-data": "敏感数据"
+ "sensitive-data": "敏感数据",
+ "access-control": "访问控制"
},
"profile": {
"email": "邮箱",
@@ -413,6 +414,11 @@
"sensitive-data": {
"description": "以下列的查询结果将会被显示为 \"******\"。在表详情页,你可以将多个列标记为敏感数据。",
"remove-sensitive-column-tips": "不再对此列数据脱敏?"
+ },
+ "access-control": {
+ "description": "允许开发者通过 SQL 编辑器对下列受保护环境中的数据库执行查询。",
+ "add-rule": "添加规则",
+ "remove-policy-tips": "删除这条规则?"
}
},
"activity": {
@@ -804,7 +810,7 @@
},
"environment-tier": {
"name": "环境级别",
- "description": "使该环境在显示上不同于其他环境。",
+ "description": "使该环境在显示上不同于其他环境。{newline}默认情况下,开发者无法通过 SQL 编辑器在这个环境的数据库上执行任何查询。",
"mark-env-as-protected": "标记为受保护的环境"
}
},
@@ -1468,6 +1474,10 @@
"title": "敏感数据",
"desc": "将数据表的列标记为敏感数据,它们在查询结果中将会被显示成 \"******\"。"
},
+ "bb-feature-access-control": {
+ "title": "访问控制",
+ "desc": "可以修改受保护的环境中的数据库的查询权限。"
+ },
"bb-feature-lgtm": {
"title": "LGTM 检查",
"desc": "检查工单是否有 \"LGTM\" 评论。"
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index bd30d11980..5e1eb15dfc 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -360,6 +360,14 @@ const routes: Array<RouteRecordRaw> = [
import("../views/SettingWorkspaceSensitiveData.vue"),
props: true,
},
+ {
+ path: "access-control",
+ name: "setting.workspace.access-control",
+ meta: { title: () => t("settings.sidebar.access-control") },
+ component: () =>
+ import("../views/SettingWorkspaceAccessControl.vue"),
+ props: true,
+ },
{
path: "version-control",
name: "setting.workspace.version-control",
diff --git a/frontend/src/types/plan.ts b/frontend/src/types/plan.ts
index 961db4ea24..e9983947cc 100644
--- a/frontend/src/types/plan.ts
+++ b/frontend/src/types/plan.ts
@@ -27,7 +27,8 @@ export type FeatureType =
| "bb.feature.approval-policy"
| "bb.feature.backup-policy"
| "bb.feature.environment-tier-policy"
- | "bb.feature.sensitive-data";
+ | "bb.feature.sensitive-data"
+ | "bb.feature.access-control";
export enum PlanType {
FREE = 0,
@@ -104,6 +105,7 @@ export const FEATURE_MATRIX: Map<FeatureType, boolean[]> = new Map([
["bb.feature.backup-policy", [false, true, true]],
["bb.feature.environment-tier-policy", [false, false, true]],
["bb.feature.sensitive-data", [false, false, true]],
+ ["bb.feature.access-control", [false, false, true]],
]);
export const FEATURE_SECTIONS: { type: string; featureList: string[] }[] =
diff --git a/frontend/src/types/plan.yaml b/frontend/src/types/plan.yaml
index 74d1bd32bc..ed208eef76 100644
--- a/frontend/src/types/plan.yaml
+++ b/frontend/src/types/plan.yaml
@@ -30,6 +30,7 @@ categoryList:
- dba-workflow
- environment-tier
- sensitive-data
+ - access-control
- type: branding
featureList:
- branding-logo
@@ -172,6 +173,7 @@ planList:
tooltip: dba-workflow-tooltip
- type: environment-tier
- type: sensitive-data
+ - type: access-control
- type: branding-logo
mainFeatureList:
- sla
diff --git a/frontend/src/types/policy.ts b/frontend/src/types/policy.ts
index 89f2e8ed10..5669cf1139 100644
--- a/frontend/src/types/policy.ts
+++ b/frontend/src/types/policy.ts
@@ -132,6 +132,6 @@ export type PolicyUpsert = {
rowStatus?: RowStatus;
// Domain specific fields
- inheritFromParent: boolean;
+ inheritFromParent?: boolean;
payload?: PolicyPayload;
};
diff --git a/frontend/src/utils/role.ts b/frontend/src/utils/role.ts
index addb094aa0..6fb75ca29d 100644
--- a/frontend/src/utils/role.ts
+++ b/frontend/src/utils/role.ts
@@ -15,6 +15,7 @@ export type WorkspacePermissionType =
| "bb.permission.workspace.manage-vcs-provider"
| "bb.permission.workspace.manage-general"
| "bb.permission.workspace.manage-sensitive-data"
+ | "bb.permission.workspace.manage-access-control"
// Can execute admininstrive queries such as "SHOW PROCESSLIST"
| "bb.permission.workspace.admin-sql-editor";
@@ -36,6 +37,7 @@ export const WORKSPACE_PERMISSION_MATRIX: Map<
["bb.permission.workspace.manage-general", [false, false, true]],
["bb.permission.workspace.manage-im-integration", [false, false, true]],
["bb.permission.workspace.manage-sensitive-data", [false, true, true]],
+ ["bb.permission.workspace.manage-access-control", [false, true, true]],
["bb.permission.workspace.admin-sql-editor", [false, true, true]],
]);
diff --git a/frontend/src/views/SettingSidebar.vue b/frontend/src/views/SettingSidebar.vue
index 5e59f36101..447f72f6f7 100644
--- a/frontend/src/views/SettingSidebar.vue
+++ b/frontend/src/views/SettingSidebar.vue
@@ -74,6 +74,13 @@
>
{{ $t("settings.sidebar.sensitive-data") }}
</router-link>
+ <router-link
+ v-if="showAccessControlItem"
+ to="/setting/access-control"
+ class="outline-item group w-full flex items-center truncate pl-11 pr-2 py-2"
+ >
+ {{ $t("settings.sidebar.access-control") }}
+ </router-link>
<router-link
v-if="showIMIntegrationItem"
to="/setting/im-integration"
@@ -151,6 +158,13 @@ const showSensitiveDataItem = computed((): boolean => {
);
});
+const showAccessControlItem = computed((): boolean => {
+ return hasWorkspacePermission(
+ "bb.permission.workspace.manage-access-control",
+ currentUser.value.role
+ );
+});
+
const showIMIntegrationItem = computed((): boolean => {
return hasWorkspacePermission(
"bb.permission.workspace.manage-im-integration",
diff --git a/frontend/src/views/SettingWorkspaceAccessControl.vue b/frontend/src/views/SettingWorkspaceAccessControl.vue
new file mode 100644
index 0000000000..c16217c514
--- /dev/null
+++ b/frontend/src/views/SettingWorkspaceAccessControl.vue
@@ -0,0 +1,304 @@
+<template>
+ <div class="w-full mt-4 space-y-4">
+ <div class="flex justify-between">
+ <div class="textinfolabel max-w-xl">
+ {{ $t("settings.access-control.description") }}
+ </div>
+
+ <div>
+ <button
+ class="btn-primary"
+ :disabled="!allowAdmin"
+ @click="state.showAddRuleModal = true"
+ >
+ {{ $t("settings.access-control.add-rule") }}
+ </button>
+ </div>
+ </div>
+
+ <div class="relative min-h-[12rem]">
+ <BBTable
+ :column-list="COLUMN_LIST"
+ :data-source="state.policyList"
+ :show-header="true"
+ :left-bordered="true"
+ :right-bordered="true"
+ :row-clickable="false"
+ >
+ <template #body="{ rowData: policy }: { rowData: Policy }">
+ <BBTableCell class="w-[1%] pl-4 pr-0">
+ <!-- w-[1%] means as narrow as possible -->
+ <BBSwitch
+ :disabled="!allowAdmin"
+ :value="policy.rowStatus === 'NORMAL'"
+ @toggle="handleToggleEnabled(policy, $event)"
+ />
+ </BBTableCell>
+ <BBTableCell class="w-[15%]">
+ <div class="flex items-center space-x-2">
+ <span>{{ databaseOfPolicy(policy).name }}</span>
+ </div>
+ </BBTableCell>
+ <BBTableCell class="w-[15%]">
+ <div class="flex flex-row items-center space-x-1">
+ <InstanceEngineIcon
+ :instance="databaseOfPolicy(policy).instance"
+ />
+ <span class="flex-1 whitespace-pre-wrap">
+ {{ instanceName(databaseOfPolicy(policy).instance) }}
+ </span>
+ </div>
+ </BBTableCell>
+ <BBTableCell class="w-[10%]">
+ <div class="flex items-center">
+ {{
+ environmentName(databaseOfPolicy(policy).instance.environment)
+ }}
+ <ProtectedEnvironmentIcon
+ class="ml-1"
+ :environment="databaseOfPolicy(policy).instance.environment"
+ />
+ </div>
+ </BBTableCell>
+ <BBTableCell class="w-[15%]">
+ {{ projectName(databaseOfPolicy(policy).project) }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ humanizeTs(policy.updatedTs) }}
+ </BBTableCell>
+ <BBTableCell>
+ <div class="flex items-center justify-center">
+ <NPopconfirm @positive-click="handleRemove(policy)">
+ <template #trigger>
+ <button
+ :disabled="!allowAdmin"
+ class="w-5 h-5 p-0.5 bg-white hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"
+ >
+ <heroicons-outline:trash />
+ </button>
+ </template>
+
+ <div class="whitespace-nowrap">
+ {{ $t("settings.access-control.remove-policy-tips") }}
+ </div>
+ </NPopconfirm>
+ </div>
+ </BBTableCell>
+ </template>
+ </BBTable>
+
+ <div
+ v-if="!state.isLoading && state.policyList.length === 0"
+ class="w-full flex flex-col py-6 justify-start items-center"
+ >
+ <heroicons-outline:inbox class="w-12 h-auto text-gray-500" />
+ <span class="text-sm leading-6 text-gray-500">{{
+ $t("common.no-data")
+ }}</span>
+ </div>
+
+ <div
+ v-if="state.isLoading || state.isUpdating"
+ class="absolute w-full h-full inset-0 bg-white/50 flex flex-col items-center justify-center"
+ >
+ <BBSpin />
+ </div>
+ </div>
+ </div>
+
+ <FeatureModal
+ v-if="state.showFeatureModal"
+ feature="bb.feature.access-control"
+ @cancel="state.showFeatureModal = false"
+ />
+
+ <BBModal
+ v-if="state.showAddRuleModal"
+ :title="$t('settings.access-control.add-rule')"
+ @close="state.showAddRuleModal = false"
+ >
+ <AddRuleForm
+ :policy-list="state.policyList"
+ @cancel="state.showAddRuleModal = false"
+ @add="handleAddRule"
+ />
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { computed, reactive, watchEffect } from "vue";
+import { useI18n } from "vue-i18n";
+import { NPopconfirm } from "naive-ui";
+
+import {
+ featureToRef,
+ useCurrentUser,
+ useDatabaseStore,
+ usePolicyStore,
+} from "@/store";
+import {
+ AccessControlPolicyPayload,
+ Database,
+ DatabaseId,
+ Policy,
+ PolicyUpsert,
+} from "@/types";
+import { BBTableColumn } from "@/bbkit/types";
+import { hasWorkspacePermission } from "@/utils";
+import AddRuleForm from "@/components/AccessControl/AddRuleForm.vue";
+import { capitalize, uniq } from "lodash-es";
+
+interface LocalState {
+ showFeatureModal: boolean;
+ showAddRuleModal: boolean;
+ isLoading: boolean;
+ isUpdating: boolean;
+ policyList: Policy[];
+}
+
+const { t } = useI18n();
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+ showAddRuleModal: false,
+ isLoading: false,
+ isUpdating: false,
+ policyList: [],
+});
+const databaseStore = useDatabaseStore();
+const policyStore = usePolicyStore();
+const hasAccessControlFeature = featureToRef("bb.feature.access-control");
+
+const currentUser = useCurrentUser();
+const allowAdmin = computed(() => {
+ return hasWorkspacePermission(
+ "bb.permission.workspace.manage-access-control",
+ currentUser.value.role
+ );
+});
+
+const databaseOfPolicy = (policy: Policy) => {
+ return databaseStore.getDatabaseById(policy.resourceId as DatabaseId);
+};
+
+const prepareList = async () => {
+ state.isLoading = true;
+
+ await new Promise((resolve) => setTimeout(resolve, 500));
+
+ const policyList = await policyStore.fetchPolicyListByType(
+ "bb.policy.access-control"
+ );
+
+ const databaseIdList = uniq(
+ policyList.map((policy) => policy.resourceId as DatabaseId)
+ );
+
+ Promise.all(
+ databaseIdList.map((databaseId) =>
+ databaseStore.getOrFetchDatabaseById(databaseId)
+ )
+ );
+ state.policyList = policyList;
+
+ state.isLoading = false;
+};
+
+watchEffect(prepareList);
+
+const handleAddRule = async (databaseList: Database[]) => {
+ if (!hasAccessControlFeature.value) {
+ state.showFeatureModal = true;
+ return;
+ }
+
+ state.showAddRuleModal = false;
+ state.isUpdating = true;
+ try {
+ for (let i = 0; i < databaseList.length; i++) {
+ const database = databaseList[i];
+ const payload: AccessControlPolicyPayload = {
+ disallowRuleList: [],
+ };
+ const policyUpsert: PolicyUpsert = {
+ inheritFromParent: false,
+ payload,
+ };
+ await policyStore.upsertPolicyByDatabaseAndType({
+ databaseId: database.id,
+ type: "bb.policy.access-control",
+ policyUpsert,
+ });
+ }
+ } finally {
+ state.isUpdating = false;
+ }
+ prepareList();
+};
+
+const handleRemove = async (policy: Policy) => {
+ if (!hasAccessControlFeature.value) {
+ state.showFeatureModal = true;
+ return;
+ }
+
+ state.isUpdating = true;
+ try {
+ policyStore.deletePolicyByDatabaseAndType({
+ databaseId: policy.resourceId,
+ type: "bb.policy.access-control",
+ });
+
+ prepareList();
+ } finally {
+ state.isUpdating = false;
+ }
+};
+
+const handleToggleEnabled = async (policy: Policy, on: boolean) => {
+ if (!hasAccessControlFeature.value) {
+ state.showFeatureModal = true;
+ return;
+ }
+
+ try {
+ const rowStatus = on ? "NORMAL" : "ARCHIVED";
+ await policyStore.upsertPolicyByDatabaseAndType({
+ databaseId: policy.resourceId as DatabaseId,
+ type: "bb.policy.access-control",
+ policyUpsert: {
+ rowStatus,
+ },
+ });
+ policy.rowStatus = rowStatus;
+ } catch {
+ // nothing todo
+ }
+};
+
+const COLUMN_LIST = computed((): BBTableColumn[] => [
+ {
+ title: capitalize(t("common.enabled")),
+ },
+ {
+ title: t("common.database"),
+ },
+ {
+ title: t("common.project"),
+ },
+ {
+ title: t("common.environment"),
+ },
+ {
+ title: t("common.instance"),
+ },
+ {
+ title: t("common.updated-at"),
+ nowrap: true,
+ },
+ {
+ title: t("common.operation"),
+ center: true,
+ nowrap: true,
+ },
+]);
+</script>