Skip to content

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

Open OAuth in a child window and pass oauth result back to parent window

天舟267258a3ce82
diff --git a/frontend/src/components/ProjectRepositorySetupPanel.vue b/frontend/src/components/ProjectRepositorySetupPanel.vue
index 0f548855af..736f1517c9 100644
--- a/frontend/src/components/ProjectRepositorySetupPanel.vue
+++ b/frontend/src/components/ProjectRepositorySetupPanel.vue
@@ -6,7 +6,6 @@
>
<template v-slot:0="{ next }">
<RepositoryVCSPanel
- :config="state.config"
@select-vcs="
(vcs) => {
next();
diff --git a/frontend/src/components/RepositoryVCSPanel.vue b/frontend/src/components/RepositoryVCSPanel.vue
index d598a52c94..4c0396c23d 100644
--- a/frontend/src/components/RepositoryVCSPanel.vue
+++ b/frontend/src/components/RepositoryVCSPanel.vue
@@ -16,20 +16,25 @@
<script lang="ts">
import { reactive } from "@vue/reactivity";
import { useStore } from "vuex";
-import { computed, PropType, watchEffect } from "@vue/runtime-core";
-import { ProjectRepoConfig, VCS } from "../types";
+import { computed, onUnmounted, watchEffect } from "@vue/runtime-core";
+import isEmpty from "lodash-es/isEmpty";
+import {
+ OAuthWindowEvent,
+ OAuthWindowEventPayload,
+ openWindowForVCSOAuth,
+ VCS,
+} from "../types";
-interface LocalState {}
+interface LocalState {
+ selectedVCS?: VCS;
+}
+
+var newWindow;
export default {
name: "RepositoryVCSPanel",
emits: ["select-vcs"],
- props: {
- config: {
- required: true,
- type: Object as PropType<ProjectRepoConfig>,
- },
- },
+ props: {},
components: {},
setup(props, { emit }) {
const store = useStore();
@@ -45,8 +50,29 @@ export default {
return store.getters["vcs/vcsList"]();
});
+ const eventListener = (event: Event) => {
+ const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;
+ if (isEmpty(payload.error)) {
+ emit("select-vcs", state.selectedVCS);
+ } else {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: payload.error,
+ });
+ }
+ };
+
+ onUnmounted(() => {
+ window.removeEventListener(OAuthWindowEvent, eventListener);
+ });
+
const selectVCS = (vcs: VCS) => {
- emit("select-vcs", vcs);
+ state.selectedVCS = vcs;
+ const newWindow = openWindowForVCSOAuth(vcs);
+ if (newWindow) {
+ window.addEventListener(OAuthWindowEvent, eventListener, false);
+ }
};
return {
diff --git a/frontend/src/components/VCSCard.vue b/frontend/src/components/VCSCard.vue
index 0f0e4efc28..39054cf95a 100644
--- a/frontend/src/components/VCSCard.vue
+++ b/frontend/src/components/VCSCard.vue
@@ -55,7 +55,7 @@
focus:outline-none
focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500
"
- @click.prevent="linkVCS(vcs)"
+ @click.prevent="linkVCS"
>
<template v-if="vcs.type.startsWith('GITLAB')">
Link this GitLab instance
@@ -69,9 +69,17 @@
</template>
<script lang="ts">
-import { reactive, PropType } from "vue";
-import { VCS, redirectURL, oauthStateKey, OAuthState } from "../types";
-import { randomString } from "../utils";
+import { reactive, PropType, onUnmounted } from "vue";
+import { useStore } from "vuex";
+import {
+ VCS,
+ redirectURL,
+ OAuthWindowEvent,
+ OAuthWindowEventPayload,
+ openWindowForVCSOAuth,
+ VCSTokenCreate,
+} from "../types";
+import { isEmpty } from "lodash";
interface LocalState {}
@@ -85,25 +93,33 @@ export default {
},
},
setup(props, ctx) {
+ const store = useStore();
const state = reactive<LocalState>({});
- const linkVCS = (vcs: VCS) => {
- // Set state in current session to prevent CSRF
- const state = randomString(40);
- const oauthState: OAuthState = {
- resourceType: "VCS",
- resourceId: vcs.id,
- };
- sessionStorage.setItem(oauthStateKey(state), JSON.stringify(oauthState));
+ const eventListener = (event: Event) => {
+ const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;
+ if (isEmpty(payload.error)) {
+ const tokenCreate: VCSTokenCreate = {
+ code: payload.code,
+ redirectURL: redirectURL(),
+ };
+ store.dispatch("vcs/createVCSToken", {
+ vcsId: props.vcs.id,
+ tokenCreate,
+ });
+ } else {
+ }
+ };
+
+ onUnmounted(() => {
+ window.removeEventListener(OAuthWindowEvent, eventListener);
+ });
- window.open(
- `${vcs.instanceURL}/oauth/authorize?client_id=${
- vcs.applicationId
- }&redirect_uri=${encodeURIComponent(
- redirectURL()
- )}&response_type=code&state=${state}`,
- "_blank"
- );
+ const linkVCS = () => {
+ const newWindow = openWindowForVCSOAuth(props.vcs);
+ if (newWindow) {
+ window.addEventListener(OAuthWindowEvent, eventListener, false);
+ }
};
return {
diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.ts
index 7724a2dc12..55c9fc7a05 100644
--- a/frontend/src/types/oauth.ts
+++ b/frontend/src/types/oauth.ts
@@ -1,13 +1,29 @@
-import { VCSId } from "./id";
+import { randomString } from "../utils";
+import { VCS } from "./vcs";
-export type OAuthResourceType = "VCS";
-export type OAuthResourceId = VCSId;
+export const OAuthStateSessionKey = "oauthstate";
-export type OAuthState = {
- resourceType: OAuthResourceType;
- resourceId: OAuthResourceId;
+export const OAuthWindowEvent = "oauthevent";
+export type OAuthWindowEventPayload = {
+ error: string;
+ code: string;
};
-export function oauthStateKey(state: string): string {
- return "oauthstate." + state;
+export function redirectURL(): string {
+ return `${window.location.origin}/oauth/callback`;
+}
+
+export function openWindowForVCSOAuth(vcs: VCS): Window | null {
+ const stateQueryParameter = randomString(40);
+ sessionStorage.setItem(OAuthStateSessionKey, stateQueryParameter);
+
+ return window.open(
+ `${vcs.instanceURL}/oauth/authorize?client_id=${
+ vcs.applicationId
+ }&redirect_uri=${encodeURIComponent(
+ redirectURL()
+ )}&response_type=code&state=${stateQueryParameter}`,
+ "oauth",
+ "location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes"
+ );
}
diff --git a/frontend/src/types/vcs.ts b/frontend/src/types/vcs.ts
index 9eb818fd3d..9cf35b8153 100644
--- a/frontend/src/types/vcs.ts
+++ b/frontend/src/types/vcs.ts
@@ -51,10 +51,6 @@ export type VCSTokenCreate = {
redirectURL: string;
};
-export function isValidApplicationIdOrSecret(str: string): boolean {
+export function isValidVCSApplicationIdOrSecret(str: string): boolean {
return /^[a-zA-Z0-9_]{64}$/.test(str);
}
-
-export function redirectURL(): string {
- return `${window.location.origin}/oauth/callback`;
-}
diff --git a/frontend/src/views/OAuthCallback.vue b/frontend/src/views/OAuthCallback.vue
index 929193464c..2b5e9ebb97 100644
--- a/frontend/src/views/OAuthCallback.vue
+++ b/frontend/src/views/OAuthCallback.vue
@@ -1,64 +1,70 @@
<template>
- <h1>OAuth callback</h1>
+ <div class="p-4">
+ <div>{{ state.message }}</div>
+ <button
+ v-if="state.hasError"
+ type="button"
+ class="btn-normal mt-2"
+ @click.prevent="window.close()"
+ >
+ Close
+ </button>
+ </div>
</template>
<script lang="ts">
+import { reactive } from "@vue/reactivity";
import { useRouter } from "vue-router";
-import { useStore } from "vuex";
import {
- OAuthState,
- oauthStateKey,
- redirectURL,
- VCSTokenCreate,
+ OAuthStateSessionKey,
+ OAuthWindowEvent,
+ OAuthWindowEventPayload,
} from "../types";
+
+interface LocalState {
+ message: string;
+ hasError: boolean;
+}
+
export default {
name: "OAuthCallback",
components: {},
props: {},
setup(props, ctx) {
- const store = useStore();
const router = useRouter();
- const item = router.currentRoute.value.query.state
- ? sessionStorage.getItem(
- oauthStateKey(router.currentRoute.value.query.state as string)
- )
- : undefined;
- if (!item) {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: `Invalid state passed to the oauth callback`,
- });
- router.replace({
- name: "setting.workspace.version-control",
- });
+ const state = reactive<LocalState>({
+ message: "",
+ hasError: false,
+ });
+
+ const payload: OAuthWindowEventPayload = {
+ error: "",
+ code: "",
+ };
+ const expectedState = sessionStorage.getItem(OAuthStateSessionKey);
+ if (
+ !expectedState ||
+ expectedState != router.currentRoute.value.query.state
+ ) {
+ state.hasError = true;
+ state.message =
+ "Failed to authorize. Invalid state passed to the oauth callback.";
+ payload.error = state.message;
} else {
- const oauthState = JSON.parse(item) as OAuthState;
- if (
- !oauthState ||
- oauthState.resourceType != "VCS" ||
- !oauthState.resourceId
- ) {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: `Invalid oauth session state`,
- });
- router.replace({
- name: "setting.workspace.version-control",
- });
- } else {
- const tokenCreate: VCSTokenCreate = {
- code: router.currentRoute.value.query.code as string,
- redirectURL: redirectURL(),
- };
- store.dispatch("vcs/createVCSToken", {
- vcsId: oauthState.resourceId,
- tokenCreate,
- });
- }
+ state.message =
+ "Successfully authorized. Redirecting back to the application...";
+ payload.code = router.currentRoute.value.query.code as string;
}
+
+ window.opener.dispatchEvent(
+ new CustomEvent(OAuthWindowEvent, { detail: payload })
+ );
+ window.close();
+
+ return {
+ state,
+ };
},
};
</script>
diff --git a/frontend/src/views/SettingWorkspaceVCS.vue b/frontend/src/views/SettingWorkspaceVCS.vue
index 61cbce4f50..1753169374 100644
--- a/frontend/src/views/SettingWorkspaceVCS.vue
+++ b/frontend/src/views/SettingWorkspaceVCS.vue
@@ -32,7 +32,11 @@ import VCSProviderSelectionPanel from "./VCSProviderSelectionPanel.vue";
import VCSProviderInfoPanel from "./VCSProviderInfoPanel.vue";
import VCSProviderConfigPanel from "./VCSProviderConfigPanel.vue";
import VCSCard from "../components/VCSCard.vue";
-import { isValidApplicationIdOrSecret, VCSConfig, VCSCreate } from "../types";
+import {
+ isValidVCSApplicationIdOrSecret,
+ VCSConfig,
+ VCSCreate,
+} from "../types";
import { isURL } from "../utils";
import { useStore } from "vuex";
@@ -89,8 +93,8 @@ export default {
return isURL(state.config.instanceURL);
} else if (state.currentStep == 2) {
return (
- isValidApplicationIdOrSecret(state.config.applicationId) &&
- isValidApplicationIdOrSecret(state.config.secret)
+ isValidVCSApplicationIdOrSecret(state.config.applicationId) &&
+ isValidVCSApplicationIdOrSecret(state.config.secret)
);
}
return true;
diff --git a/frontend/src/views/VCSProviderConfigPanel.vue b/frontend/src/views/VCSProviderConfigPanel.vue
index 9e0d9aaae3..b50a4c9562 100644
--- a/frontend/src/views/VCSProviderConfigPanel.vue
+++ b/frontend/src/views/VCSProviderConfigPanel.vue
@@ -29,7 +29,7 @@
import { onUnmounted, PropType, reactive } from "@vue/runtime-core";
import isEmpty from "lodash-es/isEmpty";
import {
- isValidApplicationIdOrSecret,
+ isValidVCSApplicationIdOrSecret,
TEXT_VALIDATION_DELAY,
VCSConfig,
} from "../types";
@@ -53,10 +53,10 @@ export default {
const state = reactive<LocalState>({
showApplicationIdError:
!isEmpty(props.config.applicationId) &&
- !isValidApplicationIdOrSecret(props.config.applicationId),
+ !isValidVCSApplicationIdOrSecret(props.config.applicationId),
showSecretError:
!isEmpty(props.config.secret) &&
- !isValidApplicationIdOrSecret(props.config.secret),
+ !isValidVCSApplicationIdOrSecret(props.config.secret),
});
onUnmounted(() => {
@@ -70,20 +70,20 @@ export default {
clearInterval(state.applicationIdValidationTimer);
// If text becomes valid, we immediately clear the error.
// otherwise, we delay TEXT_VALIDATION_DELAY to do the validation in case there is continous keystroke.
- if (isValidApplicationIdOrSecret(props.config.applicationId)) {
+ if (isValidVCSApplicationIdOrSecret(props.config.applicationId)) {
state.showApplicationIdError = false;
} else {
state.applicationIdValidationTimer = setTimeout(() => {
// If error is already displayed, we hide the error only if there is valid input.
// Otherwise, we hide the error if input is either empty or valid.
if (state.showApplicationIdError) {
- state.showApplicationIdError = !isValidApplicationIdOrSecret(
+ state.showApplicationIdError = !isValidVCSApplicationIdOrSecret(
props.config.applicationId
);
} else {
state.showApplicationIdError =
- !isValidApplicationIdOrSecret(props.config.applicationId) &&
- !isValidApplicationIdOrSecret(props.config.applicationId);
+ !isValidVCSApplicationIdOrSecret(props.config.applicationId) &&
+ !isValidVCSApplicationIdOrSecret(props.config.applicationId);
}
}, TEXT_VALIDATION_DELAY);
}
@@ -95,20 +95,20 @@ export default {
clearInterval(state.secretValidationTimer);
// If text becomes valid, we immediately clear the error.
// otherwise, we delay TEXT_VALIDATION_DELAY to do the validation in case there is continous keystroke.
- if (isValidApplicationIdOrSecret(props.config.secret)) {
+ if (isValidVCSApplicationIdOrSecret(props.config.secret)) {
state.showSecretError = false;
} else {
state.secretValidationTimer = setTimeout(() => {
// If error is already displayed, we hide the error only if there is valid input.
// Otherwise, we hide the error if input is either empty or valid.
if (state.showSecretError) {
- state.showSecretError = !isValidApplicationIdOrSecret(
+ state.showSecretError = !isValidVCSApplicationIdOrSecret(
props.config.secret
);
} else {
state.showSecretError =
!isEmpty(props.config.secret) &&
- !isValidApplicationIdOrSecret(props.config.secret);
+ !isValidVCSApplicationIdOrSecret(props.config.secret);
}
}, TEXT_VALIDATION_DELAY);
}