Skip to content

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

chore: use redirect instead of open a new window when sign in with SSO (#5071)

boojackac0cec6a1d58
diff --git a/frontend/src/components/SchemaEditor/Modals/ActionConfirmModal.vue b/frontend/src/components/SchemaEditor/Modals/ActionConfirmModal.vue
index bfacd0216f..b68f82a26e 100644
--- a/frontend/src/components/SchemaEditor/Modals/ActionConfirmModal.vue
+++ b/frontend/src/components/SchemaEditor/Modals/ActionConfirmModal.vue
@@ -11,7 +11,7 @@
<button type="button" class="btn-cancel" @click="dismissModal">
{{ $t("common.cancel") }}
</button>
- <button class="btn-primary" @click="handleConfirmButtonClick">
+ <button :class="`btn-${props.style}`" @click="handleConfirmButtonClick">
{{ $t("common.confirm") }}
</button>
</div>
@@ -19,17 +19,19 @@
</template>
<script lang="ts" setup>
-import { PropType } from "vue";
-
const props = defineProps({
title: {
- type: String as PropType<string>,
+ type: String,
default: "",
},
description: {
- type: String as PropType<string>,
+ type: String,
default: "",
},
+ style: {
+ type: String,
+ default: "primary",
+ },
});
const emit = defineEmits<{
diff --git a/frontend/src/utils/sso.ts b/frontend/src/utils/sso.ts
index fbdaa566b0..44dad6d803 100644
--- a/frontend/src/utils/sso.ts
+++ b/frontend/src/utils/sso.ts
@@ -6,16 +6,27 @@ import {
IdentityProviderType,
} from "@/types/proto/v1/idp_service";
+export const SSOConfigSessionKey = "sso-config";
+
// defaultOIDCScopes is a list of scopes that are part of OIDC standard claims. Same as backend.
const defaultOIDCScopes = ["openid", "profile", "email"];
export async function openWindowForSSO(
- identityProvider: IdentityProvider
-): Promise<Window | null> {
- // we use type to determine oauth type when receiving the callback
+ identityProvider: IdentityProvider,
+ openAsPopup = true
+) {
const stateQueryParameter = `bb.oauth.signin.${identityProvider.name}`;
sessionStorage.setItem(OAuthStateSessionKey, stateQueryParameter);
+ // Set SSO config in session storage so that we can use it in the callback page.
+ sessionStorage.setItem(
+ SSOConfigSessionKey,
+ JSON.stringify({
+ identityProviderName: identityProvider.name,
+ openAsPopup,
+ })
+ );
+ let authUrl = "";
if (identityProvider.type === IdentityProviderType.OAUTH2) {
const oauth2Config = identityProvider.config?.oauth2Config;
if (!oauth2Config) {
@@ -25,15 +36,11 @@ export async function openWindowForSSO(
const redirectUrl = encodeURIComponent(
`${window.location.origin}/oauth/callback`
);
- return window.open(
- `${oauth2Config.authUrl}?client_id=${
- oauth2Config.clientId
- }&redirect_uri=${redirectUrl}&state=${stateQueryParameter}&response_type=code&scope=${encodeURIComponent(
- oauth2Config.scopes.join(" ")
- )}`,
- "oauth",
- "location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes"
- );
+ authUrl = `${oauth2Config.authUrl}?client_id=${
+ oauth2Config.clientId
+ }&redirect_uri=${redirectUrl}&state=${stateQueryParameter}&response_type=code&scope=${encodeURIComponent(
+ oauth2Config.scopes.join(" ")
+ )}`;
} else if (identityProvider.type === IdentityProviderType.OIDC) {
const oidcConfig = identityProvider.config?.oidcConfig;
if (!oidcConfig) {
@@ -56,18 +63,28 @@ export async function openWindowForSSO(
const redirectUrl = encodeURIComponent(
`${window.location.origin}/oidc/callback`
);
- return window.open(
- `${openidConfig.authorization_endpoint}?client_id=${
- oidcConfig.clientId
- }&redirect_uri=${redirectUrl}&state=${stateQueryParameter}&response_type=code&scope=${encodeURIComponent(
- oidcConfig.scopes.join(" ")
- )}`,
- "oidc",
- "location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes"
- );
+ authUrl = `${openidConfig.authorization_endpoint}?client_id=${
+ oidcConfig.clientId
+ }&redirect_uri=${redirectUrl}&state=${stateQueryParameter}&response_type=code&scope=${encodeURIComponent(
+ oidcConfig.scopes.join(" ")
+ )}`;
} else {
throw new Error(
`identity provider type ${identityProvider.type.toString()} is not supported`
);
}
+
+ if (!authUrl) {
+ throw new Error("Invalid authentication URL");
+ }
+ if (openAsPopup) {
+ window.open(
+ authUrl,
+ "oauth",
+ "location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes"
+ );
+ } else {
+ // Redirect to the auth URL.
+ window.location.href = authUrl;
+ }
}
diff --git a/frontend/src/views/OAuthCallback.vue b/frontend/src/views/OAuthCallback.vue
index c60bf8ce7d..c75f06642f 100644
--- a/frontend/src/views/OAuthCallback.vue
+++ b/frontend/src/views/OAuthCallback.vue
@@ -1,33 +1,43 @@
<template>
<div class="p-4">
<div>{{ state.message }}</div>
- <button
- v-if="state.hasError"
- type="button"
- class="btn-normal mt-2"
- @click="window.close()"
- >
- Close
- </button>
+ <div v-if="state.hasError" class="mt-2">
+ <button
+ v-if="state.openAsPopup"
+ type="button"
+ class="btn-normal"
+ @click="window.close()"
+ >
+ Close
+ </button>
+ <router-link v-else to="/auth" class="btn-normal"
+ >Back to Sign in</router-link
+ >
+ </div>
</div>
</template>
<script lang="ts" setup>
-import { nextTick, onMounted, reactive } from "vue";
+import { useAuthStore } from "@/store";
+import { SSOConfigSessionKey } from "@/utils/sso";
+import { onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { OAuthWindowEventPayload, OAuthStateSessionKey } from "../types";
interface LocalState {
message: string;
hasError: boolean;
+ openAsPopup: boolean;
payload: OAuthWindowEventPayload;
}
const router = useRouter();
+const authStore = useAuthStore();
const state = reactive<LocalState>({
message: "",
hasError: false,
+ openAsPopup: true,
payload: {
error: "",
code: "",
@@ -42,49 +52,75 @@ onMounted(() => {
"Failed to authorize. Invalid state passed to the oauth callback.";
state.payload.error = state.message;
} else {
- state.message =
- "Successfully authorized. Redirecting back to the application...";
+ state.message = "Successfully authorized. Redirecting back to Bytebase...";
state.payload.code = router.currentRoute.value.query.code as string;
}
- closeWindow();
+ triggerAuthCallback();
});
-const closeWindow = () => {
+const triggerAuthCallback = async () => {
if (state.hasError) {
window.opener.dispatchEvent(
new CustomEvent("bb.oauth.unknown", {
detail: state.payload,
})
);
- } else {
- const eventName = sessionStorage.getItem(OAuthStateSessionKey) || "";
- const eventType = eventName.slice(0, eventName.lastIndexOf("."));
- if (eventName.startsWith("bb.oauth.signin")) {
+ return;
+ }
+
+ const eventName = sessionStorage.getItem(OAuthStateSessionKey) || "";
+ const eventType = eventName.slice(0, eventName.lastIndexOf("."));
+ if (eventName.startsWith("bb.oauth.signin")) {
+ const ssoConfig = JSON.parse(
+ sessionStorage.getItem(SSOConfigSessionKey) || "{}"
+ );
+ if (ssoConfig.openAsPopup) {
window.opener.dispatchEvent(
new CustomEvent(eventName, {
detail: state.payload,
})
);
- } else if (
- eventName.startsWith("bb.oauth.register-vcs") ||
- eventName.startsWith("bb.oauth.link-vcs-repository")
- ) {
- window.opener.dispatchEvent(
- new CustomEvent(eventType, {
- detail: state.payload,
- })
- );
+ window.close();
} else {
- window.opener.dispatchEvent(
- new CustomEvent("bb.oauth.unknown", {
- detail: state.payload,
- })
- );
+ const mfaTempToken = await authStore.login({
+ idpName: ssoConfig.identityProviderName,
+ idpContext: {
+ oauth2Context: {
+ code: state.payload.code,
+ },
+ },
+ web: true,
+ });
+ state.openAsPopup = false;
+ if (mfaTempToken) {
+ router.push({
+ name: "auth.mfa",
+ query: {
+ mfaTempToken,
+ redirect: "",
+ },
+ });
+ } else {
+ router.push("/");
+ }
}
- }
-
- nextTick(() => {
+ } else if (
+ eventName.startsWith("bb.oauth.register-vcs") ||
+ eventName.startsWith("bb.oauth.link-vcs-repository")
+ ) {
+ window.opener.dispatchEvent(
+ new CustomEvent(eventType, {
+ detail: state.payload,
+ })
+ );
window.close();
- });
+ } else {
+ window.opener.dispatchEvent(
+ new CustomEvent("bb.oauth.unknown", {
+ detail: state.payload,
+ })
+ );
+ window.close();
+ }
};
</script>
diff --git a/frontend/src/views/ProfileDashboard.vue b/frontend/src/views/ProfileDashboard.vue
index 75721ab7f8..4f02a39d3c 100644
--- a/frontend/src/views/ProfileDashboard.vue
+++ b/frontend/src/views/ProfileDashboard.vue
@@ -242,6 +242,7 @@
v-if="state.showDisable2FAConfirmModal"
:title="$t('two-factor.disable.self')"
:description="$t('two-factor.disable.description')"
+ :style="'danger'"
@close="state.showDisable2FAConfirmModal = false"
@confirm="handleDisable2FA"
/>
diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vue
index d3d32a7d12..7dbfea7926 100644
--- a/frontend/src/views/auth/Signin.vue
+++ b/frontend/src/views/auth/Signin.vue
@@ -145,10 +145,9 @@
</template>
<script lang="ts" setup>
-import { computed, onMounted, onUnmounted, reactive, watch } from "vue";
+import { computed, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
-import { OAuthWindowEventPayload } from "@/types";
import { isValidEmail, openWindowForSSO } from "@/utils";
import {
featureToRef,
@@ -156,17 +155,13 @@ import {
useAuthStore,
useIdentityProviderStore,
} from "@/store";
-import {
- IdentityProvider,
- IdentityProviderType,
-} from "@/types/proto/v1/idp_service";
+import { IdentityProvider } from "@/types/proto/v1/idp_service";
import AuthFooter from "./AuthFooter.vue";
interface LocalState {
email: string;
password: string;
showPassword: boolean;
- activeIdentityProvider?: IdentityProvider;
}
const actuatorStore = useActuatorStore();
@@ -208,69 +203,6 @@ onMounted(async () => {
await identityProviderStore.fetchIdentityProviderList();
});
-onUnmounted(() => {
- if (state.activeIdentityProvider) {
- window.removeEventListener(
- `bb.oauth.signin.${state.activeIdentityProvider.name}`,
- loginWithIdentityProviderEventListener,
- false
- );
- }
-});
-
-watch(
- () => state.activeIdentityProvider?.name,
- (newValue, oldValue) => {
- window.removeEventListener(
- `bb.oauth.signin.${oldValue}`,
- loginWithIdentityProviderEventListener,
- false
- );
- window.addEventListener(
- `bb.oauth.signin.${newValue}`,
- loginWithIdentityProviderEventListener,
- false
- );
- }
-);
-
-const loginWithIdentityProviderEventListener = async (event: Event) => {
- if (!state.activeIdentityProvider) {
- return;
- }
-
- if (
- state.activeIdentityProvider.type === IdentityProviderType.OAUTH2 ||
- state.activeIdentityProvider.type === IdentityProviderType.OIDC
- ) {
- const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;
- if (payload.error) {
- return;
- }
-
- const mfaTempToken = await authStore.login({
- idpName: state.activeIdentityProvider.name,
- idpContext: {
- oauth2Context: {
- code: payload.code,
- },
- },
- web: true,
- });
- if (mfaTempToken) {
- router.push({
- name: "auth.mfa",
- query: {
- mfaTempToken,
- redirect: "",
- },
- });
- } else {
- router.push("/");
- }
- }
-};
-
const allowSignin = computed(() => {
return isValidEmail(state.email) && state.password;
});
@@ -297,7 +229,6 @@ const trySignin = async () => {
const trySigninWithIdentityProvider = async (
identityProvider: IdentityProvider
) => {
- state.activeIdentityProvider = identityProvider;
- await openWindowForSSO(identityProvider);
+ await openWindowForSSO(identityProvider, false);
};
</script>