Skip to content

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

feat(frontend): migration auth store to v1 (#4849)

boojack359bafa9d35f
diff --git a/backend/legacyapi/principal.go b/backend/legacyapi/principal.go
index 68bd419140..442bfcfe2b 100644
--- a/backend/legacyapi/principal.go
+++ b/backend/legacyapi/principal.go
@@ -52,8 +52,7 @@ type Principal struct {
Role Role `jsonapi:"attr,role"`
// The ServiceKey is the password, only used for SERVICE_ACCOUNT.
// We only return the service key for the first time after the creation for SERVICE_ACCOUNT.
- ServiceKey string `jsonapi:"attr,serviceKey"`
- IdentityProviderName string `jsonapi:"attr,identityProviderName"`
+ ServiceKey string `jsonapi:"attr,serviceKey"`
}
// MarshalJSON customizes the Principal Marshal method so the returned object
diff --git a/frontend/src/components/KBar/KBarWrapper.vue b/frontend/src/components/KBar/KBarWrapper.vue
index 1f48e85ce4..cff90775fd 100644
--- a/frontend/src/components/KBar/KBarWrapper.vue
+++ b/frontend/src/components/KBar/KBarWrapper.vue
@@ -35,7 +35,7 @@ import KBarHelper from "./KBarHelper.vue";
import KBarFooter from "./KBarFooter.vue";
import { useI18n } from "vue-i18n";
import { useModalStackStatus } from "../../bbkit/BBModalStack.vue";
-import { useAuthStore } from "@/store";
+import { useCurrentUser } from "@/store";
export default defineComponent({
name: "KBarWrapper",
@@ -65,10 +65,10 @@ export default defineComponent({
return true;
}
- const currentUser = useAuthStore().currentUser;
+ const currentUser = useCurrentUser();
// totally disable kbar when not logged in
// since there is no point to show it on signin/signup pages
- return !currentUser || currentUser.id < 0;
+ return !currentUser || currentUser.value.id < 0;
});
const globalActions = computed(() => [
diff --git a/frontend/src/components/ProfileDropdown.vue b/frontend/src/components/ProfileDropdown.vue
index 3abd5a768a..8ce1137693 100644
--- a/frontend/src/components/ProfileDropdown.vue
+++ b/frontend/src/components/ProfileDropdown.vue
@@ -119,6 +119,7 @@ import {
pushNotification,
useActuatorStore,
useAuthStore,
+ useCurrentUser,
useDebugStore,
useUIStateStore,
} from "@/store";
@@ -135,8 +136,7 @@ export default defineComponent({
const router = useRouter();
const { setLocale, locale } = useLanguage();
const languageMenu = ref();
-
- const { currentUser } = storeToRefs(authStore);
+ const currentUser = useCurrentUser();
// For now, debug mode is a global setting and will affect all users.
// So we only allow DBA and Owner to toggle it.
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 1dabb1f169..9b57fa05f6 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -50,6 +50,7 @@ import {
useOnboardingStateStore,
useTabStore,
useIdentityProviderStore,
+ useCurrentUser,
} from "@/store";
const HOME_MODULE = "workspace.home";
@@ -586,14 +587,14 @@ const routes: Array<RouteRecordRaw> = [
if (project.rowStatus == "NORMAL") {
const actionList: string[] = [];
- const currentUser = useAuthStore().currentUser;
+ const currentUser = useCurrentUser();
let allowAlterSchemaOrChangeData = false;
let allowCreateDB = false;
let allowTransferDB = false;
if (
hasWorkspacePermission(
"bb.permission.workspace.manage-instance",
- currentUser.role
+ currentUser.value.role
)
) {
allowAlterSchemaOrChangeData = true;
@@ -601,7 +602,7 @@ const routes: Array<RouteRecordRaw> = [
allowTransferDB = true;
} else {
const memberOfProject = project.memberList.find(
- (m) => m.principal.id === currentUser.id
+ (m) => m.principal.id === currentUser.value.id
);
if (memberOfProject) {
allowAlterSchemaOrChangeData = hasProjectPermission(
@@ -1067,13 +1068,13 @@ router.beforeEach((to, from, next) => {
}
}
- const currentUser = authStore.currentUser;
+ const currentUser = useCurrentUser();
if (to.name?.toString().startsWith("setting.workspace.im-integration")) {
if (
!hasWorkspacePermission(
"bb.permission.workspace.manage-im-integration",
- currentUser.role
+ currentUser.value.role
)
) {
next({
@@ -1088,7 +1089,7 @@ router.beforeEach((to, from, next) => {
if (
!hasWorkspacePermission(
"bb.permission.workspace.manage-sso",
- currentUser.role
+ currentUser.value.role
)
) {
next({
@@ -1103,7 +1104,7 @@ router.beforeEach((to, from, next) => {
if (
!hasWorkspacePermission(
"bb.permission.workspace.manage-vcs-provider",
- currentUser.role
+ currentUser.value.role
)
) {
next({
@@ -1118,7 +1119,7 @@ router.beforeEach((to, from, next) => {
if (
!hasWorkspacePermission(
"bb.permission.workspace.manage-project",
- currentUser.role
+ currentUser.value.role
)
) {
next({
@@ -1133,7 +1134,7 @@ router.beforeEach((to, from, next) => {
if (
!hasWorkspacePermission(
"bb.permission.workspace.audit-log",
- currentUser.role
+ currentUser.value.role
)
) {
next({
@@ -1148,7 +1149,7 @@ router.beforeEach((to, from, next) => {
if (
!hasWorkspacePermission(
"bb.permission.workspace.debug-log",
- currentUser.role
+ currentUser.value.role
)
) {
next({
@@ -1163,7 +1164,7 @@ router.beforeEach((to, from, next) => {
if (
!hasWorkspacePermission(
"bb.permission.workspace.manage-instance",
- currentUser.role
+ currentUser.value.role
)
) {
next({
@@ -1179,7 +1180,7 @@ router.beforeEach((to, from, next) => {
!hasFeature("bb.feature.data-source") ||
!hasWorkspacePermission(
"bb.permission.workspace.manage-instance",
- currentUser.role
+ currentUser.value.role
)
) {
next({
diff --git a/frontend/src/store/modules/auth.ts b/frontend/src/store/modules/auth.ts
index defaaac8d0..f2e79e170b 100644
--- a/frontend/src/store/modules/auth.ts
+++ b/frontend/src/store/modules/auth.ts
@@ -1,113 +1,35 @@
-import { defineStore, storeToRefs } from "pinia";
+import { defineStore } from "pinia";
import axios from "axios";
import { isEqual } from "lodash-es";
-import { computed, Ref } from "vue";
-import {
- Principal,
- AuthState,
- AuthProviderType,
- VCSLoginInfo,
- SignupInfo,
- ActivateInfo,
- ResourceObject,
- unknown,
- PrincipalId,
- AuthProvider,
- BytebaseLoginInfo,
- UNKNOWN_ID,
-} from "@/types";
+import { computed } from "vue";
+import { SignupInfo, ActivateInfo } from "@/types";
import { getIntCookie } from "@/utils";
import { authServiceClient } from "@/grpcweb";
-import { usePrincipalStore } from "./principal";
-import { LoginRequest } from "@/types/proto/v1/auth_service";
+import { LoginRequest, User } from "@/types/proto/v1/auth_service";
+import { convertUserToPrincipal, useUserStore } from ".";
+import { unknown } from "@/utils/common";
-function convert(user: ResourceObject): Principal {
- return usePrincipalStore().principalById(parseInt(user.id, 10));
+interface AuthState {
+ currentUser: User;
}
-function convertAuthProvider(authProvider: ResourceObject) {
- return { ...authProvider.attributes } as AuthProvider;
-}
-
-export const useAuthStore = defineStore("auth", {
+export const useAuthStore = defineStore("auth_v1", {
state: (): AuthState => ({
- authProviderList: [],
- currentUser: unknown("PRINCIPAL") as Principal,
+ currentUser: User.fromPartial({}),
}),
actions: {
isLoggedIn: () => {
return getIntCookie("user") != undefined;
},
- setAuthProviderList(authProviderList: AuthProvider[]) {
- this.authProviderList = authProviderList;
- },
- setCurrentUser(user: Principal) {
- this.currentUser = user;
- },
- async fetchProviderList() {
- const providerList = (await axios.get("/api/auth/provider")).data.data;
- const convertedProviderList: AuthProvider[] = providerList.map(
- (provider: ResourceObject) => {
- return convertAuthProvider(provider);
- }
- );
- this.setAuthProviderList(convertedProviderList);
- return convertedProviderList;
- },
- async login(loginInfo: BytebaseLoginInfo) {
- await axios.post("/v1/auth/login", {
- email: loginInfo.email,
- password: loginInfo.password,
- web: true,
- });
- const userId = getIntCookie("user");
- if (userId) {
- const loggedInUser = await usePrincipalStore().fetchPrincipalById(
- userId
- );
-
- this.setCurrentUser(loggedInUser);
- return loggedInUser;
- }
- return unknown("PRINCIPAL") as Principal;
- },
- async loginWithIdentityProvider(request: LoginRequest) {
+ async login(request: Partial<LoginRequest>) {
await axios.post("/v1/auth/login", request);
const userId = getIntCookie("user");
if (userId) {
- const loggedInUser = await usePrincipalStore().fetchPrincipalById(
- userId
- );
-
- this.setCurrentUser(loggedInUser);
+ const loggedInUser = await useUserStore().getOrFetchUserById(userId);
+ this.currentUser = loggedInUser;
return loggedInUser;
}
- return unknown("PRINCIPAL") as Principal;
- },
- async vcsLogin(
- authProviderType: AuthProviderType,
- loginInfo: VCSLoginInfo
- ) {
- const loggedInUser = (
- await axios.post(`/api/auth/login/${authProviderType}`, {
- data: { type: "loginInfo", attributes: loginInfo },
- })
- ).data.data;
- // Refresh the corresponding principal
- await usePrincipalStore().fetchPrincipalById(loggedInUser.id);
- // The conversion relies on the above refresh.
- const convertedUser = convert(loggedInUser);
- this.setCurrentUser(convertedUser);
- return convertedUser;
- },
- async logout() {
- const unknownPrincipal = unknown("PRINCIPAL") as Principal;
- try {
- await axios.post("/v1/auth/logout");
- } finally {
- this.setCurrentUser(unknownPrincipal);
- }
- return unknownPrincipal;
+ return unknown("USER");
},
async signup(signupInfo: SignupInfo) {
await authServiceClient().createUser({
@@ -117,21 +39,20 @@ export const useAuthStore = defineStore("auth", {
password: signupInfo.password,
},
});
- await axios.post("/v1/auth/login", {
+ const user = await this.login({
email: signupInfo.email,
password: signupInfo.password,
- web: true,
});
- const userId = getIntCookie("user");
- if (userId) {
- const loggedInUser = await usePrincipalStore().fetchPrincipalById(
- userId
- );
-
- this.setCurrentUser(loggedInUser);
- return loggedInUser;
+ return user;
+ },
+ async logout() {
+ const unknownUser = unknown("USER");
+ try {
+ await axios.post("/v1/auth/logout");
+ } finally {
+ this.currentUser = unknownUser;
}
- return unknown("PRINCIPAL") as Principal;
+ return unknownUser;
},
async activate(activateInfo: ActivateInfo) {
const activatedUser = (
@@ -140,46 +61,40 @@ export const useAuthStore = defineStore("auth", {
})
).data.data;
- // Refresh the corresponding principal
- await usePrincipalStore().fetchPrincipalById(activatedUser.id);
-
- // The conversion relies on the above task to get the latest data
- const convertedUser = convert(activatedUser);
- this.setCurrentUser(convertedUser);
- return convertedUser;
+ // Refresh the corresponding user.
+ const user = await useUserStore().getOrFetchUserById(activatedUser.id);
+ this.currentUser = user;
+ return user;
},
async restoreUser() {
const userId = getIntCookie("user");
if (userId) {
- const loggedInUser = await usePrincipalStore().fetchPrincipalById(
- userId
- );
-
- this.setCurrentUser(loggedInUser);
+ const loggedInUser = await useUserStore().getOrFetchUserById(userId);
+ this.currentUser = loggedInUser;
return loggedInUser;
}
- return unknown("PRINCIPAL") as Principal;
+ return unknown("USER");
},
- async refreshUserIfNeeded(principalId: PrincipalId) {
- if (principalId == this.currentUser.id) {
- const refreshedUser = usePrincipalStore().principalById(
- this.currentUser.id
- );
+ async refreshUserIfNeeded(name: string) {
+ if (name === this.currentUser.name) {
+ const refreshedUser = await useUserStore().getOrFetchUserByName(name);
if (!isEqual(refreshedUser, this.currentUser)) {
- this.setCurrentUser(refreshedUser);
+ this.currentUser = refreshedUser;
}
}
},
},
});
-export const useCurrentUser = (): Ref<Principal> => {
- return storeToRefs(useAuthStore()).currentUser;
+export const useCurrentUser = () => {
+ const authStore = useAuthStore();
+
+ return computed(() => {
+ return convertUserToPrincipal(authStore.currentUser);
+ });
};
-export const useIsLoggedIn = (): Ref<boolean> => {
+export const useIsLoggedIn = () => {
const store = useAuthStore();
- return computed(
- () => store.isLoggedIn() && store.currentUser.id !== UNKNOWN_ID
- );
+ return computed(() => store.isLoggedIn() && store.currentUser.name !== "");
};
diff --git a/frontend/src/store/modules/principal.ts b/frontend/src/store/modules/principal.ts
index 347c60a07a..5bd1d9e8b9 100644
--- a/frontend/src/store/modules/principal.ts
+++ b/frontend/src/store/modules/principal.ts
@@ -25,7 +25,6 @@ function convert(principal: ResourceObject): Principal {
email: principal.attributes.email as string,
role: principal.attributes.role as RoleType,
serviceKey: principal.attributes.serviceKey as string,
- identityProviderName: principal.attributes.identityProviderName as string,
};
}
diff --git a/frontend/src/store/modules/user.ts b/frontend/src/store/modules/user.ts
index ba56d66bc0..cfb4cc39b5 100644
--- a/frontend/src/store/modules/user.ts
+++ b/frontend/src/store/modules/user.ts
@@ -1,8 +1,13 @@
import { defineStore } from "pinia";
import { authServiceClient } from "@/grpcweb";
-import { User } from "@/types/proto/v1/auth_service";
+import {
+ User,
+ userRoleToJSON,
+ userTypeToJSON,
+} from "@/types/proto/v1/auth_service";
import { isEqual, isUndefined } from "lodash-es";
-import { userNamePrefix } from "./v1/common";
+import { getUserId, userNamePrefix } from "./v1/common";
+import { Principal, PrincipalType, RoleType } from "@/types";
interface UserState {
userMapByName: Map<string, User>;
@@ -99,3 +104,17 @@ const getUpdateMaskFromUsers = (
}
return updateMask;
};
+
+export const convertUserToPrincipal = (user: User): Principal => {
+ const userRole = userRoleToJSON(user.userRole) as RoleType;
+ const userType = userTypeToJSON(user.userType) as PrincipalType;
+
+ return {
+ id: getUserId(user.name),
+ name: user.title,
+ email: user.email,
+ role: userRole,
+ type: userType,
+ serviceKey: user.password,
+ };
+};
diff --git a/frontend/src/store/modules/v1/auth.ts b/frontend/src/store/modules/v1/auth.ts
deleted file mode 100644
index 54cb7a637a..0000000000
--- a/frontend/src/store/modules/v1/auth.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import axios from "axios";
-import { isEqual } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed } from "vue";
-import { authServiceClient } from "@/grpcweb";
-import { ActivateInfo, SignupInfo } from "@/types";
-import { LoginRequest, User } from "@/types/proto/v1/auth_service";
-import { getIntCookie } from "@/utils";
-import { unknown } from "@/utils/common";
-import { useUserStore } from "../user";
-import { getUserId } from "./common";
-
-interface AuthState {
- currentUser: User;
-}
-
-export const useAuthV1Store = defineStore("auth_v1", {
- state: (): AuthState => ({
- currentUser: User.fromPartial({}),
- }),
- actions: {
- isLoggedIn: () => {
- return getIntCookie("user") != undefined;
- },
- async login(request: Partial<LoginRequest>) {
- await axios.post("/v1/auth/login", request);
- const userId = getIntCookie("user");
- if (userId) {
- const loggedInUser = await useUserStore().getOrFetchUserById(userId);
- this.currentUser = loggedInUser;
- return loggedInUser;
- }
- return unknown("USER");
- },
- async signup(signupInfo: SignupInfo) {
- await authServiceClient().createUser({
- user: {
- email: signupInfo.email,
- title: signupInfo.name,
- password: signupInfo.password,
- },
- });
- const user = await this.login({
- email: signupInfo.email,
- password: signupInfo.password,
- });
- return user;
- },
- async logout() {
- const unknownUser = unknown("USER");
- try {
- await axios.post("/v1/auth/logout");
- } finally {
- this.currentUser = unknownUser;
- }
- return unknownUser;
- },
- async activate(activateInfo: ActivateInfo) {
- const activatedUser = (
- await axios.post("/api/auth/activate", {
- data: { type: "activateInfo", attributes: activateInfo },
- })
- ).data.data;
-
- // Refresh the corresponding user.
- const user = await useUserStore().getOrFetchUserById(activatedUser.id);
- this.currentUser = user;
- return user;
- },
- async restoreUser() {
- const userId = getIntCookie("user");
- if (userId) {
- const loggedInUser = await useUserStore().getOrFetchUserById(userId);
- this.currentUser = loggedInUser;
- return loggedInUser;
- }
- return unknown("USER");
- },
- async refreshUserIfNeeded(name: string) {
- if (name === this.currentUser.name) {
- const refreshedUser = await useUserStore().getOrFetchUserByName(name);
- if (!isEqual(refreshedUser, this.currentUser)) {
- this.currentUser = refreshedUser;
- }
- }
- },
- },
-});
-
-export const useCurrentUser = () => {
- const authStore = useAuthV1Store();
-
- return computed(() => {
- return {
- ...authStore.currentUser,
- id: getUserId(authStore.currentUser.name),
- };
- });
-};
-
-export const useIsLoggedIn = () => {
- const store = useAuthV1Store();
- return computed(() => store.isLoggedIn() && store.currentUser.name !== "");
-};
diff --git a/frontend/src/store/modules/v1/common.ts b/frontend/src/store/modules/v1/common.ts
index b0cddb98af..d8d2f2011b 100644
--- a/frontend/src/store/modules/v1/common.ts
+++ b/frontend/src/store/modules/v1/common.ts
@@ -6,19 +6,19 @@ export const getNameParentTokens = (
tokenPrefixes: string[]
): string[] => {
const parts = name.split("/");
- if (parts.length !== 2 * tokenPrefixes.length) {
+ if (parts.length !== tokenPrefixes.length * 2) {
return [];
}
const tokens: string[] = [];
for (let i = 0; i < tokenPrefixes.length; i++) {
- if (parts[2 * i] !== tokenPrefixes[i]) {
+ if (parts[i * 2] + "/" !== tokenPrefixes[i]) {
return [];
}
- if (parts[2 * i + 1] === "") {
+ if (parts[i * 2 + 1] === "") {
return [];
}
- tokens.push(parts[2 * i + 1]);
+ tokens.push(parts[i * 2 + 1]);
}
return tokens;
};
diff --git a/frontend/src/types/auth.ts b/frontend/src/types/auth.ts
index cc7bf792c8..eaa9f00d6f 100644
--- a/frontend/src/types/auth.ts
+++ b/frontend/src/types/auth.ts
@@ -1,10 +1,3 @@
-// Auth
-
-import { VCSId } from "./id";
-
-// For now, a single user's auth provider should either belong to GITLAB_SELF_HOST, GITHUB_COM or BYTEBASE
-export type AuthProviderType = "GITLAB_SELF_HOST" | "GITHUB_COM" | "BYTEBASE";
-
export type SignupInfo = {
email: string;
password: string;
@@ -22,27 +15,3 @@ export type BytebaseLoginInfo = {
email: string;
password: string;
};
-
-export type AuthProvider = {
- id: VCSId;
- type: AuthProviderType;
- name: string;
- instanceUrl: string;
- applicationId: string;
- secret: string;
-};
-
-export const EmptyAuthProvider: AuthProvider = {
- id: 0,
- type: "BYTEBASE",
- name: "",
- instanceUrl: "",
- applicationId: "",
- secret: "",
-};
-
-export type VCSLoginInfo = {
- vcsId: VCSId;
- name: string;
- code: string;
-};
diff --git a/frontend/src/types/principal.ts b/frontend/src/types/principal.ts
index 52695e5d7c..ca7df1f5c7 100644
--- a/frontend/src/types/principal.ts
+++ b/frontend/src/types/principal.ts
@@ -15,7 +15,6 @@ export type Principal = {
email: string;
role: RoleType;
serviceKey: string;
- identityProviderName: string;
};
export type PrincipalCreate = {
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index ef01e3268f..682b605b87 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -1,6 +1,5 @@
import { RemovableRef } from "@vueuse/core";
import {
- AuthProvider,
DeploymentConfig,
EnvironmentId,
MigrationHistoryId,
@@ -55,11 +54,6 @@ export interface ActuatorState {
releaseInfo: RemovableRef<ReleaseInfo>;
}
-export interface AuthState {
- authProviderList: AuthProvider[];
- currentUser: Principal;
-}
-
export interface AuditLogState {
auditLogList: AuditLog[];
}
diff --git a/frontend/src/views/ProfileDashboard.vue b/frontend/src/views/ProfileDashboard.vue
index 5220e2cf57..8e08104a76 100644
--- a/frontend/src/views/ProfileDashboard.vue
+++ b/frontend/src/views/ProfileDashboard.vue
@@ -120,7 +120,7 @@
</dt>
<dd class="mt-1 text-sm text-main">
<input
- v-if="state.editing && !isSSOUser"
+ v-if="state.editing"
id="email"
required
autocomplete="off"
@@ -136,7 +136,7 @@
</dd>
</div>
- <template v-if="state.editing && !isSSOUser">
+ <template v-if="state.editing">
<div class="sm:col-span-1">
<dt class="text-sm font-medium text-control-light">
{{ $t("settings.profile.password") }}
@@ -260,11 +260,6 @@ const passwordMismatch = computed(() => {
);
});
-const isSSOUser = computed(() => {
- const name = `users/${principal.value.id}`;
- return userStore.userMapByName.get(name)?.identityProvider !== "";
-});
-
// 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(() => {
diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vue
index e32fb0bd15..f512f78b8f 100644
--- a/frontend/src/views/auth/Signin.vue
+++ b/frontend/src/views/auth/Signin.vue
@@ -147,7 +147,7 @@
import { computed, onMounted, onUnmounted, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
-import { AuthProvider, OAuthWindowEventPayload } from "@/types";
+import { OAuthWindowEventPayload } from "@/types";
import { isValidEmail, openWindowForSSO } from "@/utils";
import {
featureToRef,
@@ -165,7 +165,6 @@ interface LocalState {
email: string;
password: string;
showPassword: boolean;
- activeAuthProvider?: AuthProvider;
activeIdentityProvider?: IdentityProvider;
}
@@ -199,7 +198,6 @@ onMounted(async () => {
state.showPassword = true;
}
- await authStore.fetchProviderList();
await identityProviderStore.fetchIdentityProviderList();
});
@@ -243,15 +241,13 @@ const loginWithIdentityProviderEventListener = async (event: Event) => {
return;
}
const code = payload.code;
- await authStore.loginWithIdentityProvider({
+ await authStore.login({
idpName: state.activeIdentityProvider.name,
context: {
oauth2Context: {
code,
},
},
- email: "",
- password: "",
web: true,
});
router.push("/");
@@ -266,6 +262,7 @@ const trySignin = async () => {
await authStore.login({
email: state.email,
password: state.password,
+ web: true,
});
router.push("/");
};