Skip to content

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

refactor(auth): use GetCurrentUser instead of user from cookie (#15838)

boojack2bcf1066f91d
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.go
index 88f52bfe65..b62315302c 100644
--- a/backend/api/auth/auth.go
+++ b/backend/api/auth/auth.go
@@ -45,13 +45,9 @@ const (
// AccessTokenCookieName is the cookie name of access token.
AccessTokenCookieName = "access-token"
- // UserIDCookieName is the cookie name of user ID.
- UserIDCookieName = "user"
// GatewayMetadataAccessTokenKey is the gateway metadata key for access token.
GatewayMetadataAccessTokenKey = "bytebase-access-token"
- // GatewayMetadataUserIDKey is the gateway metadata key for user ID.
- GatewayMetadataUserIDKey = "bytebase-user"
// GatewayMetadataRequestOriginKey is the gateway metadata key for the request origin header.
GatewayMetadataRequestOriginKey = "bytebase-request-origin"
)
diff --git a/backend/api/auth/header.go b/backend/api/auth/header.go
index 5385dfecfb..a142384b47 100644
--- a/backend/api/auth/header.go
+++ b/backend/api/auth/header.go
@@ -32,8 +32,6 @@ func (m *GatewayResponseModifier) Modify(ctx context.Context, response http.Resp
}
}
m.processMetadata(ctx, md, GatewayMetadataAccessTokenKey, AccessTokenCookieName, true /* httpOnly */, isHTTPS, response)
- // TODO(steven): remove me please.
- m.processMetadata(ctx, md, GatewayMetadataUserIDKey, UserIDCookieName, false /* httpOnly */, isHTTPS, response)
return nil
}
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index bb8c1f6e21..bafc91c71e 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -183,7 +183,6 @@ func (s *AuthService) Login(ctx context.Context, request *v1pb.LoginRequest) (*v
}
if err := grpc.SetHeader(ctx, metadata.New(map[string]string{
auth.GatewayMetadataAccessTokenKey: response.Token,
- auth.GatewayMetadataUserIDKey: fmt.Sprintf("%d", loginUser.ID),
auth.GatewayMetadataRequestOriginKey: origin,
})); err != nil {
return nil, status.Errorf(codes.Internal, "failed to set grpc header, error: %v", err)
@@ -266,7 +265,6 @@ func (s *AuthService) Logout(ctx context.Context, _ *v1pb.LogoutRequest) (*empty
if err := grpc.SetHeader(ctx, metadata.New(map[string]string{
auth.GatewayMetadataAccessTokenKey: "",
- auth.GatewayMetadataUserIDKey: "",
})); err != nil {
return nil, status.Errorf(codes.Internal, "failed to set grpc header, error: %v", err)
}
diff --git a/frontend/src/App.vue b/frontend/src/App.vue
index b736b9dab1..93088f122d 100644
--- a/frontend/src/App.vue
+++ b/frontend/src/App.vue
@@ -15,7 +15,7 @@
<OverlayStackManager>
<NotificationContext>
<AuthContext>
- <router-view v-if="actuatorStore.initialized" />
+ <router-view v-if="initialized" />
<div
v-else
class="fixed inset-0 bg-white flex flex-col items-center justify-center"
@@ -40,11 +40,10 @@ import {
} from "naive-ui";
import { ServerError } from "nice-grpc-common";
import { ClientError, Status } from "nice-grpc-web";
-import { onErrorCaptured, onMounted, watchEffect } from "vue";
+import { onErrorCaptured, onMounted, ref, watchEffect } from "vue";
import { watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import Watermark from "@/components/misc/Watermark.vue";
-import { AUTH_PASSWORD_RESET_MODULE } from "@/router/auth";
import { themeOverrides, dateLang, generalLang } from "../naive-ui.config";
import { provideAppRootContext } from "./AppRootContext";
import AuthContext from "./AuthContext.vue";
@@ -53,10 +52,8 @@ import OverlayStackManager from "./components/misc/OverlayStackManager.vue";
import { overrideAppProfile } from "./customAppProfile";
import { t } from "./plugins/i18n";
import {
- useActuatorV1Store,
useAuthStore,
useNotificationStore,
- useSubscriptionV1Store,
useWorkspaceV1Store,
} from "./store";
import { isDev } from "./utils";
@@ -69,59 +66,22 @@ const router = useRouter();
const { key } = provideAppRootContext();
const authStore = useAuthStore();
const notificationStore = useNotificationStore();
-const actuatorStore = useActuatorV1Store();
const workspaceStore = useWorkspaceV1Store();
+const initialized = ref(false);
onMounted(async () => {
- const initActuator = async () => {
- actuatorStore.fetchServerInfo();
- };
- const initSubscription = async () => {
- await useSubscriptionV1Store().fetchSubscription();
- };
- const initFeatureMatrix = async () => {
- await useSubscriptionV1Store().fetchFeatureMatrix();
- };
- const restoreUser = async () => {
- await authStore.restoreUser();
- };
- const initBasicModules = async () => {
- await Promise.all([
- initActuator(),
- initFeatureMatrix(),
- initSubscription(),
- // We need to restore the basic info in order to perform route authentication.
- restoreUser(),
- ]);
- };
-
- await initBasicModules();
- actuatorStore.initialized = true;
-
- if (authStore.requireResetPassword) {
- router.replace({
- name: AUTH_PASSWORD_RESET_MODULE,
- });
+ if (authStore.isLoggedIn) {
+ await workspaceStore.fetchIamPolicy();
}
+
+ initialized.value = true;
});
watchEffect(async () => {
- // Override app profile
+ // Override app profile.
overrideAppProfile();
});
-watch(
- () => authStore.currentUserId,
- async (currentUserId) => {
- if (currentUserId) {
- await workspaceStore.fetchIamPolicy();
- }
- },
- {
- immediate: true,
- }
-);
-
onErrorCaptured((error: any /* , _, info */) => {
// Handle grpc request error.
// It looks like: `{"path":"/bytebase.v1.AuthService/Login","code":2,"details":"Response closed without headers"}`
diff --git a/frontend/src/AuthContext.vue b/frontend/src/AuthContext.vue
index a8fe000e98..379ddac53a 100644
--- a/frontend/src/AuthContext.vue
+++ b/frontend/src/AuthContext.vue
@@ -4,13 +4,13 @@
</template>
<script setup lang="ts">
-import { useDialog, type DialogReactive } from "naive-ui";
-import { onMounted, ref } from "vue";
+import { onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import SigninModal from "@/views/auth/SigninModal.vue";
import { t } from "./plugins/i18n";
+import { AUTH_PASSWORD_RESET_MODULE } from "./router/auth";
import { WORKSPACE_ROOT_MODULE } from "./router/dashboard/workspaceRoutes";
-import { useActuatorV1Store, useAuthStore, pushNotification } from "./store";
+import { useAuthStore, pushNotification } from "./store";
// Check expiration every 15 sec and:
// 1. logout if expired.
@@ -19,22 +19,24 @@ const CHECK_LOGGEDIN_STATE_DURATION = 15 * 1000;
const router = useRouter();
const authStore = useAuthStore();
-const actuatorStore = useActuatorV1Store();
-const dialog = useDialog();
-const $dialog = ref<DialogReactive | undefined>();
const prevLoggedIn = ref(false);
onMounted(() => {
- prevLoggedIn.value = authStore.isLoggedIn();
+ if (!authStore.isLoggedIn) {
+ return;
+ }
+ if (authStore.requireResetPassword) {
+ router.replace({
+ name: AUTH_PASSWORD_RESET_MODULE,
+ });
+ return;
+ }
- setInterval(() => {
- if (!actuatorStore.initialized) {
- return;
- }
-
- const loggedIn = authStore.isLoggedIn();
+ prevLoggedIn.value = authStore.isLoggedIn;
- if (prevLoggedIn.value != loggedIn) {
+ setInterval(() => {
+ const loggedIn = authStore.isLoggedIn;
+ if (prevLoggedIn.value !== loggedIn) {
prevLoggedIn.value = loggedIn;
if (!loggedIn) {
authStore.showLoginModal = true;
@@ -47,32 +49,30 @@ onMounted(() => {
return;
}
}
+ }, CHECK_LOGGEDIN_STATE_DURATION);
+});
+
+// When current user changed, we need to redirect to the workspace root page.
+watch(
+ () => authStore.currentUserName,
+ (currentUserName, prevCurrentUserName) => {
if (
- loggedIn &&
- authStore.currentUserId !== authStore.getUserIdFromCookie() &&
- $dialog.value === undefined
+ currentUserName &&
+ prevCurrentUserName &&
+ currentUserName !== prevCurrentUserName
) {
- $dialog.value = dialog.create({
+ router.push({
+ name: WORKSPACE_ROOT_MODULE,
+ // to force route reload
+ query: { _r: Date.now() },
+ });
+ pushNotification({
+ module: "bytebase",
+ style: "INFO",
title: t("auth.login-as-another.title"),
- content: t("auth.login-as-another.content"),
- type: "warning",
- autoFocus: false,
- closable: false,
- maskClosable: false,
- closeOnEsc: false,
- onPositiveClick() {
- authStore.restoreUser().then(() => {
- router.push({
- name: WORKSPACE_ROOT_MODULE,
- // to force route reload
- query: { _r: Date.now() },
- });
- });
- },
- positiveText: t("common.confirm"),
- showIcon: false,
+ description: t("auth.login-as-another.content"),
});
}
- }, CHECK_LOGGEDIN_STATE_DURATION);
-});
+ }
+);
</script>
diff --git a/frontend/src/axios.ts b/frontend/src/axios.ts
new file mode 100644
index 0000000000..a2a9a91c6e
--- /dev/null
+++ b/frontend/src/axios.ts
@@ -0,0 +1,54 @@
+import axios from "axios";
+import { isDev } from "./utils";
+import { isSilent } from "./plugins/silent-request";
+import { pushNotification } from "./store";
+
+axios.defaults.timeout = 30000;
+axios.interceptors.request.use((request) => {
+ if (isDev() && request.url!.startsWith("/api")) {
+ console.debug(
+ request.method?.toUpperCase() + " " + request.url + " request",
+ JSON.stringify(request, null, 2)
+ );
+ }
+
+ return request;
+});
+
+axios.interceptors.response.use(
+ (response) => {
+ if (isDev() && response.config.url!.startsWith("/api")) {
+ console.debug(
+ response.config.method?.toUpperCase() +
+ " " +
+ response.config.url +
+ " response",
+ JSON.stringify(response.data, null, 2)
+ );
+ }
+ return response;
+ },
+ async (error) => {
+ if (error.response) {
+ if (error.response.data?.message && !isSilent()) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: error.response.data.message,
+ // If server enables --debug, then the response will include the detailed error.
+ description: error.response.data.error
+ ? error.response.data.error
+ : undefined,
+ });
+ }
+ } else if (error.code == "ECONNABORTED" && !isSilent()) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "Connecting server timeout. Make sure the server is running.",
+ });
+ }
+
+ throw error;
+ }
+);
diff --git a/frontend/src/components/IssueV1/logic/review.ts b/frontend/src/components/IssueV1/logic/review.ts
index a0b05e41a6..1ba0a16d68 100644
--- a/frontend/src/components/IssueV1/logic/review.ts
+++ b/frontend/src/components/IssueV1/logic/review.ts
@@ -1,10 +1,10 @@
import { computed, unref, watchEffect } from "vue";
import {
candidatesOfApprovalStepV1,
- useAuthStore,
batchGetOrFetchUsers,
+ useCurrentUserV1,
+ userNamePrefix,
} from "@/store";
-import { userNamePrefix } from "@/store/modules/v1/common";
import type {
ReviewFlow,
MaybeRef,
@@ -96,8 +96,10 @@ export const useWrappedReviewStepsV1 = (
issue: MaybeRef<ComposedIssue>,
context: ReviewContext
) => {
+ const currentUser = useCurrentUserV1();
+ // Format: users/{email}
const currentUserName = computed(
- () => `${userNamePrefix}${useAuthStore().currentUser.email}`
+ () => `${userNamePrefix}${currentUser.value.email}`
);
watchEffect(async () => {
diff --git a/frontend/src/components/RegenerateRecoveryCodesView.vue b/frontend/src/components/RegenerateRecoveryCodesView.vue
index 959a56bb7a..1fbcdf26f6 100644
--- a/frontend/src/components/RegenerateRecoveryCodesView.vue
+++ b/frontend/src/components/RegenerateRecoveryCodesView.vue
@@ -19,9 +19,9 @@
<script lang="ts" setup>
import { NButton } from "naive-ui";
-import { computed, onMounted, reactive } from "vue";
+import { onMounted, reactive } from "vue";
import { useI18n } from "vue-i18n";
-import { pushNotification, useAuthStore, useUserStore } from "@/store";
+import { pushNotification, useCurrentUserV1, useUserStore } from "@/store";
import { UpdateUserRequest } from "@/types/proto/v1/user_service";
import RecoveryCodesView from "./RecoveryCodesView.vue";
@@ -41,13 +41,11 @@ const props = withDefaults(
const emit = defineEmits(["close"]);
const { t } = useI18n();
-const authStore = useAuthStore();
const userStore = useUserStore();
const state = reactive<LocalState>({
recoveryCodesDownloaded: false,
});
-
-const currentUser = computed(() => authStore.currentUser);
+const currentUser = useCurrentUserV1();
onMounted(() => {
regenerateTempMfaSecret();
diff --git a/frontend/src/components/v2/Model/PagedTable.vue b/frontend/src/components/v2/Model/PagedTable.vue
index 6d7ccb5c1f..b663b18ff9 100644
--- a/frontend/src/components/v2/Model/PagedTable.vue
+++ b/frontend/src/components/v2/Model/PagedTable.vue
@@ -36,7 +36,7 @@ import { useDebounceFn } from "@vueuse/core";
import { sortBy, uniq } from "lodash-es";
import { NSelect, NButton } from "naive-ui";
import { computed, reactive, watch, ref, type Ref } from "vue";
-import { useIsLoggedIn, useCurrentUserV1 } from "@/store";
+import { useAuthStore, useCurrentUserV1 } from "@/store";
import { useDynamicLocalStorage, getDefaultPagination } from "@/utils";
type LocalState = {
@@ -77,6 +77,7 @@ const emit = defineEmits<{
(event: "list:update", list: T[]): void;
}>();
+const authStore = useAuthStore();
const currentUser = useCurrentUserV1();
const options = computed(() => {
@@ -105,8 +106,6 @@ const sessionState = useDynamicLocalStorage<SessionState>(
}
);
-const isLoggedIn = useIsLoggedIn();
-
const pageSize = computed(() => {
const sizeInSession = sessionState.value.pageSize ?? 0;
if (!options.value.find((o) => o.value === sizeInSession)) {
@@ -121,7 +120,7 @@ const onPageSizeChange = (size: number) => {
};
const fetchData = async (refresh = false) => {
- if (!isLoggedIn.value) {
+ if (!authStore.isLoggedIn) {
return;
}
@@ -181,12 +180,14 @@ if (Date.now() - sessionState.value.updatedTs > SESSION_LIFE) {
resetSession();
}
fetchData(true);
-watch(isLoggedIn, () => {
- // Reset session when logged out.
- if (!isLoggedIn.value) {
+
+watch(
+ () => authStore.currentUserName,
+ () => {
+ // Reset session when logging status changed.
resetSession();
}
-});
+);
watch(
() => dataList.value,
diff --git a/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts b/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts
index 3fc35d3181..31ec8c61fb 100644
--- a/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts
+++ b/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts
@@ -2,6 +2,7 @@ import { ClientError, ServerError, Status } from "nice-grpc-common";
import type { ClientMiddleware } from "nice-grpc-web";
import { router } from "@/router";
import { useAuthStore } from "@/store";
+import { UserServiceDefinition } from "@/types/proto/v1/user_service";
export type IgnoreErrorsOptions = {
/**
@@ -36,6 +37,13 @@ export const authInterceptorMiddleware: ClientMiddleware<IgnoreErrorsOptions> =
// omit specified errors
} else {
if (code === Status.UNAUTHENTICATED) {
+ // Skip show login modal when the request is to get current user.
+ if (
+ call.method.path ===
+ `/${UserServiceDefinition.fullName}/${UserServiceDefinition.methods.getCurrentUser.name}`
+ ) {
+ return;
+ }
// When receiving 401 and is returned by our server, it means the current
// login user's token becomes invalid. Thus we force the user to login again.
useAuthStore().showLoginModal = true;
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 2ef8d22ab3..069936424d 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -1,5 +1,4 @@
import { VueQueryPlugin } from "@tanstack/vue-query";
-import axios from "axios";
import "core-js/stable";
import Long from "long";
import protobufjs from "protobufjs";
@@ -9,14 +8,19 @@ import App from "./App.vue";
import "./assets/css/github-markdown-style.css";
import "./assets/css/inter.css";
import "./assets/css/tailwind.css";
+import "./axios";
import dayjs from "./plugins/dayjs";
import highlight from "./plugins/highlight";
import i18n from "./plugins/i18n";
import NaiveUI from "./plugins/naive-ui";
-import { isSilent } from "./plugins/silent-request";
import "./polyfill";
import { router } from "./router";
-import { pinia, pushNotification } from "./store";
+import {
+ pinia,
+ useActuatorV1Store,
+ useAuthStore,
+ useSubscriptionV1Store,
+} from "./store";
import {
humanizeTs,
humanizeDurationV1,
@@ -31,69 +35,33 @@ protobufjs.configure();
console.debug("dev:", isDev());
console.debug("release:", isRelease());
-axios.defaults.timeout = 30000;
-axios.interceptors.request.use((request) => {
- if (isDev() && request.url!.startsWith("/api")) {
- console.debug(
- request.method?.toUpperCase() + " " + request.url + " request",
- JSON.stringify(request, null, 2)
- );
- }
+(async () => {
+ const app = createApp(App);
- return request;
-});
+ // Allow template to access various function
+ app.config.globalProperties.window = window;
+ app.config.globalProperties.console = console;
+ app.config.globalProperties.dayjs = dayjs;
+ app.config.globalProperties.humanizeTs = humanizeTs;
+ app.config.globalProperties.humanizeDurationV1 = humanizeDurationV1;
+ app.config.globalProperties.humanizeDate = humanizeDate;
+ app.config.globalProperties.isDev = isDev();
+ app.config.globalProperties.isRelease = isRelease();
-axios.interceptors.response.use(
- (response) => {
- if (isDev() && response.config.url!.startsWith("/api")) {
- console.debug(
- response.config.method?.toUpperCase() +
- " " +
- response.config.url +
- " response",
- JSON.stringify(response.data, null, 2)
- );
- }
- return response;
- },
- async (error) => {
- if (error.response) {
- if (error.response.data?.message && !isSilent()) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: error.response.data.message,
- // If server enables --debug, then the response will include the detailed error.
- description: error.response.data.error
- ? error.response.data.error
- : undefined,
- });
- }
- } else if (error.code == "ECONNABORTED" && !isSilent()) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: "Connecting server timeout. Make sure the server is running.",
- });
- }
+ app.use(pinia);
- throw error;
- }
-);
+ const initStores = async () => {
+ await Promise.all([
+ useActuatorV1Store().fetchServerInfo(),
+ useSubscriptionV1Store().fetchSubscription(),
+ useSubscriptionV1Store().fetchFeatureMatrix(),
+ useAuthStore().fetchCurrentUser(),
+ ]);
+ };
-const app = createApp(App);
-// Allow template to access various function
-app.config.globalProperties.window = window;
-app.config.globalProperties.console = console;
-app.config.globalProperties.dayjs = dayjs;
-app.config.globalProperties.humanizeTs = humanizeTs;
-app.config.globalProperties.humanizeDurationV1 = humanizeDurationV1;
-app.config.globalProperties.humanizeDate = humanizeDate;
-app.config.globalProperties.isDev = isDev();
-app.config.globalProperties.isRelease = isRelease();
+ await initStores();
-app.use(VueQueryPlugin);
-app.use(pinia);
+ app.use(router).use(highlight).use(i18n).use(NaiveUI).use(VueQueryPlugin);
-app.use(router).use(highlight).use(i18n).use(NaiveUI);
-app.mount("#app");
+ app.mount("#app");
+})();
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index b3fb073806..ca012f6930 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -66,14 +66,13 @@ export const router = createRouter({
router.beforeEach((to, from, next) => {
console.debug("Router %s -> %s", from.name, to.name);
+ const actuatorStore = useActuatorV1Store();
+ const authStore = useAuthStore();
+ const routerStore = useRouterStore();
const disallowNavigateAwaySQLEditor = useAppFeature(
"bb.feature.disallow-navigate-to-console"
);
- const authStore = useAuthStore();
- const routerStore = useRouterStore();
- const isLoggedIn = authStore.isLoggedIn();
-
const fromModule = from.name
? from.name.toString().split(".")[0]
: WORKSPACE_ROOT_MODULE;
@@ -110,6 +109,7 @@ router.beforeEach((to, from, next) => {
to.name === AUTH_SIGNIN_ADMIN_MODULE ||
to.name === AUTH_SIGNUP_MODULE ||
to.name === AUTH_MFA_MODULE ||
+ to.name === AUTH_PASSWORD_RESET_MODULE ||
to.name === AUTH_PASSWORD_FORGOT_MODULE
) {
useSQLEditorTabStore().reset();
@@ -119,18 +119,10 @@ router.beforeEach((to, from, next) => {
import("@/plugins/ai/store").then(({ useConversationStore }) => {
useConversationStore().reset();
});
- if (isLoggedIn) {
- if (typeof to.query.redirect === "string") {
- location.replace(to.query.redirect);
- return;
- }
- next({ name: WORKSPACE_ROOT_MODULE, replace: true });
- } else {
- next();
- }
+ next();
return;
} else {
- if (!isLoggedIn) {
+ if (!authStore.isLoggedIn) {
const query: any = {
...(to.query || {}),
};
@@ -168,10 +160,9 @@ router.beforeEach((to, from, next) => {
}
const currentUserV1 = useCurrentUserV1();
- const serverInfo = useActuatorV1Store().serverInfo;
// If 2FA is required, redirect to MFA setup page if the user has not enabled 2FA.
- if (hasFeature("bb.feature.2fa") && serverInfo?.require2fa) {
+ if (hasFeature("bb.feature.2fa") && actuatorStore.serverInfo?.require2fa) {
const user = currentUserV1.value;
if (user && !user.mfaEnabled) {
next({
diff --git a/frontend/src/store/modules/auth.ts b/frontend/src/store/modules/auth.ts
index 8816a6cb32..7560e1284a 100644
--- a/frontend/src/store/modules/auth.ts
+++ b/frontend/src/store/modules/auth.ts
@@ -10,54 +10,45 @@ import {
AUTH_MFA_MODULE,
} from "@/router/auth";
import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";
-import { useAppFeature, useUserStore, useSettingV1Store } from "@/store";
-import { unknownUser } from "@/types";
+import { useAppFeature, useSettingV1Store, useUserStore } from "@/store";
+import { UNKNOWN_USER_NAME, unknownUser } from "@/types";
import type { LoginRequest } from "@/types/proto/v1/auth_service";
import { LoginResponse } from "@/types/proto/v1/auth_service";
import { DatabaseChangeMode } from "@/types/proto/v1/setting_service";
import { User, UserType } from "@/types/proto/v1/user_service";
-import { getIntCookie } from "@/utils";
export const useAuthStore = defineStore("auth_v1", () => {
const userStore = useUserStore();
- const currentUserId = ref<number | undefined>();
const showLoginModal = ref<boolean>(false);
+ // Format: users/{user}. {user} is a system-generated unique ID.
+ const currentUserName = ref<string | undefined>(undefined);
- const currentUser = computed(() => {
- if (currentUserId.value) {
- return (
- userStore.getUserByIdentifier(`${currentUserId.value}`) ?? unknownUser()
- );
- }
- return unknownUser();
+ const isLoggedIn = computed(() => {
+ return (
+ Boolean(currentUserName.value) &&
+ currentUserName.value !== UNKNOWN_USER_NAME
+ );
});
- const isLoggedIn = () => {
- return getUserIdFromCookie() != undefined;
- };
-
- const getUserIdFromCookie = () => {
- return getIntCookie("user");
- };
-
const requireResetPassword = computed(() => {
- if (!currentUserId.value) {
+ if (!isLoggedIn.value) {
return false;
}
return useLocalStorage<boolean>(
- `${currentUserId.value}.require_reset_password`,
+ `${currentUserName.value}.require_reset_password`,
false
).value;
});
const setRequireResetPassword = (requireResetPassword: boolean) => {
- if (currentUserId.value) {
- const needResetPasswordCache = useLocalStorage<boolean>(
- `${currentUserId.value}.require_reset_password`,
- false
- );
- needResetPasswordCache.value = requireResetPassword;
+ if (!isLoggedIn.value) {
+ return false;
}
+ const needResetPasswordCache = useLocalStorage<boolean>(
+ `${currentUserName.value}.require_reset_password`,
+ false
+ );
+ needResetPasswordCache.value = requireResetPassword;
};
const getRedirectQuery = () => {
@@ -70,7 +61,6 @@ export const useAuthStore = defineStore("auth_v1", () => {
redirect: string = ""
) => {
const { data } = await axios.post<LoginResponse>("/v1/auth/login", request);
-
const redirectUrl = redirect || getRedirectQuery();
if (data.mfaTempToken) {
return router.push({
@@ -82,7 +72,7 @@ export const useAuthStore = defineStore("auth_v1", () => {
});
}
- await restoreUser();
+ await fetchCurrentUser();
setRequireResetPassword(data.requireResetPassword);
await useSettingV1Store().getOrFetchSettingByName(
@@ -112,7 +102,6 @@ export const useAuthStore = defineStore("auth_v1", () => {
return router.replace(nextPage);
}
- showLoginModal.value = false;
};
const signup = async (request: Partial<User>) => {
@@ -134,7 +123,6 @@ export const useAuthStore = defineStore("auth_v1", () => {
const logout = async () => {
try {
await axios.post("/v1/auth/logout");
- showLoginModal.value = false;
} catch {
// nothing
} finally {
@@ -151,25 +139,22 @@ export const useAuthStore = defineStore("auth_v1", () => {
}
};
- const restoreUser = async () => {
- currentUserId.value = getUserIdFromCookie();
- if (currentUserId.value) {
- await useUserStore().getOrFetchUserByIdentifier(
- String(currentUserId.value),
- true // silent
- );
+ const fetchCurrentUser = async () => {
+ try {
+ const currentUser = await userStore.fetchCurrentUser();
+ currentUserName.value = currentUser.name;
+ } catch {
+ // do nothing.
}
};
return {
- currentUser,
- currentUserId,
+ currentUserName,
isLoggedIn,
- getUserIdFromCookie,
login,
signup,
logout,
- restoreUser,
+ fetchCurrentUser,
requireResetPassword,
setRequireResetPassword,
showLoginModal,
@@ -178,10 +163,10 @@ export const useAuthStore = defineStore("auth_v1", () => {
export const useCurrentUserV1 = () => {
const authStore = useAuthStore();
- return computed(() => authStore.currentUser);
-};
-
-export const useIsLoggedIn = () => {
- const store = useAuthStore();
- return computed(() => store.isLoggedIn() && store.currentUser.name !== "");
+ const userStore = useUserStore();
+ return computed(
+ () =>
+ userStore.getUserByIdentifier(authStore.currentUserName || "") ||
+ unknownUser()
+ );
};
diff --git a/frontend/src/store/modules/user.ts b/frontend/src/store/modules/user.ts
index b3aa9524b5..5aa448deec 100644
--- a/frontend/src/store/modules/user.ts
+++ b/frontend/src/store/modules/user.ts
@@ -65,6 +65,12 @@ export const useUserStore = defineStore("user", () => {
return getOrFetchUserByIdentifier(SYSTEM_BOT_USER_NAME);
});
+ const fetchCurrentUser = async () => {
+ const user = await userServiceClient.getCurrentUser({});
+ setUser(user);
+ return user;
+ };
+
const fetchUserList = async (params: {
pageSize: number;
pageToken?: string;
@@ -167,6 +173,7 @@ export const useUserStore = defineStore("user", () => {
return {
allUser,
systemBotUser,
+ fetchCurrentUser,
fetchUserList,
createUser,
updateUser,
diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.ts
index 69fe3d339c..3a38bc3a4e 100644
--- a/frontend/src/utils/util.ts
+++ b/frontend/src/utils/util.ts
@@ -155,18 +155,6 @@ export function randomString(
return result;
}
-export function getIntCookie(name: string): number | undefined {
- const list = document.cookie.split(";");
- for (let i = 0; i < list.length; i++) {
- const parts = list[i].split("=");
- if (parts[0].trim() == name) {
- return parts.length > 1 ? parseInt(parts[1]) : undefined;
- }
- }
-
- return undefined;
-}
-
export function getHighlightHTMLByKeyWords(s: string, k: string) {
if (!k) return s;
return s.replaceAll(k, `<b class="text-accent">${k}</b>`);
diff --git a/frontend/src/utils/v1/worksheet.ts b/frontend/src/utils/v1/worksheet.ts
index f0b2ce35c6..82d3aad92f 100644
--- a/frontend/src/utils/v1/worksheet.ts
+++ b/frontend/src/utils/v1/worksheet.ts
@@ -1,4 +1,4 @@
-import { useAuthStore, useProjectV1Store } from "@/store";
+import { useCurrentUserV1, useProjectV1Store } from "@/store";
import { extractUserId } from "@/store/modules/v1/common";
import { UNKNOWN_PROJECT_NAME } from "@/types";
import type { Worksheet } from "@/types/proto/v1/worksheet_service";
@@ -16,9 +16,9 @@ export const extractWorksheetUID = (name: string) => {
// PROJECT_WRITE: workspace Owner/DBA and all members in the project.
// PROJECT_READ: workspace Owner/DBA and all members in the project.
export const isWorksheetReadableV1 = (sheet: Worksheet) => {
- const authStore = useAuthStore();
+ const currentUser = useCurrentUserV1();
- if (extractUserId(sheet.creator) === authStore.currentUser.email) {
+ if (extractUserId(sheet.creator) === currentUser.value.email) {
// Always readable to the creator
return true;
}
@@ -47,9 +47,9 @@ export const isWorksheetReadableV1 = (sheet: Worksheet) => {
// PROJECT_WRITE: workspace Owner/DBA and all members in the project.
// PROJECT_READ: workspace Owner/DBA and project owner.
export const isWorksheetWritableV1 = (sheet: Worksheet) => {
- const authStore = useAuthStore();
+ const currentUser = useCurrentUserV1();
- if (extractUserId(sheet.creator) === authStore.currentUser.email) {
+ if (extractUserId(sheet.creator) === currentUser.value.email) {
// Always writable to the creator
return true;
}
diff --git a/frontend/src/views/ProfileDashboard.vue b/frontend/src/views/ProfileDashboard.vue
index 43bdd68cd0..d359a8c311 100644
--- a/frontend/src/views/ProfileDashboard.vue
+++ b/frontend/src/views/ProfileDashboard.vue
@@ -157,10 +157,7 @@
<FeatureBadge :feature="'bb.feature.2fa'" custom-class="ml-2" />
</span>
<div class="space-x-2">
- <NButton
- v-if="user.email === currentUserV1.email"
- @click="enable2FA"
- >
+ <NButton v-if="user.email === currentUser.email" @click="enable2FA">
{{ isMFAEnabled ? $t("common.edit") : $t("common.enable") }}
</NButton>
<NButton v-if="isMFAEnabled" @click="disable2FA">
@@ -197,7 +194,7 @@
</p>
<RegenerateRecoveryCodesView
v-if="state.showRegenerateRecoveryCodesView"
- :recovery-codes="authStore.currentUser.recoveryCodes"
+ :recovery-codes="currentUser.recoveryCodes"
@close="state.showRegenerateRecoveryCodesView = false"
/>
</template>
@@ -247,7 +244,6 @@ import {
featureToRef,
pushNotification,
useActuatorV1Store,
- useAuthStore,
useCurrentUserV1,
useSettingV1Store,
useUserStore,
@@ -284,8 +280,7 @@ const { t } = useI18n();
const router = useRouter();
const actuatorStore = useActuatorV1Store();
const settingV1Store = useSettingV1Store();
-const authStore = useAuthStore();
-const currentUserV1 = useCurrentUserV1();
+const currentUser = useCurrentUserV1();
const userStore = useUserStore();
const workspaceStore = useWorkspaceV1Store();
const permissionStore = usePermissionStore();
@@ -338,21 +333,21 @@ const isMFAEnabled = computed(() => {
// only user can regenerate their recovery-codes.
const showRegenerateRecoveryCodes = computed(() => {
- return user.value.mfaEnabled && user.value.name === currentUserV1.value.name;
+ return user.value.mfaEnabled && user.value.name === currentUser.value.name;
});
const user = computedAsync(() => {
if (props.principalEmail) {
return userStore.getOrFetchUserByIdentifier(props.principalEmail);
}
- return currentUserV1.value;
+ return currentUser.value;
}, unknownUser());
const userRoles = computed(() => {
return [...workspaceStore.getWorkspaceRolesByEmail(user.value.email)];
});
-const isSelf = computed(() => currentUserV1.value.name === user.value.name);
+const isSelf = computed(() => currentUser.value.name === user.value.name);
// User can change her own info.
// Besides, owner can also change anyone's info. This is for resetting password in case user forgets.
diff --git a/frontend/src/views/TwoFactorSetup.vue b/frontend/src/views/TwoFactorSetup.vue
index 1268a00126..d7324515e5 100644
--- a/frontend/src/views/TwoFactorSetup.vue
+++ b/frontend/src/views/TwoFactorSetup.vue
@@ -91,7 +91,7 @@ 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, useAuthStore, useUserStore } from "@/store";
+import { pushNotification, useCurrentUserV1, useUserStore } from "@/store";
import { UpdateUserRequest } from "@/types/proto/v1/user_service";
const issuerName = "Bytebase";
@@ -115,7 +115,6 @@ const props = defineProps<{
const { t } = useI18n();
const router = useRouter();
-const authStore = useAuthStore();
const userStore = useUserStore();
const state = reactive<LocalState>({
currentStep: SETUP_AUTH_APP_STEP,
@@ -124,6 +123,7 @@ const state = reactive<LocalState>({
otpCode: "",
recoveryCodesDownloaded: false,
});
+const currentUser = useCurrentUserV1();
const stepTabList = computed(() => {
return [
@@ -131,7 +131,7 @@ const stepTabList = computed(() => {
{ title: t("two-factor.setup-steps.download-recovery-codes.self") },
];
});
-const currentUser = computed(() => authStore.currentUser);
+
const allowNext = computed(() => {
if (state.currentStep === SETUP_AUTH_APP_STEP) {
return state.otpCode.length >= 6;
diff --git a/frontend/src/views/auth/SigninModal.vue b/frontend/src/views/auth/SigninModal.vue
index b3cd2cd31b..0bf81d4e31 100644
--- a/frontend/src/views/auth/SigninModal.vue
+++ b/frontend/src/views/auth/SigninModal.vue
@@ -22,14 +22,27 @@
<script lang="tsx" setup>
import { NButton } from "naive-ui";
+import { watch } from "vue";
+import { useRoute } from "vue-router";
import { BBModal } from "@/bbkit";
import { useAuthStore } from "@/store";
import Signin from "@/views/auth/Signin.vue";
+const route = useRoute();
const authStore = useAuthStore();
const logout = () => {
authStore.showLoginModal = false;
authStore.logout();
};
+
+// Auto-close the modal when the route changed.
+watch(
+ () => route.name,
+ () => {
+ if (authStore.showLoginModal) {
+ authStore.showLoginModal = false;
+ }
+ }
+);
</script>