Skip to content

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

Return the role together with the principal from the server.

天舟844a33d95384
diff --git a/api/principal.go b/api/principal.go
index 14d1c54860..8e638ef9f3 100644
--- a/api/principal.go
+++ b/api/principal.go
@@ -60,8 +60,9 @@ type Principal struct {
Email string `jsonapi:"attr,email"`
// No need to return to the client
PasswordHash string
- // From member
- Role Role
+ // Role is stored in the member table, but we include it when returning the principal.
+ // This simplifies the client code where it won't require order depenendency to fetch the related member info first.
+ Role Role `jsonapi:"attr,role"`
}
// Customize the Principal Marshal method so the returned object
diff --git a/frontend/src/App.vue b/frontend/src/App.vue
index 56bdd1a88f..1a3b974ebe 100644
--- a/frontend/src/App.vue
+++ b/frontend/src/App.vue
@@ -88,9 +88,6 @@ export default {
watchEffect(watchNotification);
- // Restore previously logged in user if applicable.
- store.dispatch("auth/restoreUser");
-
onErrorCaptured((e: any, _, info) => {
// If e has response, then we assume it's an http error and has already been
// handled by the axios global handler.
diff --git a/frontend/src/components/ProvideDashboardContext.vue b/frontend/src/components/ProvideDashboardContext.vue
index 006a687e0a..6dba8211ed 100644
--- a/frontend/src/components/ProvideDashboardContext.vue
+++ b/frontend/src/components/ProvideDashboardContext.vue
@@ -3,17 +3,20 @@
</template>
<script lang="ts">
+import { ComputedRef } from "@vue/reactivity";
import { useStore } from "vuex";
import { Principal, DEFAULT_PROJECT_ID } from "../types";
+import { computed } from "@vue/runtime-core";
export default {
name: "ProvideDashboardContext",
async setup() {
const store = useStore();
- await store.dispatch("member/fetchMemberList");
- // fetchPrincipalList relies on fetchMemberList to find the role of the principal.
- await store.dispatch("principal/fetchPrincipalList");
+ const currentUser: ComputedRef<Principal> = computed(() =>
+ store.getters["auth/currentUser"]()
+ );
+
await store.dispatch("environment/fetchEnvironmentList");
await Promise.all([
@@ -22,12 +25,7 @@ export default {
store.dispatch("uistate/restoreState"),
]);
- // Refresh the user after fetchMemberList / fetchPrincipalList.
- // The user info may change remotely and thus we need to refresh both in-memory and local cache state.
- store.dispatch("auth/refreshUser").then((currentUser: Principal) => {
- // In order to display the empty/non-empty inbox icon on the sidebar properly.
- store.dispatch("message/fetchMessageListByUser", currentUser.id);
- });
+ store.dispatch("message/fetchMessageListByUser", currentUser.value.id);
},
};
</script>
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 040faea6d2..5d2ec8d431 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -18,7 +18,7 @@ import Activate from "../views/auth/Activate.vue";
import PasswordReset from "../views/auth/PasswordReset.vue";
import { store } from "../store";
import { isDev, idFromSlug, isDBAOrOwner } from "../utils";
-import { Principal } from "../types";
+import { Principal, UNKNOWN_ID } from "../types";
const HOME_MODULE = "workspace.home";
const AUTH_MODULE = "auth";
@@ -646,243 +646,257 @@ router.beforeEach((to, from, next) => {
}
}
- const loginUser: Principal = store.getters["auth/currentUser"]();
- if (
- to.name === "workspace.instance" ||
- to.name?.toString().startsWith("setting.workspace.version-control")
- ) {
- if (isDBAOrOwner(loginUser.role)) {
- next();
- } else {
- next({
- name: "error.403",
- replace: false,
- });
+ const checkRouteAuth = (user: Principal) => {
+ if (
+ to.name === "workspace.instance" ||
+ to.name?.toString().startsWith("setting.workspace.version-control")
+ ) {
+ if (isDBAOrOwner(user.role)) {
+ next();
+ } else {
+ console.log("403333", user);
+ next({
+ name: "error.403",
+ replace: false,
+ });
+ }
+ return;
}
- return;
- }
- // Fetching specific instance would try to fetch the sensitive info
- // so we short circuit here for non-DBA/Owner to avoid there.
- if (to.name?.toString().startsWith("workspace.instance.")) {
- if (!isDBAOrOwner(loginUser.role)) {
- next({
- name: "error.403",
- replace: false,
- });
+ // Fetching specific instance would try to fetch the sensitive info
+ // so we short circuit here for non-DBA/Owner to avoid there.
+ if (to.name?.toString().startsWith("workspace.instance.")) {
+ if (!isDBAOrOwner(user.role)) {
+ next({
+ name: "error.403",
+ replace: false,
+ });
+ return;
+ }
+ }
+
+ if (to.name === "workspace.database.create") {
+ if (
+ !store.getters["plan/feature"]("bb.dba-workflow") ||
+ isDBAOrOwner(user.role)
+ ) {
+ next();
+ } else {
+ next({
+ name: "error.403",
+ replace: false,
+ });
+ }
return;
}
- }
- if (to.name === "workspace.database.create") {
- if (
- !store.getters["plan/feature"]("bb.dba-workflow") ||
- isDBAOrOwner(loginUser.role)
- ) {
- next();
- } else {
- next({
- name: "error.403",
- replace: false,
- });
+ if (to.name?.toString().startsWith("workspace.database.datasource")) {
+ if (
+ !store.getters["plan/feature"]("bb.data-source") ||
+ !isDBAOrOwner(user.role)
+ ) {
+ next({
+ name: "error.403",
+ replace: false,
+ });
+ return;
+ }
}
- return;
- }
- if (to.name?.toString().startsWith("workspace.database.datasource")) {
if (
- !store.getters["plan/feature"]("bb.data-source") ||
- !isDBAOrOwner(loginUser.role)
+ to.name === "error.403" ||
+ to.name === "error.404" ||
+ to.name === "error.500" ||
+ to.name === "oauth-callback" ||
+ to.name === "workspace.home" ||
+ // to.name === "workspace.inbox" ||
+ to.name === "workspace.project" ||
+ to.name === "workspace.database" ||
+ to.name === "workspace.archive" ||
+ to.name === "workspace.environment" ||
+ (to.name?.toString().startsWith("setting") &&
+ to.name?.toString() != "setting.workspace.version-control.detail")
) {
- next({
- name: "error.403",
- replace: false,
- });
+ next();
return;
}
- }
- if (
- to.name === "error.403" ||
- to.name === "error.404" ||
- to.name === "error.500" ||
- to.name === "oauth-callback" ||
- to.name === "workspace.home" ||
- // to.name === "workspace.inbox" ||
- to.name === "workspace.project" ||
- to.name === "workspace.database" ||
- to.name === "workspace.archive" ||
- to.name === "workspace.environment" ||
- (to.name?.toString().startsWith("setting") &&
- to.name?.toString() != "setting.workspace.version-control.detail")
- ) {
- next();
- return;
- }
+ // We may just change the anchor (e.g. in Issue Detail view), thus we don't need
+ // to fetch the data to verify its existence since we have already verified before.
+ if (to.name == from.name) {
+ next();
+ return;
+ }
- // We may just change the anchor (e.g. in Issue Detail view), thus we don't need
- // to fetch the data to verify its existence since we have already verified before.
- if (to.name == from.name) {
- next();
- return;
- }
+ const routerSlug = store.getters["router/routeSlug"](to);
+ const principalId = routerSlug.principalId;
+ const environmentSlug = routerSlug.environmentSlug;
+ const projectSlug = routerSlug.projectSlug;
+ const issueSlug = routerSlug.issueSlug;
+ const instanceSlug = routerSlug.instanceSlug;
+ const databaseSlug = routerSlug.databaseSlug;
+ const dataSourceSlug = routerSlug.dataSourceSlug;
+ const vcsSlug = routerSlug.vcsSlug;
- const routerSlug = store.getters["router/routeSlug"](to);
- const principalId = routerSlug.principalId;
- const environmentSlug = routerSlug.environmentSlug;
- const projectSlug = routerSlug.projectSlug;
- const issueSlug = routerSlug.issueSlug;
- const instanceSlug = routerSlug.instanceSlug;
- const databaseSlug = routerSlug.databaseSlug;
- const dataSourceSlug = routerSlug.dataSourceSlug;
- const vcsSlug = routerSlug.vcsSlug;
+ console.debug("RouterSlug:", routerSlug);
- console.debug("RouterSlug:", routerSlug);
+ if (principalId) {
+ store
+ .dispatch("principal/fetchPrincipalById", principalId)
+ .then(() => {
+ next();
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
+ });
+ return;
+ }
- if (principalId) {
- store
- .dispatch("principal/fetchPrincipalById", principalId)
- .then(() => {
+ if (environmentSlug) {
+ if (
+ store.getters["environment/environmentById"](
+ idFromSlug(environmentSlug)
+ )
+ ) {
next();
- })
- .catch((error) => {
- next({
- name: "error.404",
- replace: false,
- });
- throw error;
+ return;
+ }
+ next({
+ name: "error.404",
+ replace: false,
});
- return;
- }
+ }
- if (environmentSlug) {
- if (
- store.getters["environment/environmentById"](idFromSlug(environmentSlug))
- ) {
- next();
+ if (projectSlug) {
+ store
+ .dispatch("project/fetchProjectById", idFromSlug(projectSlug))
+ .then(() => {
+ next();
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
+ });
return;
}
- next({
- name: "error.404",
- replace: false,
- });
- }
- if (projectSlug) {
- store
- .dispatch("project/fetchProjectById", idFromSlug(projectSlug))
- .then((project) => {
+ if (issueSlug) {
+ if (issueSlug.toLowerCase() == "new") {
next();
- })
- .catch((error) => {
- next({
- name: "error.404",
- replace: false,
+ return;
+ }
+ store
+ .dispatch("issue/fetchIssueById", idFromSlug(issueSlug))
+ .then(() => {
+ next();
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
});
- throw error;
- });
- return;
- }
-
- if (issueSlug) {
- if (issueSlug.toLowerCase() == "new") {
- next();
return;
}
- store
- .dispatch("issue/fetchIssueById", idFromSlug(issueSlug))
- .then((issue) => {
+
+ if (databaseSlug) {
+ if (
+ databaseSlug.toLowerCase() == "new" ||
+ databaseSlug.toLowerCase() == "grant"
+ ) {
next();
- })
- .catch((error) => {
- next({
- name: "error.404",
- replace: false,
+ return;
+ }
+ store
+ .dispatch("database/fetchDatabaseById", {
+ databaseId: idFromSlug(databaseSlug),
+ })
+ .then((database) => {
+ if (!dataSourceSlug) {
+ next();
+ } else {
+ store
+ .dispatch("dataSource/fetchDataSourceById", {
+ dataSourceId: idFromSlug(dataSourceSlug),
+ databaseId: database.id,
+ })
+ .then(() => {
+ next();
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
+ });
+ }
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
});
- throw error;
- });
- return;
- }
-
- if (databaseSlug) {
- if (
- databaseSlug.toLowerCase() == "new" ||
- databaseSlug.toLowerCase() == "grant"
- ) {
- next();
return;
}
- store
- .dispatch("database/fetchDatabaseById", {
- databaseId: idFromSlug(databaseSlug),
- })
- .then((database) => {
- if (!dataSourceSlug) {
+
+ if (instanceSlug) {
+ store
+ .dispatch("instance/fetchInstanceById", idFromSlug(instanceSlug))
+ .then(() => {
next();
- } else {
- store
- .dispatch("dataSource/fetchDataSourceById", {
- dataSourceId: idFromSlug(dataSourceSlug),
- databaseId: database.id,
- })
- .then((dataSource) => {
- next();
- })
- .catch((error) => {
- next({
- name: "error.404",
- replace: false,
- });
- throw error;
- });
- }
- })
- .catch((error) => {
- next({
- name: "error.404",
- replace: false,
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
});
- throw error;
- });
- return;
- }
+ return;
+ }
- if (instanceSlug) {
- store
- .dispatch("instance/fetchInstanceById", idFromSlug(instanceSlug))
- .then((instance) => {
- next();
- })
- .catch((error) => {
- next({
- name: "error.404",
- replace: false,
+ if (vcsSlug) {
+ store
+ .dispatch("vcs/fetchVCSById", idFromSlug(vcsSlug))
+ .then(() => {
+ next();
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
});
- throw error;
- });
- return;
- }
+ return;
+ }
- if (vcsSlug) {
- store
- .dispatch("vcs/fetchVCSById", idFromSlug(vcsSlug))
- .then(() => {
- next();
- })
- .catch((error) => {
- next({
- name: "error.404",
- replace: false,
- });
- throw error;
- });
- return;
- }
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ };
- next({
- name: "error.404",
- replace: false,
- });
+ const loginUser: Principal = store.getters["auth/currentUser"]();
+ // On displaying the first page, we need to do an async restore to fetch the lastest user from the server.
+ if (loginUser.id == UNKNOWN_ID) {
+ store.dispatch("auth/restoreUser").then((user: Principal) => {
+ checkRouteAuth(user);
+ });
+ } else {
+ checkRouteAuth(loginUser);
+ }
});
router.afterEach((to, from) => {
diff --git a/frontend/src/store/modules/auth.ts b/frontend/src/store/modules/auth.ts
index c53d112d66..df8e94895c 100644
--- a/frontend/src/store/modules/auth.ts
+++ b/frontend/src/store/modules/auth.ts
@@ -1,6 +1,5 @@
import axios from "axios";
import isEqual from "lodash-es/isEqual";
-import isEmpty from "lodash-es/isEmpty";
import {
Principal,
AuthState,
@@ -101,16 +100,6 @@ const actions = {
return unknown("PRINCIPAL") as Principal;
},
- async refreshUser({ commit, state, rootGetters }: any) {
- const refreshedUser = rootGetters["principal/principalById"](
- state.currentUser.id
- );
- if (!isEqual(refreshedUser, state.currentUser)) {
- commit("setCurrentUser", refreshedUser);
- }
- return refreshedUser;
- },
-
async logout({ commit }: any) {
removeCookie("user");
console.log("logout:", getIntCookie("user"));
diff --git a/frontend/src/store/modules/principal.ts b/frontend/src/store/modules/principal.ts
index a5dab45aad..911f9b2224 100644
--- a/frontend/src/store/modules/principal.ts
+++ b/frontend/src/store/modules/principal.ts
@@ -11,11 +11,11 @@ import {
empty,
EMPTY_ID,
PrincipalType,
+ RoleType,
} from "../../types";
import { isRelease, randomString } from "../../utils";
-function convert(principal: ResourceObject, rootGetters: any): Principal {
- const member = rootGetters["member/memberByPrincipalId"](principal.id);
+function convert(principal: ResourceObject): Principal {
return {
id: parseInt(principal.id),
creatorId: principal.attributes.creatorId as PrincipalId,
@@ -26,7 +26,7 @@ function convert(principal: ResourceObject, rootGetters: any): Principal {
type: principal.attributes.type as PrincipalType,
name: principal.attributes.name as string,
email: principal.attributes.email as string,
- role: member.role,
+ role: principal.attributes.role as RoleType,
};
}
@@ -38,7 +38,7 @@ const getters = {
convert:
(state: PrincipalState, getters: any, rootState: any, rootGetters: any) =>
(principal: ResourceObject, includedList: ResourceObject[]): Principal => {
- return convert(principal, rootGetters);
+ return convert(principal);
},
principalList: (state: PrincipalState) => (): Principal[] => {
@@ -69,11 +69,11 @@ const getters = {
};
const actions = {
- async fetchPrincipalList({ state, commit, rootGetters }: any) {
+ async fetchPrincipalList({ commit }: any) {
const userList: ResourceObject[] = (await axios.get(`/api/principal`)).data
.data;
const principalList = userList.map((user) => {
- return convert(user, rootGetters);
+ return convert(user);
});
commit("setPrincipalList", principalList);
@@ -81,13 +81,9 @@ const actions = {
return principalList;
},
- async fetchPrincipalById(
- { commit, rootGetters }: any,
- principalId: PrincipalId
- ) {
+ async fetchPrincipalById({ commit }: any, principalId: PrincipalId) {
const principal = convert(
- (await axios.get(`/api/principal/${principalId}`)).data.data,
- rootGetters
+ (await axios.get(`/api/principal/${principalId}`)).data.data
);
commit("upsertPrincipalInList", principal);
@@ -96,10 +92,7 @@ const actions = {
},
// Returns existing user if already created.
- async createPrincipal(
- { commit, rootGetters }: any,
- newPrincipal: PrincipalCreate
- ) {
+ async createPrincipal({ commit }: any, newPrincipal: PrincipalCreate) {
const createdPrincipal = convert(
(
await axios.post(`/api/principal`, {
@@ -113,8 +106,7 @@ const actions = {
},
},
})
- ).data.data,
- rootGetters
+ ).data.data
);
commit("appendPrincipal", createdPrincipal);
@@ -123,7 +115,7 @@ const actions = {
},
async patchPrincipal(
- { commit, rootGetters }: any,
+ { commit }: any,
{
principalId,
principalPatch,
@@ -140,8 +132,7 @@ const actions = {
attributes: principalPatch,
},
})
- ).data.data,
- rootGetters
+ ).data.data
);
commit("upsertPrincipalInList", updatedPrincipal);
diff --git a/server/principal.go b/server/principal.go
index 8743e389d9..e315f37abc 100644
--- a/server/principal.go
+++ b/server/principal.go
@@ -45,6 +45,12 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch principal list").SetInternal(err)
}
+ for _, principal := range list {
+ if err := s.ComposePrincipalRole(context.Background(), principal); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch role for principal: %v", principal.Name)).SetInternal(err)
+ }
+ }
+
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, list); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal principal list response").SetInternal(err)
@@ -111,5 +117,23 @@ func (s *Server) ComposePrincipalById(ctx context.Context, id int, includeList [
return nil, err
}
+ s.ComposePrincipalRole(ctx, principal)
+
return principal, nil
}
+
+func (s *Server) ComposePrincipalRole(ctx context.Context, principal *api.Principal) error {
+ if principal.ID == api.SYSTEM_BOT_ID {
+ principal.Role = api.Owner
+ } else {
+ memberFind := &api.MemberFind{
+ PrincipalId: &principal.ID,
+ }
+ member, err := s.MemberService.FindMember(context.Background(), memberFind)
+ if err != nil {
+ return err
+ }
+ principal.Role = member.Role
+ }
+ return nil
+}