Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Use cookie instead of localstorage to determine whether user is logged in
天舟bf301b3da70d
diff --git a/backend/server/jwt.go b/backend/server/jwt.goindex a5830f4e5e..57d522d1e0 100644--- a/backend/server/jwt.go+++ b/backend/server/jwt.go@@ -135,7 +135,7 @@ func setTokenCookie(name, token string, expiration time.Time, c echo.Context) {func setUserCookie(user *api.Principal, expiration time.Time, c echo.Context) {cookie := new(http.Cookie)cookie.Name = "user"- cookie.Value = user.Name+ cookie.Value = strconv.Itoa(user.ID)cookie.Expires = expirationcookie.Path = "/"c.SetCookie(cookie)diff --git a/backend/server/server.go b/backend/server/server.goindex 060b40a41c..f81a960783 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -69,7 +69,7 @@ func NewServer(logger *bytebase.Logger) *Server {g.Use(middleware.JWTWithConfig(middleware.JWTConfig{Skipper: func(c echo.Context) bool {- return strings.HasPrefix(c.Path(), "/api/auth") || (c.Path() == "/api/principal" && c.Request().Method == "GET")+ return strings.HasPrefix(c.Path(), "/api/auth")},Claims: &Claims{},SigningMethod: middleware.AlgorithmHS256,diff --git a/frontend/src/App.vue b/frontend/src/App.vueindex e6d2707eab..8db1e91f68 100644--- a/frontend/src/App.vue+++ b/frontend/src/App.vue@@ -1,30 +1,27 @@<template>- <!-- Suspense is experimental, be aware of the potential change -->- <Suspense>- <template #default>- <ProvideContext>- <router-view />- </ProvideContext>- </template>- <template #fallback>- <div class="flex flex-row justify-between p-4 space-x-2">- <span class="items-center flex">Loading...</span>- <button- class="items-center flex justify-center btn-normal"- @click.prevent="ping"- >- Ping- </button>- </div>- </template>- </Suspense>+ <router-view />+ <template v-if="state.notificationList.length > 0">+ <BBNotification+ :placement="'BOTTOM_RIGHT'"+ :notificationList="state.notificationList"+ @close="removeNotification"+ />+ </template></template><script lang="ts">-import { onErrorCaptured } from "vue";+import { reactive, watchEffect, onErrorCaptured } from "vue";import { useStore } from "vuex";import ProvideContext from "./components/ProvideContext.vue";import { isDev } from "./utils";+import { Notification } from "./types";+import { BBNotificationItem } from "./bbkit/types";++const NOTIFICAITON_DURATION = 8000;++interface LocalState {+ notificationList: BBNotificationItem[];+}export default {name: "App",@@ -32,11 +29,45 @@ export default {setup(props, ctx) {const store = useStore();- // Restore previously logged in user if applicable.- store.dispatch("auth/restoreUser").catch((error: Error) => {- console.log(error);+ const state = reactive<LocalState>({+ notificationList: [],});+ const removeNotification = (id: string) => {+ state.notificationList.shift();+ };++ const watchNotification = () => {+ store+ .dispatch("notification/tryPopNotification", {+ module: "bytebase",+ })+ .then((notification: Notification | undefined) => {+ if (notification) {+ state.notificationList.push({+ style: notification.style,+ title: notification.title,+ description: notification.description || "",+ link: notification.link || "",+ linkTitle: notification.linkTitle || "",+ });+ // state.notification = notification;+ // We don't want user to miss "CRITICAL" notification and+ // thus don't automatically dismiss it.+ if (notification.style != "CRITICAL" && !notification.manualHide) {+ setTimeout(() => {+ removeNotification(notification.id);+ }, NOTIFICAITON_DURATION);+ }+ }+ });+ };++ watchEffect(watchNotification);++ // Restore previously logged in user if applicable.+ store.dispatch("auth/restoreUser");+onErrorCaptured((e: any, _, info) => {// If e has response, then we assume it's an http error and has already been// handled by the axios global handler.@@ -51,18 +82,9 @@ export default {return true;});- const ping = () => {- store.dispatch("debug/ping").then((message: string) => {- store.dispatch("notification/pushNotification", {- module: "bytebase",- style: "SUCCESS",- title: message,- });- });- };-return {- ping,+ state,+ removeNotification,};},};diff --git a/frontend/src/layouts/DashboardLayout.vue b/frontend/src/layouts/DashboardLayout.vueindex a16e820e8e..cb2544992e 100644--- a/frontend/src/layouts/DashboardLayout.vue+++ b/frontend/src/layouts/DashboardLayout.vue@@ -6,31 +6,33 @@<DashboardHeader /></div></nav>- <router-view name="body" />+ <!-- Suspense is experimental, be aware of the potential change -->+ <Suspense>+ <template #default>+ <ProvideContext>+ <router-view name="body" />+ </ProvideContext>+ </template>+ <template #fallback>+ <div class="flex flex-row justify-between p-4 space-x-2">+ <span class="items-center flex">Loading...</span>+ <button+ class="items-center flex justify-center btn-normal"+ @click.prevent="ping"+ >+ Ping+ </button>+ </div>+ </template>+ </Suspense></div>- <template v-if="state.notificationList.length > 0">- <BBNotification- :placement="'BOTTOM_RIGHT'"- :notificationList="state.notificationList"- @close="removeNotification"- />- </template></template><script lang="ts">-import { reactive, watchEffect, ref } from "vue";import { useStore } from "vuex";import ProvideContext from "../components/ProvideContext.vue";import DashboardHeader from "../views/DashboardHeader.vue";import BannerDemo from "../views/BannerDemo.vue";-import { Notification } from "../types";-import { BBNotificationItem } from "../bbkit/types";--const NOTIFICAITON_DURATION = 8000;--interface LocalState {- notificationList: BBNotificationItem[];-}export default {name: "DashboardLayout",@@ -38,45 +40,18 @@ export default {setup(props, ctx) {const store = useStore();- const state = reactive<LocalState>({- notificationList: [],- });-- const removeNotification = (id: string) => {- state.notificationList.shift();- };-- const watchNotification = () => {- store- .dispatch("notification/tryPopNotification", {+ const ping = () => {+ store.dispatch("debug/ping").then((message: string) => {+ store.dispatch("notification/pushNotification", {module: "bytebase",- })- .then((notification: Notification | undefined) => {- if (notification) {- state.notificationList.push({- style: notification.style,- title: notification.title,- description: notification.description || "",- link: notification.link || "",- linkTitle: notification.linkTitle || "",- });- // state.notification = notification;- // We don't want user to miss "CRITICAL" notification and- // thus don't automatically dismiss it.- if (notification.style != "CRITICAL" && !notification.manualHide) {- setTimeout(() => {- removeNotification(notification.id);- }, NOTIFICAITON_DURATION);- }- }+ style: "SUCCESS",+ title: message,});+ });};- watchEffect(watchNotification);-return {- state,- removeNotification,+ ping,};},};diff --git a/frontend/src/store/modules/auth.ts b/frontend/src/store/modules/auth.tsindex a722cd889c..6ea11a7073 100644--- a/frontend/src/store/modules/auth.ts+++ b/frontend/src/store/modules/auth.ts@@ -10,7 +10,7 @@ import {ResourceObject,unknown,} from "../../types";-import { getCookie } from "../../utils";+import { getIntCookie, removeCookie } from "../../utils";function convert(user: ResourceObject, rootGetters: any): Principal {return rootGetters["principal/principalById"](user.id);@@ -22,7 +22,7 @@ const state: () => AuthState = () => ({const getters = {isLoggedIn: (state: AuthState) => (): boolean => {- return !isEmpty(getCookie("user"));+ return getIntCookie("user") != undefined;},currentUser: (state: AuthState) => (): Principal => {@@ -41,7 +41,6 @@ const actions = {rootGetters);- localStorage.setItem("bb.auth.user", JSON.stringify(loggedInUser));commit("setCurrentUser", loggedInUser);return loggedInUser;},@@ -59,7 +58,6 @@ const actions = {// The conversion relies on the above task.const convertedUser = convert(newUser, rootGetters);- localStorage.setItem("bb.auth.user", JSON.stringify(convertedUser));commit("setCurrentUser", convertedUser);return convertedUser;@@ -81,18 +79,24 @@ const actions = {// The conversion relies on the above task to get the lastest dataconst convertedUser = convert(activatedUser, rootGetters);- localStorage.setItem("bb.auth.user", JSON.stringify(convertedUser));commit("setCurrentUser", convertedUser);return convertedUser;},- async restoreUser({ commit }: any) {- const jsonUser = localStorage.getItem("bb.auth.user");- if (jsonUser) {- const user: Principal = JSON.parse(jsonUser);- commit("setCurrentUser", user);- return user;+ async restoreUser({ commit, dispatch }: any) {+ const userId = getIntCookie("user");+ if (!isEmpty(userId)) {+ const loggedInUser = await dispatch(+ "principal/fetchPrincipalById",+ userId,+ {+ root: true,+ }+ );++ commit("setCurrentUser", loggedInUser);+ return loggedInUser;}return unknown("PRINCIPAL") as Principal;},@@ -102,14 +106,13 @@ const actions = {state.currentUser.id);if (!isEqual(refreshedUser, state.currentUser)) {- localStorage.setItem("bb.auth.user", JSON.stringify(refreshedUser));commit("setCurrentUser", refreshedUser);}return refreshedUser;},async logout({ commit }: any) {- localStorage.removeItem("bb.auth.user");+ removeCookie("user");commit("setCurrentUser", unknown("PRINCIPAL") as Principal);return unknown("PRINCIPAL") as Principal;},diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.tsindex 0ee1136ebc..f2f2181b19 100644--- a/frontend/src/utils/util.ts+++ b/frontend/src/utils/util.ts@@ -80,7 +80,19 @@ export function randomString(n?: number): string {return result;}-export function getCookie(name: string): string {+export function getIntCookie(name: string): number | undefined {+ const list = document.cookie.split(";");+ for (var i = 0; i < list.length; i++) {+ const parts = list[i].split("=");+ if (parts[0] == name) {+ return parts.length > 1 ? parseInt(parts[1]) : undefined;+ }+ }++ return undefined;+}++export function getStringCookie(name: string): string {const list = document.cookie.split(";");for (var i = 0; i < list.length; i++) {const parts = list[i].split("=");@@ -92,3 +104,17 @@ export function getCookie(name: string): string {return "";}++export function removeCookie(name: string) {+ const newList = [];+ const list = document.cookie.split(";");+ for (var i = 0; i < list.length; i++) {+ const parts = list[i].split("=");+ if (parts[0] == name) {+ newList.push(`${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT`);+ } else {+ newList.push(list[i]);+ }+ }+ document.cookie = newList.join(";");+}