Skip to content

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

feat: added Gitlab Login (#321)

Luke Zhoue8d7c64413f8
diff --git a/api/auth.go b/api/auth.go
index 53c71e62f9..bb47840aa3 100644
--- a/api/auth.go
+++ b/api/auth.go
@@ -1,5 +1,23 @@
package api
+import "github.com/bytebase/bytebase/plugin/vcs"
+
+type AuthProvider struct {
+ Type *vcs.Type `jsonapi:"attr,type"`
+ InstanceURL string `jsonapi:"attr,instanceUrl"`
+ ApplicationID string `jsonapi:"attr,applicationId"`
+ // Secret will be used for OAuth on the client side when user choose to login via Gitlab
+ Secret string `jsonapi:"attr,secret"`
+}
+
+// GitlabLogin is the API message for logins via Gitlab.
+type GitlabLogin struct {
+ InstanceURL string `jsonapi:"attr,instanceUrl"`
+ ApplicationID string `jsonapi:"attr,applicationId"`
+ Secret string `jsonapi:"attr,secret"`
+ AccessToken string `jsonapi:"attr,accessToken"`
+}
+
// Login is the API message for logins.
type Login struct {
// Domain specific fields
diff --git a/api/principal.go b/api/principal.go
index bcd7700d06..878c40a7cc 100644
--- a/api/principal.go
+++ b/api/principal.go
@@ -28,6 +28,13 @@ func (e PrincipalType) String() string {
return ""
}
+type PrincipalAuthProvider string
+
+const (
+ PrincipalAuthProviderBytebase PrincipalAuthProvider = "BYTEBASE"
+ PrincipalAuthProviderGitlabSelfHost PrincipalAuthProvider = "GITLAB_SELF_HOST"
+)
+
// Principal is the API message for principals.
type Principal struct {
ID int `jsonapi:"primary,principal"`
@@ -39,9 +46,10 @@ type Principal struct {
UpdatedTs int64 `jsonapi:"attr,updatedTs"`
// Domain specific fields
- Type PrincipalType `jsonapi:"attr,type"`
- Name string `jsonapi:"attr,name"`
- Email string `jsonapi:"attr,email"`
+ Type PrincipalType `jsonapi:"attr,type"`
+ AuthProvider PrincipalAuthProvider `jsonapi:"attr,authProvider"`
+ Name string `jsonapi:"attr,name"`
+ Email string `jsonapi:"attr,email"`
// Do not return to the client
PasswordHash string
// Role is stored in the member table, but we include it when returning the principal.
@@ -53,25 +61,27 @@ type Principal struct {
// can map directly to the frontend Principal object without any conversion.
func (p *Principal) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
- ID int `json:"id"`
- CreatorID int `json:"creatorId"`
- CreatedTs int64 `json:"createdTs"`
- UpdaterID int `json:"updaterId"`
- UpdatedTs int64 `json:"updatedTs"`
- Type PrincipalType `json:"type"`
- Name string `json:"name"`
- Email string `json:"email"`
- Role Role `json:"role"`
+ ID int `json:"id"`
+ CreatorID int `json:"creatorId"`
+ CreatedTs int64 `json:"createdTs"`
+ UpdaterID int `json:"updaterId"`
+ UpdatedTs int64 `json:"updatedTs"`
+ Type PrincipalType `json:"type"`
+ AuthProvider PrincipalAuthProvider `json:"authProvider"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Role Role `json:"role"`
}{
- ID: p.ID,
- CreatorID: p.CreatorID,
- CreatedTs: p.CreatedTs,
- UpdaterID: p.UpdaterID,
- UpdatedTs: p.UpdatedTs,
- Type: p.Type,
- Name: p.Name,
- Email: p.Email,
- Role: p.Role,
+ ID: p.ID,
+ CreatorID: p.CreatorID,
+ CreatedTs: p.CreatedTs,
+ UpdaterID: p.UpdaterID,
+ UpdatedTs: p.UpdatedTs,
+ Type: p.Type,
+ AuthProvider: p.AuthProvider,
+ Name: p.Name,
+ Email: p.Email,
+ Role: p.Role,
})
}
@@ -84,6 +94,7 @@ type PrincipalCreate struct {
// Domain specific fields
Type PrincipalType
+ AuthProvider PrincipalAuthProvider
Name string `jsonapi:"attr,name"`
Email string `jsonapi:"attr,email"`
Password string `jsonapi:"attr,password"`
diff --git a/frontend/src/components/ProfileDropdown.vue b/frontend/src/components/ProfileDropdown.vue
index ba143482b6..4824ad4d2e 100644
--- a/frontend/src/components/ProfileDropdown.vue
+++ b/frontend/src/components/ProfileDropdown.vue
@@ -203,22 +203,31 @@ export default {
const switchToOwner = () => {
store.dispatch("auth/login", {
- email: "[email protected]",
- password: "1024",
+ authProvider: "BYTEBASE",
+ payload: {
+ email: "[email protected]",
+ password: "1024",
+ },
});
};
const switchToDBA = () => {
store.dispatch("auth/login", {
- email: "[email protected]",
- password: "aaa",
+ authProvider: "BYTEBASE",
+ payload: {
+ email: "[email protected]",
+ password: "aaa",
+ },
});
};
const switchToDeveloper = () => {
store.dispatch("auth/login", {
- email: "[email protected]",
- password: "aaa",
+ authProvider: "BYTEBASE",
+ payload: {
+ email: "[email protected]",
+ password: "aaa",
+ },
});
};
diff --git a/frontend/src/components/RepositoryVCSProviderPanel.vue b/frontend/src/components/RepositoryVCSProviderPanel.vue
index 9b32294594..2967bf3eee 100644
--- a/frontend/src/components/RepositoryVCSProviderPanel.vue
+++ b/frontend/src/components/RepositoryVCSProviderPanel.vue
@@ -119,7 +119,8 @@ export default {
state.selectedVCS = vcs;
const newWindow = openWindowForOAuth(
`${vcs.instanceUrl}/oauth/authorize`,
- vcs.applicationId
+ vcs.applicationId,
+ "register"
);
if (newWindow) {
window.addEventListener(OAuthWindowEvent, eventListener, false);
diff --git a/frontend/src/components/VCSSetupWizard.vue b/frontend/src/components/VCSSetupWizard.vue
index 999f072460..baaedcf60a 100644
--- a/frontend/src/components/VCSSetupWizard.vue
+++ b/frontend/src/components/VCSSetupWizard.vue
@@ -150,7 +150,8 @@ export default {
if (state.currentStep == OAUTH_INFO_STEP && newStep > oldStep) {
const newWindow = openWindowForOAuth(
`${state.config.instanceUrl}/oauth/authorize`,
- state.config.applicationId
+ state.config.applicationId,
+ "register"
);
if (newWindow) {
state.oAuthResultCallback = (token: OAuthToken | undefined) => {
diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.yml
index 31b2e2b05c..7c066a311a 100644
--- a/frontend/src/locales/en.yml
+++ b/frontend/src/locales/en.yml
@@ -577,6 +577,7 @@ auth:
admin-account: admin account
forget-password: Forgot your password?
new-user: New to Bytebase?
+ third-party: You can reach to your Admin to enable third party login.
password-forget:
title: Forgot your password?
content: Please contact your Bytebase Admin to reset your password.
@@ -923,6 +924,8 @@ version-control:
scripts will automatically trigger the corresponding database change.
Bytebase owners manage all the applicable VCSs here, so that project
owners can link the projects with their Git repositories from these VCSs.
+ **Once configured, Bytebase will enable third party login via your
+ configured VCSs**
add-git-provider:
self: Add a Git provider
description: >-
diff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.yml
index c04137854c..fe12cd34dd 100644
--- a/frontend/src/locales/zh-CN.yml
+++ b/frontend/src/locales/zh-CN.yml
@@ -524,6 +524,7 @@ auth:
title: 登录您的账号
forget-password: 忘记密码?
new-user: 第一次使用 Bytebase?
+ third-party: 您可联系管理员开启第三方认证登录
password-forget:
title: 忘记了您的密码?
content: 请联系的您的 Bytebase 管理员重置密码
@@ -815,7 +816,7 @@ version-control:
description: >-
Bytebase 支持 GitOps 工作流。该工作流下,数据库迁移脚本存储在版本控制系统上
(VCS),新创建的迁移脚本会自动触发对应的数据库变更。Bytebase 的所有者先在此配置 VCS,在这之后,项目的所有者就可以从所配置的 VCS
- 中选取他们的 Git 仓库。
+ 中选取他们的 Git 仓库。 **配置VCS后,Bytebase 将自动开启通过 VCS 的第三方认证登录**
add-git-provider:
self: 添加 Git 提供方
description: >-
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 8fec5770df..702e6d8ba4 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -796,7 +796,9 @@ router.beforeEach((to, from, next) => {
to.name === SIGNUP_MODULE ||
to.name === ACTIVATE_MODULE ||
to.name === PASSWORD_RESET_MODULE ||
- to.name === PASSWORD_FORGOT_MODULE
+ to.name === PASSWORD_FORGOT_MODULE ||
+ // this is for oauth login
+ to.name === "oauth-callback"
) {
if (isLoggedIn) {
next({ name: HOME_MODULE, replace: true });
diff --git a/frontend/src/store/modules/auth.ts b/frontend/src/store/modules/auth.ts
index 9e986a19d0..31f87fdc4f 100644
--- a/frontend/src/store/modules/auth.ts
+++ b/frontend/src/store/modules/auth.ts
@@ -9,6 +9,8 @@ import {
ResourceObject,
unknown,
PrincipalId,
+ AuthProvider,
+ VCSLoginInfo,
} from "../../types";
import { getIntCookie } from "../../utils";
@@ -16,11 +18,20 @@ function convert(user: ResourceObject, rootGetters: any): Principal {
return rootGetters["principal/principalById"](user.id);
}
+function convertAuthProvider(authProvider: ResourceObject) {
+ return { ...authProvider.attributes };
+}
+
const state: () => AuthState = () => ({
+ authProviderList: [],
currentUser: unknown("PRINCIPAL") as Principal,
});
const getters = {
+ authProviderList: (state: AuthState) => (): AuthProvider[] => {
+ return state.authProviderList;
+ },
+
isLoggedIn: (state: AuthState) => (): boolean => {
return getIntCookie("user") != undefined;
},
@@ -31,10 +42,21 @@ const getters = {
};
const actions = {
+ async fetchProviderList({ commit }: any) {
+ const providerList = (await axios.get("/api/auth/provider")).data.data;
+ const convertedProviderList = providerList.map(
+ (provider: ResourceObject) => {
+ return convertAuthProvider(provider);
+ }
+ );
+ commit("setAuthProviderList", convertedProviderList);
+ return convertedProviderList;
+ },
+
async login({ commit, dispatch, rootGetters }: any, loginInfo: LoginInfo) {
const loggedInUser = (
- await axios.post("/api/auth/login", {
- data: { type: "loginInfo", attributes: loginInfo },
+ await axios.post(`/api/auth/login/${loginInfo.authProvider}`, {
+ data: { type: "loginInfo", attributes: loginInfo.payload },
})
).data.data;
@@ -126,6 +148,10 @@ const actions = {
};
const mutations = {
+ setAuthProviderList(state: AuthState, authProviderList: AuthProvider[]) {
+ state.authProviderList = authProviderList;
+ },
+
setCurrentUser(state: AuthState, user: Principal) {
state.currentUser = user;
},
diff --git a/frontend/src/types/auth.ts b/frontend/src/types/auth.ts
index 3feda073a5..cee794234e 100644
--- a/frontend/src/types/auth.ts
+++ b/frontend/src/types/auth.ts
@@ -1,7 +1,11 @@
// Auth
+
+// For now, a single user's auth provider should either belong to GITLAB_SELF_HOST or BYTEBASE
+export type AuthProviderType = "GITLAB_SELF_HOST" | "BYTEBASE";
+
export type LoginInfo = {
- email: string;
- password: string;
+ authProvider: AuthProviderType;
+ payload: VCSLoginInfo | BytebaseLoginInfo;
};
export type SignupInfo = {
@@ -16,3 +20,29 @@ export type ActivateInfo = {
name: string;
token: string;
};
+
+export type BytebaseLoginInfo = {
+ email: string;
+ password: string;
+};
+
+export type AuthProvider = {
+ type: AuthProviderType;
+ instanceUrl: string;
+ applicationId: string;
+ secret: string;
+};
+
+export const EmptyAuthProvider: AuthProvider = {
+ type: "BYTEBASE",
+ instanceUrl: "",
+ applicationId: "",
+ secret: "",
+};
+
+export type VCSLoginInfo = {
+ applicationId: string;
+ secret: string;
+ instanceUrl: string;
+ accessToken: string;
+};
diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.ts
index 9fa7b3bd45..a6b033de2e 100644
--- a/frontend/src/types/oauth.ts
+++ b/frontend/src/types/oauth.ts
@@ -25,11 +25,15 @@ export function redirectUrl(): string {
return `${window.location.origin}/oauth/callback`;
}
+type OAuthType = "login" | "register";
+
export function openWindowForOAuth(
endpoint: string,
- applicationId: string
+ applicationId: string,
+ type: OAuthType
): Window | null {
- const stateQueryParameter = randomString(40);
+ // we use type to determine oauth type when receiving the callback
+ const stateQueryParameter = `${type}-${randomString(20)}`;
sessionStorage.setItem(OAuthStateSessionKey, stateQueryParameter);
return window.open(
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index 4e66593e1e..6e52d49dca 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -1,4 +1,11 @@
-import { EnvironmentId, MigrationHistoryId, Policy, PolicyType, View } from ".";
+import {
+ AuthProvider,
+ EnvironmentId,
+ MigrationHistoryId,
+ Policy,
+ PolicyType,
+ View,
+} from ".";
import { Activity } from "./activity";
import { ServerInfo } from "./actuator";
import { Backup, BackupSetting } from "./backup";
@@ -44,6 +51,7 @@ export interface ActuatorState {
}
export interface AuthState {
+ authProviderList: AuthProvider[];
currentUser: Principal;
}
diff --git a/frontend/src/views/DashboardHeader.vue b/frontend/src/views/DashboardHeader.vue
index 864858bf7a..a6f607abe0 100644
--- a/frontend/src/views/DashboardHeader.vue
+++ b/frontend/src/views/DashboardHeader.vue
@@ -3,41 +3,46 @@
<div class="flex items-center">
<div class="flex-shrink-0 w-44">
<router-link to="/" class="select-none" active-class exact-active-class>
- <img class="h-12 w-auto" src="../assets/logo-full.svg" alt="Bytebase" />
+ <img
+ class="h-12 w-auto"
+ src="../assets/logo-full.svg"
+ alt="Bytebase"
+ />
</router-link>
</div>
<div class="hidden sm:block">
<div class="ml-6 flex items-baseline space-x-1">
- <router-link
- to="/project"
- class="bar-link px-2 py-2 rounded-md"
- >{{ $t("common.projects") }}</router-link>
+ <router-link to="/project" class="bar-link px-2 py-2 rounded-md">{{
+ $t("common.projects")
+ }}</router-link>
<router-link to="/db" class="bar-link px-2 py-2 rounded-md">
- {{
- $t("common.databases")
- }}
+ {{ $t("common.databases") }}
</router-link>
<router-link
v-if="showDBAItem"
to="/instance"
class="bar-link px-2 py-2 rounded-md"
- >{{ $t("common.instances") }}</router-link>
+ >{{ $t("common.instances") }}</router-link
+ >
<router-link
to="/environment"
class="bar-link px-2 py-2 rounded-md"
- >{{ $t("common.environments") }}</router-link>
+ >{{ $t("common.environments") }}</router-link
+ >
<router-link
to="/setting/member"
class="bar-link px-2 py-2 rounded-md"
- >{{ $t("common.settings") }}</router-link>
+ >{{ $t("common.settings") }}</router-link
+ >
<router-link
v-if="isDevFeatures"
to="/sql-editor"
class="bar-link px-2 py-2 rounded-md"
- >{{ $t('sql-editor.self') }}</router-link>
+ >{{ $t("sql-editor.self") }}</router-link
+ >
</div>
</div>
</div>
@@ -47,17 +52,23 @@
v-if="isDevFeatures"
class="hidden md:flex sm:flex-row items-center space-x-2 text-sm font-medium"
>
- <span class="hidden lg:block font-normal text-accent">{{ $t('setting.plan.self') }}</span>
+ <span class="hidden lg:block font-normal text-accent">{{
+ $t("setting.plan.self")
+ }}</span>
<div
class="bar-link"
:class="currentPlan == 0 ? 'underline' : ''"
@click.prevent="switchToFree"
- >{{ $t('setting.plan.free') }}</div>
+ >
+ {{ $t("setting.plan.free") }}
+ </div>
<div
class="bar-link"
:class="currentPlan == 1 ? 'underline' : ''"
@click.prevent="switchToTeam"
- >{{ $t('setting.plan.team') }}</div>
+ >
+ {{ $t("setting.plan.team") }}
+ </div>
<!-- <div
class="bar-link"
:class="currentPlan == 2 ? 'underline' : ''"
@@ -70,22 +81,30 @@
v-if="!isRelease"
class="hidden md:flex sm:flex-row items-center space-x-2 text-sm font-medium"
>
- <span class="hidden lg:block font-normal text-accent">{{ $t('settings.profile.role') }}</span>
+ <span class="hidden lg:block font-normal text-accent">{{
+ $t("settings.profile.role")
+ }}</span>
<div
class="bar-link"
:class="currentUser.role == 'OWNER' ? 'underline' : ''"
@click.prevent="switchToOwner"
- >{{ $t('common.role.owner') }}</div>
+ >
+ {{ $t("common.role.owner") }}
+ </div>
<div
class="bar-link"
:class="currentUser.role == 'DBA' ? 'underline' : ''"
@click.prevent="switchToDBA"
- >{{ $t('common.role.dba') }}</div>
+ >
+ {{ $t("common.role.dba") }}
+ </div>
<div
class="bar-link"
:class="currentUser.role == 'DEVELOPER' ? 'underline' : ''"
@click.prevent="switchToDeveloper"
- >{{ $t('common.role.developer') }}</div>
+ >
+ {{ $t("common.role.developer") }}
+ </div>
</div>
<router-link to="/inbox" exact-active-class>
<span
@@ -125,28 +144,32 @@
Open: "block", closed: "hidden"
-->
<div v-if="state.showMobileMenu" class="block md:hidden">
- <router-link
- to="/project"
- class="bar-link rounded-md block px-3 py-2"
- >{{ $t('common.projects') }}</router-link>
+ <router-link to="/project" class="bar-link rounded-md block px-3 py-2">{{
+ $t("common.projects")
+ }}</router-link>
- <router-link to="/db" class="bar-link rounded-md block px-3 py-2">{{ $t('common.databases') }}</router-link>
+ <router-link to="/db" class="bar-link rounded-md block px-3 py-2">{{
+ $t("common.databases")
+ }}</router-link>
<router-link
v-if="showDBAItem"
to="/instance"
class="bar-link rounded-md block px-3 py-2"
- >{{ $t('common.instances') }}</router-link>
+ >{{ $t("common.instances") }}</router-link
+ >
<router-link
to="/environment"
class="bar-link rounded-md block px-3 py-2"
- >{{ $t('common.environments') }}</router-link>
+ >{{ $t("common.environments") }}</router-link
+ >
<router-link
to="/setting/member"
class="bar-link rounded-md block px-3 py-2"
- >{{ $t("common.settings") }}</router-link>
+ >{{ $t("common.settings") }}</router-link
+ >
</div>
</template>
@@ -209,22 +232,31 @@ export default {
const switchToOwner = () => {
store.dispatch("auth/login", {
- email: "[email protected]",
- password: "1024",
+ authProvider: "BYTEBASE",
+ payload: {
+ email: "[email protected]",
+ password: "1024",
+ },
});
};
const switchToDBA = () => {
store.dispatch("auth/login", {
- email: "[email protected]",
- password: "2048",
+ authProvider: "BYTEBASE",
+ payload: {
+ email: "[email protected]",
+ password: "2048",
+ },
});
};
const switchToDeveloper = () => {
store.dispatch("auth/login", {
- email: "[email protected]",
- password: "4096",
+ authProvider: "BYTEBASE",
+ payload: {
+ email: "[email protected]",
+ password: "4096",
+ },
});
};
diff --git a/frontend/src/views/SettingWorkspaceVCSDetail.vue b/frontend/src/views/SettingWorkspaceVCSDetail.vue
index 1b2d45819e..9ab48fb5d7 100644
--- a/frontend/src/views/SettingWorkspaceVCSDetail.vue
+++ b/frontend/src/views/SettingWorkspaceVCSDetail.vue
@@ -6,14 +6,20 @@
class="flex flex-row items-center space-x-2"
>
<div class="textlabel whitespace-nowrap">
- {{ $t('version-control.setting.add-git-provider.gitlab-self-host-ce-ee') }}
+ {{
+ $t(
+ "version-control.setting.add-git-provider.gitlab-self-host-ce-ee"
+ )
+ }}
</div>
<img class="h-6 w-auto" src="../assets/gitlab-logo.svg" />
</div>
</div>
<div>
- <label for="instanceurl" class="textlabel"> {{ $t('common.instance') }} URL </label>
+ <label for="instanceurl" class="textlabel">
+ {{ $t("common.instance") }} URL
+ </label>
<input
id="instanceurl"
name="instanceurl"
@@ -25,9 +31,17 @@
</div>
<div>
- <label for="name" class="textlabel"> {{ $t('version-control.setting.add-git-provider.basic-info.display-name') }} </label>
+ <label for="name" class="textlabel">
+ {{
+ $t("version-control.setting.add-git-provider.basic-info.display-name")
+ }}
+ </label>
<p class="mt-1 textinfolabel">
- {{ $t('version-control.setting.add-git-provider.basic-info.display-name-label') }}
+ {{
+ $t(
+ "version-control.setting.add-git-provider.basic-info.display-name-label"
+ )
+ }}
</p>
<input
id="name"
@@ -39,13 +53,15 @@
</div>
<div>
- <label for="applicationid" class="textlabel"> {{ $t('common.application') }} ID </label>
+ <label for="applicationid" class="textlabel">
+ {{ $t("common.application") }} ID
+ </label>
<p class="mt-1 textinfolabel">
<template v-if="vcs.type == 'GITLAB_SELF_HOST'">
- {{ $t('version-control.setting.git-provider.application-id-label') }}
- <a :href="adminApplicationUrl" target="_blank" class="normal-link"
- >{{ $t('version-control.setting.git-provider.view-in-gitlab') }}</a
- >
+ {{ $t("version-control.setting.git-provider.application-id-label") }}
+ <a :href="adminApplicationUrl" target="_blank" class="normal-link">{{
+ $t("version-control.setting.git-provider.view-in-gitlab")
+ }}</a>
</template>
</p>
<input
@@ -61,7 +77,7 @@
<label for="secret" class="textlabel"> Secret </label>
<p class="mt-1 textinfolabel">
<template v-if="vcs.type == 'GITLAB_SELF_HOST'">
- {{ $t('version-control.setting.git-provider.secret-label-gitlab') }}
+ {{ $t("version-control.setting.git-provider.secret-label-gitlab") }}
</template>
</p>
<input
@@ -87,7 +103,7 @@
</template>
<template v-else>
<div class="mt-1 textinfolabel">
- {{ $t('version-control.setting.git-provider.delete') }}
+ {{ $t("version-control.setting.git-provider.delete") }}
</div>
</template>
<div>
@@ -96,7 +112,7 @@
class="btn-normal py-2 px-4"
@click.prevent="cancel"
>
- {{ $t('common.cancel') }}
+ {{ $t("common.cancel") }}
</button>
<button
type="button"
@@ -104,7 +120,7 @@
:disabled="!allowUpdate"
@click.prevent="doUpdate"
>
- {{ $t('common.update') }}
+ {{ $t("common.update") }}
</button>
</div>
</div>
@@ -112,7 +128,7 @@
<div class="py-6">
<div class="text-lg leading-6 font-medium text-main">
- {{ $t('repository.linked') + ` (${repositoryList.length})` }}
+ {{ $t("repository.linked") + ` (${repositoryList.length})` }}
</div>
<div class="mt-4">
<RepositoryTable :repository-list="repositoryList" />
@@ -229,7 +245,8 @@ export default {
) {
const newWindow = openWindowForOAuth(
`${vcs.value.instanceUrl}/oauth/authorize`,
- vcs.value.applicationId
+ vcs.value.applicationId,
+ "register"
);
if (newWindow) {
state.oAuthResultCallback = (token: OAuthToken | undefined) => {
diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vue
index 75eea088f1..b917ddaa92 100644
--- a/frontend/src/views/auth/Signin.vue
+++ b/frontend/src/views/auth/Signin.vue
@@ -9,10 +9,16 @@
<h2 class="mt-6 text-3xl leading-9 font-extrabold text-main">
{{ $t("auth.sign-in.title") }}
</h2>
+ <h2
+ v-if="authProviderList.length == 0"
+ class="text-gray-500 leading-4 tracking-wide font-light text-sm"
+ >
+ {{ $t("auth.sign-in.third-party") }}
+ </h2>
</div>
- <div class="mt-8">
- <div class="mt-6">
+ <div class="mt-4">
+ <div class="mt-4">
<form class="space-y-6" @submit.prevent="trySignin">
<div>
<label
@@ -61,14 +67,43 @@
</div>
<div>
- <span class="block w-full rounded-md shadow-sm">
+ <span class="flex w-full rounded-md items-center">
<button
type="submit"
:disabled="!allowSignin"
- class="btn-primary w-full flex justify-center py-2 px-4"
+ class="btn-primary justify-center flex-grow py-2 px-4"
>
{{ $t("common.sign-in") }}
</button>
+
+ <template
+ v-for="authProvider in authProviderList"
+ :key="authProvider.type"
+ >
+ <!-- GitLab auth provider -->
+ <n-button
+ circle
+ quaternary
+ :bordered="false"
+ @click.prevent="
+ () => {
+ state.activeAuthProvider = authProvider;
+ const window = openWindowForOAuth(
+ `${authProvider.instanceUrl}/${
+ AuthProviderConfig[authProvider.type].apiPath
+ }`,
+ authProvider.applicationId,
+ 'login'
+ );
+ }
+ "
+ >
+ <img
+ class="w-4"
+ :src="AuthProviderConfig[authProvider.type].iconPath"
+ />
+ </n-button>
+ </template>
</span>
</div>
</form>
@@ -94,16 +129,28 @@
</template>
<script lang="ts">
-import { computed, onMounted, reactive, ref } from "vue";
+import { computed, onMounted, reactive } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
-import { LoginInfo } from "../../types";
+import {
+ AuthProvider,
+ EmptyAuthProvider,
+ VCSLoginInfo,
+ LoginInfo,
+ OAuthConfig,
+ OAuthToken,
+ OAuthWindowEvent,
+ OAuthWindowEventPayload,
+ openWindowForOAuth,
+ redirectUrl,
+} from "../../types";
import { isDev, isValidEmail } from "../../utils";
import AuthFooter from "./AuthFooter.vue";
interface LocalState {
email: string;
password: string;
+ activeAuthProvider: AuthProvider;
}
export default {
@@ -116,6 +163,7 @@ export default {
const state = reactive<LocalState>({
email: "",
password: "",
+ activeAuthProvider: EmptyAuthProvider,
});
onMounted(() => {
@@ -128,16 +176,69 @@ export default {
if (store.getters["actuator/needAdminSetup"]()) {
router.push({ name: "auth.signup", replace: true });
}
+
+ store.dispatch("auth/fetchProviderList");
+ window.addEventListener(OAuthWindowEvent, eventListener, false);
});
+ const AuthProviderConfig = {
+ GITLAB_SELF_HOST: {
+ apiPath: "oauth/authorize",
+ // see https://vitejs.cn/guide/assets.html#the-public-directory for static resource import during run time
+ iconPath: new URL("../../assets/gitlab-logo.svg", import.meta.url).href,
+ },
+ };
+
const allowSignin = computed(() => {
return isValidEmail(state.email) && state.password;
});
+ const authProviderList = computed(() => {
+ return store.getters["auth/authProviderList"]();
+ });
+
+ const eventListener = (event: Event) => {
+ const payload = (event as CustomEvent).detail as OAuthWindowEventPayload;
+ if (payload.error) {
+ return;
+ }
+ const oAuthConfig: OAuthConfig = {
+ endpoint: `${state.activeAuthProvider.instanceUrl}/oauth/token`,
+ applicationId: state.activeAuthProvider.applicationId,
+ secret: state.activeAuthProvider.secret,
+ redirectUrl: redirectUrl(),
+ };
+ store
+ .dispatch("gitlab/exchangeToken", {
+ oAuthConfig,
+ code: payload.code,
+ })
+ .then((token: OAuthToken) => {
+ const gitlabLoginInfo: VCSLoginInfo = {
+ applicationId: state.activeAuthProvider!.applicationId,
+ secret: state.activeAuthProvider.secret,
+ instanceUrl: state.activeAuthProvider.instanceUrl,
+ accessToken: token.accessToken,
+ };
+
+ store
+ .dispatch("auth/login", {
+ authProvider: "GITLAB_SELF_HOST",
+ payload: gitlabLoginInfo,
+ })
+ .then(() => {
+ router.push("/");
+ });
+ });
+ };
+
const trySignin = () => {
const loginInfo: LoginInfo = {
- email: state.email,
- password: state.password,
+ authProvider: "BYTEBASE",
+ payload: {
+ email: state.email,
+ password: state.password,
+ },
};
store.dispatch("auth/login", loginInfo).then(() => {
router.push("/");
@@ -147,7 +248,10 @@ export default {
return {
state,
allowSignin,
+ authProviderList,
+ AuthProviderConfig,
trySignin,
+ openWindowForOAuth,
};
},
};
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index 97d22d8fbc..aa6ec02455 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -138,6 +138,44 @@ func (provider *Provider) APIURL(instanceURL string) string {
return fmt.Sprintf("%s/%s", instanceURL, apiPath)
}
+func (provider *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) (*vcs.UserInfo, error) {
+ resp, err := httpGet(
+ instanceURL,
+ "user",
+ &oauthCtx.AccessToken,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ if resp.StatusCode == 404 {
+ return nil, common.Errorf(common.NotFound, fmt.Errorf("failed to fetch user info from GitLab instance %s", instanceURL))
+ } else if resp.StatusCode >= 300 {
+ return nil, fmt.Errorf("failed to read user info from GitLab instance %s, status code: %d",
+ instanceURL,
+ resp.StatusCode,
+ )
+ }
+
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ UserInfo := &vcs.UserInfo{}
+ if err := json.Unmarshal(b, UserInfo); err != nil {
+ return nil, err
+ }
+
+ return UserInfo, err
+}
+
func (provider *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL string, repositoryID string, filePath string, fileCommitCreate vcs.FileCommitCreate) error {
body, err := json.Marshal(fileCommit{
Branch: fileCommitCreate.Branch,
diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.go
index ed4cdab829..2969a8c81a 100644
--- a/plugin/vcs/vcs.go
+++ b/plugin/vcs/vcs.go
@@ -65,9 +65,30 @@ type VCSPushEvent struct {
FileCommit VCSFileCommit `json:"fileCommit"`
}
+type UserState string
+
+const (
+ UserStateActive UserState = "active"
+ UserStateArchived UserState = "archived"
+)
+
+// UserInfo is the API message for user info.
+type UserInfo struct {
+ Email string `json:"email"`
+ Name string `json:"name"`
+ State UserState `json:"state"`
+}
+
type Provider interface {
// Returns the API URL for a given VCS instance URL
APIURL(instanceURL string) string
+
+ // Try to use this provider as an auth provider and fetch the user info stored at this provider
+ //
+ // oauthCtx: OAuth context to write the file content
+ // instanceURL: VCS instance URL
+ TryLogin(ctx context.Context, oauthCtx common.OauthContext, instanceURL string) (*UserInfo, error)
+
// Commits a new file
//
// oauthCtx: OAuth context to write the file content
diff --git a/server/auth.go b/server/auth.go
index b99696b1ca..7c485e28b8 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -8,30 +8,129 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
+ vcsPlugin "github.com/bytebase/bytebase/plugin/vcs"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
"golang.org/x/crypto/bcrypt"
)
func (s *Server) registerAuthRoutes(g *echo.Group) {
- g.POST("/auth/login", func(c echo.Context) error {
+
+ // for now, we only support Gitlab
+ g.GET("/auth/provider", func(c echo.Context) error {
ctx := context.Background()
- login := &api.Login{}
- if err := jsonapi.UnmarshalPayload(c.Request().Body, login); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted login request").SetInternal(err)
+ vcsFind := &api.VCSFind{}
+ list, err := s.VCSService.FindVCSList(ctx, vcsFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch vcs list").SetInternal(err)
}
- principalFind := &api.PrincipalFind{
- Email: &login.Email,
+ authProvider := make([]*api.AuthProvider, 0)
+ for _, vcs := range list {
+ newProvider := &api.AuthProvider{
+ Type: &vcs.Type,
+ InstanceURL: vcs.InstanceURL,
+ ApplicationID: vcs.ApplicationID,
+ Secret: vcs.Secret,
+ }
+ authProvider = append(authProvider, newProvider)
}
- user, err := s.PrincipalService.FindPrincipal(ctx, principalFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, authProvider); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal auth provider").SetInternal(err)
}
- if user == nil {
- return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("User not found: %s", login.Email))
+ return nil
+ })
+
+ g.POST("/auth/login/:auth_provider", func(c echo.Context) error {
+ ctx := context.Background()
+ var user *api.Principal
+
+ authProvider := api.PrincipalAuthProvider(c.Param("auth_provider"))
+ switch authProvider {
+ case api.PrincipalAuthProviderBytebase:
+ {
+ login := &api.Login{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, login); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted login request").SetInternal(err)
+ }
+
+ principalFind := &api.PrincipalFind{
+ Email: &login.Email,
+ }
+ var err error
+ user, err = s.PrincipalService.FindPrincipal(ctx, principalFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)
+ }
+ if user == nil {
+ return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("User not found: %s", login.Email))
+ }
+ // if user had already use third party method logged in, we will forbid she login via Bytebase
+ if user.AuthProvider != api.PrincipalAuthProviderBytebase {
+ return echo.NewHTTPError(http.StatusUnauthorized, "User has bond to Gitlab")
+ }
+ // Compare the stored hashed password, with the hashed version of the password that was received.
+ if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(login.Password)); err != nil {
+ // If the two passwords don't match, return a 401 status.
+ return echo.NewHTTPError(http.StatusUnauthorized, "Incorrect password").SetInternal(err)
+ }
+ }
+ case api.PrincipalAuthProviderGitlabSelfHost:
+ {
+ gitlabLogin := &api.GitlabLogin{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, gitlabLogin); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted gitlab login request").SetInternal(err)
+ }
+ GitlabUserInfo, err := vcsPlugin.Get("GITLAB_SELF_HOST", vcsPlugin.ProviderConfig{Logger: s.l}).TryLogin(ctx,
+ common.OauthContext{
+ ClientID: gitlabLogin.ApplicationID,
+ ClientSecret: gitlabLogin.Secret,
+ AccessToken: gitlabLogin.AccessToken,
+ RefreshToken: "",
+ Refresher: nil,
+ },
+ gitlabLogin.InstanceURL,
+ )
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Fail to fetch user info from gitlab").SetInternal(err)
+ }
+
+ // we only allow active user to login via gitlab
+ if GitlabUserInfo.State != vcsPlugin.UserStateActive {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Fail to login via Gitlab, user is Archived")
+ }
+
+ principalFind := &api.PrincipalFind{
+ Email: &GitlabUserInfo.Email,
+ }
+ user, err = s.PrincipalService.FindPrincipal(ctx, principalFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)
+ }
+
+ // create a new user if not exist
+ if user == nil {
+ // if user login via gitlab at the first time, we will generate a random password.
+ // The random password is supposed to be not guessable.
+ // But even one can guess the password, she won't be allowed to login.
+ // If user signs up via 3rd party login like GitLab, we will disallow bytebase builtin password/email login unless user manually switch the login option later.
+ signup := &api.Signup{
+ Email: GitlabUserInfo.Email,
+ Password: common.RandomString(20),
+ Name: GitlabUserInfo.Name,
+ }
+ var httpError *echo.HTTPError
+ user, httpError = trySignup(ctx, s, signup, api.PrincipalAuthProviderGitlabSelfHost)
+ if httpError != nil {
+ return httpError
+ }
+ }
+ }
}
+ // test the status of this user
memberFind := &api.MemberFind{
PrincipalID: &user.ID,
}
@@ -40,18 +139,12 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user").SetInternal(err)
}
if member == nil {
- return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Member not found: %s", login.Email))
+ return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Member not found: %s", user.Email))
}
if member.RowStatus == api.Archived {
return echo.NewHTTPError(http.StatusUnauthorized, "This user has been deactivated by the admin")
}
- // Compare the stored hashed password, with the hashed version of the password that was received.
- if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(login.Password)); err != nil {
- // If the two passwords don't match, return a 401 status.
- return echo.NewHTTPError(http.StatusUnauthorized, "Incorrect password").SetInternal(err)
- }
-
// If password is correct, generate tokens and set cookies.
if err := GenerateTokensAndSetCookies(c, user, s.mode, s.secret); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token").SetInternal(err)
@@ -81,88 +174,97 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted signup request").SetInternal(err)
}
- passwordHash, err := bcrypt.GenerateFromPassword([]byte(signup.Password), bcrypt.DefaultCost)
+ user, err := trySignup(ctx, s, signup, api.PrincipalAuthProviderBytebase)
if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
+ return err
}
- principalCreate := &api.PrincipalCreate{
- CreatorID: api.SystemBotID,
- Type: api.EndUser,
- Name: signup.Name,
- Email: signup.Email,
- PasswordHash: string(passwordHash),
+ if err := GenerateTokensAndSetCookies(c, user, s.mode, s.secret); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token").SetInternal(err)
}
- user, err := s.PrincipalService.CreatePrincipal(ctx, principalCreate)
- if err != nil {
- if common.ErrorCode(err) == common.Conflict {
- return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Email already exists: %s", signup.Email))
- }
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup").SetInternal(err)
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, user); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal signup response").SetInternal(err)
}
+ return nil
+ })
+}
- findRole := api.Owner
- find := &api.MemberFind{
- Role: &findRole,
+func trySignup(ctx context.Context, s *Server, signup *api.Signup, authProvider api.PrincipalAuthProvider) (*api.Principal, *echo.HTTPError) {
+ passwordHash, err := bcrypt.GenerateFromPassword([]byte(signup.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
+ }
+
+ principalCreate := &api.PrincipalCreate{
+ CreatorID: api.SystemBotID,
+ Type: api.EndUser,
+ AuthProvider: authProvider,
+ Name: signup.Name,
+ Email: signup.Email,
+ PasswordHash: string(passwordHash),
+ }
+ user, err := s.PrincipalService.CreatePrincipal(ctx, principalCreate)
+ if err != nil {
+ if common.ErrorCode(err) == common.Conflict {
+ return nil, echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Email already exists: %s", signup.Email))
}
- list, err := s.MemberService.FindMemberList(ctx, find)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup").SetInternal(err)
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup").SetInternal(err)
+ }
+
+ findRole := api.Owner
+ find := &api.MemberFind{
+ Role: &findRole,
+ }
+ list, err := s.MemberService.FindMemberList(ctx, find)
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup").SetInternal(err)
+ }
+
+ // Grant the member Owner role if there is no existing Owner member.
+ role := api.Developer
+ if len(list) == 0 {
+ role = api.Owner
+ }
+ memberCreate := &api.MemberCreate{
+ CreatorID: user.ID,
+ Status: api.Active,
+ Role: role,
+ PrincipalID: user.ID,
+ }
+
+ member, err := s.MemberService.CreateMember(ctx, memberCreate)
+ if err != nil {
+ if common.ErrorCode(err) == common.Conflict {
+ return nil, echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Member already exists: %s", signup.Email))
}
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup").SetInternal(err)
+ }
- // Grant the member Owner role if there is no existing Owner member.
- role := api.Developer
- if len(list) == 0 {
- role = api.Owner
+ {
+ bytes, err := json.Marshal(api.ActivityMemberCreatePayload{
+ PrincipalID: member.PrincipalID,
+ PrincipalName: user.Name,
+ PrincipalEmail: user.Email,
+ MemberStatus: member.Status,
+ Role: member.Role,
+ })
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)
}
- memberCreate := &api.MemberCreate{
+ activityCreate := &api.ActivityCreate{
CreatorID: user.ID,
- Status: api.Active,
- Role: role,
- PrincipalID: user.ID,
+ ContainerID: member.ID,
+ Type: api.ActivityMemberCreate,
+ Level: api.ActivityInfo,
+ Payload: string(bytes),
}
-
- member, err := s.MemberService.CreateMember(ctx, memberCreate)
+ _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
if err != nil {
- if common.ErrorCode(err) == common.Conflict {
- return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Member already exists: %s", signup.Email))
- }
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup").SetInternal(err)
- }
-
- {
- bytes, err := json.Marshal(api.ActivityMemberCreatePayload{
- PrincipalID: member.PrincipalID,
- PrincipalName: user.Name,
- PrincipalEmail: user.Email,
- MemberStatus: member.Status,
- Role: member.Role,
- })
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)
- }
- activityCreate := &api.ActivityCreate{
- CreatorID: user.ID,
- ContainerID: member.ID,
- Type: api.ActivityMemberCreate,
- Level: api.ActivityInfo,
- Payload: string(bytes),
- }
- _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after create member: %d", member.ID)).SetInternal(err)
- }
- }
-
- if err := GenerateTokensAndSetCookies(c, user, s.mode, s.secret); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token").SetInternal(err)
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after create member: %d", member.ID)).SetInternal(err)
}
+ }
- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, user); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal signup response").SetInternal(err)
- }
- return nil
- })
+ return user, nil
}
diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sql
index 1769354af3..a429250505 100644
--- a/store/migration/10001__init_schema.sql
+++ b/store/migration/10001__init_schema.sql
@@ -12,6 +12,7 @@ CREATE TABLE principal (
updater_id INTEGER NOT NULL REFERENCES principal (id),
updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
`type` TEXT NOT NULL CHECK (`type` IN ('END_USER', 'SYSTEM_BOT')),
+ auth_provider TEXT NOT NULL CHECK (auth_provider in ('BYTEBASE', 'GITLAB_SELF_HOST')),
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL
@@ -44,6 +45,7 @@ INSERT INTO
creator_id,
updater_id,
`type`,
+ auth_provider,
name,
email,
password_hash
@@ -54,6 +56,7 @@ VALUES
1,
1,
'SYSTEM_BOT',
+ 'BYTEBASE',
'Bytebase',
''
diff --git a/store/principal.go b/store/principal.go
index ef4ab63a0d..eb74d7a2b3 100644
--- a/store/principal.go
+++ b/store/principal.go
@@ -145,16 +145,18 @@ func createPrincipal(ctx context.Context, tx *Tx, create *api.PrincipalCreate) (
creator_id,
updater_id,
type,
+ auth_provider,
name,
email,
password_hash
)
- VALUES (?, ?, ?, ?, ?, ?)
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, type, name, email, password_hash
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, type, auth_provider, name, email, password_hash
`,
create.CreatorID,
create.CreatorID,
create.Type,
+ create.AuthProvider,
create.Name,
create.Email,
create.PasswordHash,
@@ -174,6 +176,7 @@ func createPrincipal(ctx context.Context, tx *Tx, create *api.PrincipalCreate) (
&principal.UpdaterID,
&principal.UpdatedTs,
&principal.Type,
+ &principal.AuthProvider,
&principal.Name,
&principal.Email,
&principal.PasswordHash,
@@ -202,6 +205,7 @@ func findPrincipalList(ctx context.Context, tx *Tx, find *api.PrincipalFind) (_
updater_id,
updated_ts,
type,
+ auth_provider,
name,
email,
password_hash
@@ -225,6 +229,7 @@ func findPrincipalList(ctx context.Context, tx *Tx, find *api.PrincipalFind) (_
&principal.UpdaterID,
&principal.UpdatedTs,
&principal.Type,
+ &principal.AuthProvider,
&principal.Name,
&principal.Email,
&principal.PasswordHash,
@@ -258,7 +263,7 @@ func patchPrincipal(ctx context.Context, tx *Tx, patch *api.PrincipalPatch) (*ap
UPDATE principal
SET `+strings.Join(set, ", ")+`
WHERE id = ?
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, type, name, email, password_hash
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, type, auth_provider, name, email, password_hash
`,
args...,
)
@@ -276,6 +281,7 @@ func patchPrincipal(ctx context.Context, tx *Tx, patch *api.PrincipalPatch) (*ap
&principal.UpdaterID,
&principal.UpdatedTs,
&principal.Type,
+ &principal.AuthProvider,
&principal.Name,
&principal.Email,
&principal.PasswordHash,
diff --git a/store/seed/test/10000__reset.sql b/store/seed/test/10000__reset.sql
index f10332160d..7c3dd25804 100644
--- a/store/seed/test/10000__reset.sql
+++ b/store/seed/test/10000__reset.sql
@@ -114,6 +114,7 @@ DELETE FROM
WHERE
id != 1;
+
-- By default, for every table, we reserve id <=100 for internal user
UPDATE
sqlite_sequence
diff --git a/store/seed/test/10001__principal.sql b/store/seed/test/10001__principal.sql
index f298f35088..7ffb58454c 100644
--- a/store/seed/test/10001__principal.sql
+++ b/store/seed/test/10001__principal.sql
@@ -6,6 +6,7 @@ INSERT INTO
creator_id,
updater_id,
`type`,
+ auth_provider,
name,
email,
password_hash
@@ -15,6 +16,7 @@ VALUES
1,
1,
'END_USER',
+ 'BYTEBASE',
'Demo Owner',
-- 1024
@@ -27,6 +29,7 @@ INSERT INTO
creator_id,
updater_id,
`type`,
+ auth_provider,
name,
email,
password_hash
@@ -36,6 +39,7 @@ VALUES
1,
1,
'END_USER',
+ 'BYTEBASE',
'Jerry DBA',
-- 2048
@@ -48,6 +52,7 @@ INSERT INTO
creator_id,
updater_id,
`type`,
+ auth_provider,
name,
email,
password_hash
@@ -57,6 +62,7 @@ VALUES
1,
1,
'END_USER',
+ 'BYTEBASE',
'Tom Dev',
-- 4096
@@ -69,6 +75,7 @@ INSERT INTO
creator_id,
updater_id,
`type`,
+ auth_provider,
name,
email,
password_hash
@@ -78,6 +85,7 @@ VALUES
1,
1,
'END_USER',
+ 'BYTEBASE',
'Jane Dev',
-- 8192