Skip to content

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

chore: optimize auth (#13805)

ecmadao7c4ad6e6f797
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.go
index 6bb6dde72b..c669a23b05 100644
--- a/backend/api/auth/auth.go
+++ b/backend/api/auth/auth.go
@@ -60,7 +60,6 @@ const (
type APIAuthInterceptor struct {
store *store.Store
secret string
- tokenDuration time.Duration
licenseService enterprise.LicenseService
stateCfg *state.State
profile *config.Profile
@@ -70,7 +69,6 @@ type APIAuthInterceptor struct {
func New(
store *store.Store,
secret string,
- tokenDuration time.Duration,
licenseService enterprise.LicenseService,
stateCfg *state.State,
profile *config.Profile,
@@ -78,7 +76,6 @@ func New(
return &APIAuthInterceptor{
store: store,
secret: secret,
- tokenDuration: tokenDuration,
licenseService: licenseService,
stateCfg: stateCfg,
profile: profile,
diff --git a/backend/api/auth/header.go b/backend/api/auth/header.go
index 06c380354f..68e17b6683 100644
--- a/backend/api/auth/header.go
+++ b/backend/api/auth/header.go
@@ -9,11 +9,13 @@ import (
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
+
+ "github.com/bytebase/bytebase/backend/store"
)
// GatewayResponseModifier is the response modifier for grpc gateway.
type GatewayResponseModifier struct {
- TokenDuration time.Duration
+ Store *store.Store
}
// Modify is the mux option for modifying response header.
@@ -29,12 +31,12 @@ func (m *GatewayResponseModifier) Modify(ctx context.Context, response http.Resp
isHTTPS = true
}
}
- m.processMetadata(md, GatewayMetadataAccessTokenKey, AccessTokenCookieName, true /* httpOnly */, isHTTPS, response)
- m.processMetadata(md, GatewayMetadataUserIDKey, UserIDCookieName, false /* httpOnly */, isHTTPS, response)
+ m.processMetadata(ctx, md, GatewayMetadataAccessTokenKey, AccessTokenCookieName, true /* httpOnly */, isHTTPS, response)
+ m.processMetadata(ctx, md, GatewayMetadataUserIDKey, UserIDCookieName, false /* httpOnly */, isHTTPS, response)
return nil
}
-func (m *GatewayResponseModifier) processMetadata(md runtime.ServerMetadata, metadataKey, cookieName string, httpOnly, isHTTPS bool, response http.ResponseWriter) {
+func (m *GatewayResponseModifier) processMetadata(ctx context.Context, md runtime.ServerMetadata, metadataKey, cookieName string, httpOnly, isHTTPS bool, response http.ResponseWriter) {
values := md.HeaderMD.Get(metadataKey)
if len(values) == 0 {
return
@@ -54,6 +56,7 @@ func (m *GatewayResponseModifier) processMetadata(md runtime.ServerMetadata, met
if isHTTPS {
sameSite = http.SameSiteNoneMode
}
+ tokenDuration := GetTokenDuration(ctx, m.Store)
http.SetCookie(response, &http.Cookie{
Name: cookieName,
Value: value,
@@ -62,7 +65,7 @@ func (m *GatewayResponseModifier) processMetadata(md runtime.ServerMetadata, met
// Suppose we have a valid refresh token, we will refresh the token in 2 cases:
// 1. The access token is about to expire in <<refreshThresholdDuration>>
// 2. The access token has already expired, we refresh the token so that the ongoing request can pass through.
- Expires: time.Now().Add(m.TokenDuration - 1*time.Second),
+ Expires: time.Now().Add(tokenDuration - 1*time.Second),
Path: "/",
// Http-only helps mitigate the risk of client side script accessing the protected cookie.
HttpOnly: httpOnly,
@@ -72,3 +75,33 @@ func (m *GatewayResponseModifier) processMetadata(md runtime.ServerMetadata, met
})
}
}
+
+func GetTokenDuration(ctx context.Context, store *store.Store) time.Duration {
+ tokenDuration := DefaultTokenDuration
+
+ workspaceProfile, err := store.GetWorkspaceGeneralSetting(ctx)
+ if err != nil {
+ return tokenDuration
+ }
+ passwordRestriction, err := store.GetPasswordRestrictionSetting(ctx)
+ if err != nil {
+ return tokenDuration
+ }
+
+ if workspaceProfile.TokenDuration != nil && workspaceProfile.TokenDuration.GetSeconds() > 0 {
+ tokenDuration = workspaceProfile.TokenDuration.AsDuration()
+ }
+ // Currently we implement the password rotation restriction in a simple way:
+ // 1. Only check if users need to reset their password during login.
+ // 2. For the 1st time login, if `RequireResetPasswordForFirstLogin` is true, `require_reset_password` in the response will be true
+ // 3. Otherwise if the `PasswordRotation` exists, check the password last updated time to decide if the `require_reset_password` is true.
+ // So we will use the minimum value between (`workspaceProfile.TokenDuration`, `passwordRestriction.PasswordRotation`) to force to expire the token.
+ if passwordRestriction.PasswordRotation != nil && passwordRestriction.PasswordRotation.GetSeconds() > 0 {
+ passwordRotation := passwordRestriction.PasswordRotation.AsDuration()
+ if passwordRotation.Seconds() < tokenDuration.Seconds() {
+ tokenDuration = passwordRotation
+ }
+ }
+
+ return tokenDuration
+}
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.go
index 7d60694b24..01f96fb184 100644
--- a/backend/api/v1/auth_service.go
+++ b/backend/api/v1/auth_service.go
@@ -52,7 +52,6 @@ type AuthService struct {
v1pb.UnimplementedAuthServiceServer
store *store.Store
secret string
- tokenDuration time.Duration
licenseService enterprise.LicenseService
metricReporter *metricreport.Reporter
profile *config.Profile
@@ -62,11 +61,10 @@ type AuthService struct {
}
// NewAuthService creates a new AuthService.
-func NewAuthService(store *store.Store, secret string, tokenDuration time.Duration, licenseService enterprise.LicenseService, metricReporter *metricreport.Reporter, profile *config.Profile, stateCfg *state.State, iamManager *iam.Manager, postCreateUser func(ctx context.Context, user *store.UserMessage, firstEndUser bool) error) (*AuthService, error) {
+func NewAuthService(store *store.Store, secret string, licenseService enterprise.LicenseService, metricReporter *metricreport.Reporter, profile *config.Profile, stateCfg *state.State, iamManager *iam.Manager, postCreateUser func(ctx context.Context, user *store.UserMessage, firstEndUser bool) error) (*AuthService, error) {
return &AuthService{
store: store,
secret: secret,
- tokenDuration: tokenDuration,
licenseService: licenseService,
metricReporter: metricReporter,
profile: profile,
@@ -744,10 +742,11 @@ func (s *AuthService) Login(ctx context.Context, request *v1pb.LoginRequest) (*v
}
}
+ tokenDuration := auth.GetTokenDuration(ctx, s.store)
userMFAEnabled := loginUser.MFAConfig != nil && loginUser.MFAConfig.OtpSecret != ""
// We only allow MFA login (2-step) when the feature is enabled and user has enabled MFA.
if s.licenseService.IsFeatureEnabled(api.Feature2FA) == nil && !mfaSecondLogin && userMFAEnabled {
- mfaTempToken, err := auth.GenerateMFATempToken(loginUser.Name, loginUser.ID, s.profile.Mode, s.secret, s.tokenDuration)
+ mfaTempToken, err := auth.GenerateMFATempToken(loginUser.Name, loginUser.ID, s.profile.Mode, s.secret, tokenDuration)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to generate MFA temp token")
}
@@ -757,7 +756,7 @@ func (s *AuthService) Login(ctx context.Context, request *v1pb.LoginRequest) (*v
}
if loginUser.Type == api.EndUser {
- token, err := auth.GenerateAccessToken(loginUser.Name, loginUser.ID, s.profile.Mode, s.secret, s.tokenDuration)
+ token, err := auth.GenerateAccessToken(loginUser.Name, loginUser.ID, s.profile.Mode, s.secret, tokenDuration)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to generate API access token")
}
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 4281cd2010..3e5883d57e 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -3,7 +3,6 @@ package server
import (
"context"
"fmt"
- "time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
@@ -43,10 +42,9 @@ func configureGrpcRouters(
relayRunner *relay.Runner,
planCheckScheduler *plancheck.Scheduler,
postCreateUser apiv1.CreateUserFunc,
- secret string,
- tokenDuration time.Duration) (*apiv1.PlanService, *apiv1.RolloutService, *apiv1.IssueService, *apiv1.SQLService, error) {
+ secret string) (*apiv1.PlanService, *apiv1.RolloutService, *apiv1.IssueService, *apiv1.SQLService, error) {
// Register services.
- authService, err := apiv1.NewAuthService(stores, secret, tokenDuration, licenseService, metricReporter, profile, stateCfg, iamManager, postCreateUser)
+ authService, err := apiv1.NewAuthService(stores, secret, licenseService, metricReporter, profile, stateCfg, iamManager, postCreateUser)
if err != nil {
return nil, nil, nil, nil, err
}
diff --git a/backend/server/init.go b/backend/server/init.go
index 35b6b47821..334e172b19 100644
--- a/backend/server/init.go
+++ b/backend/server/init.go
@@ -2,13 +2,11 @@ package server
import (
"context"
- "time"
"github.com/google/uuid"
"github.com/pkg/errors"
"google.golang.org/protobuf/encoding/protojson"
- "github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/metric"
@@ -18,7 +16,7 @@ import (
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
-func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, error) {
+func (s *Server) getInitSetting(ctx context.Context) (string, error) {
// secretLength is the length for the secret used to sign the JWT auto token.
const secretLength = 32
@@ -28,13 +26,13 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Value: "",
Description: "The branding slogo image in base64 string format.",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial JWT token
secret, err := common.RandomString(secretLength)
if err != nil {
- return "", 0, errors.Wrap(err, "failed to generate random JWT secret")
+ return "", errors.Wrap(err, "failed to generate random JWT secret")
}
authSetting, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{
Name: api.SettingAuthSecret,
@@ -42,7 +40,7 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Description: "Random string used to sign the JWT auth token.",
}, api.SystemBotID)
if err != nil {
- return "", 0, err
+ return "", err
}
// Set secret to the stored secret.
secret = authSetting.Value
@@ -53,26 +51,26 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Value: uuid.New().String(),
Description: "The workspace identifier",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// Init SCIM config
scimToken, err := common.RandomString(secretLength)
if err != nil {
- return "", 0, errors.Wrap(err, "failed to generate random SCIM secret")
+ return "", errors.Wrap(err, "failed to generate random SCIM secret")
}
scimSettingValue, err := protojson.Marshal(&storepb.SCIMSetting{
Token: scimToken,
})
if err != nil {
- return "", 0, errors.Wrap(err, "failed to marshal initial scim setting")
+ return "", errors.Wrap(err, "failed to marshal initial scim setting")
}
if _, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{
Name: api.SettingSCIM,
Value: string(scimSettingValue),
Description: "The SCIM sync",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// Init password validation
@@ -85,14 +83,14 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
RequireResetPasswordForFirstLogin: false,
})
if err != nil {
- return "", 0, errors.Wrap(err, "failed to marshal initial password validation setting")
+ return "", errors.Wrap(err, "failed to marshal initial password validation setting")
}
if _, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{
Name: api.SettingPasswordRestriction,
Value: string(passwordSettingValue),
Description: "The password validation",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial license
@@ -101,7 +99,7 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Value: "",
Description: "Enterprise license",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial IM app
@@ -110,7 +108,7 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Value: "{}",
Description: "",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial watermark setting
@@ -119,7 +117,7 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Value: "0",
Description: "Display watermark",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial OpenAI key setting
@@ -128,7 +126,7 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Value: "",
Description: "API key to request OpenAI (ChatGPT)",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
if _, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{
@@ -136,52 +134,52 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Value: "",
Description: "API Endpoint for OpenAI",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial external approval setting
externalApprovalSettingValue, err := protojson.Marshal(&storepb.ExternalApprovalSetting{})
if err != nil {
- return "", 0, errors.Wrap(err, "failed to marshal initial external approval setting")
+ return "", errors.Wrap(err, "failed to marshal initial external approval setting")
}
if _, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{
Name: api.SettingWorkspaceExternalApproval,
Value: string(externalApprovalSettingValue),
Description: "The external approval setting",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial schema template setting
schemaTemplateSettingValue, err := protojson.Marshal(&storepb.SchemaTemplateSetting{})
if err != nil {
- return "", 0, errors.Wrap(err, "failed to marshal initial schema template setting")
+ return "", errors.Wrap(err, "failed to marshal initial schema template setting")
}
if _, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{
Name: api.SettingSchemaTemplate,
Value: string(schemaTemplateSettingValue),
Description: "The schema template setting",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial data classification setting
dataClassificationSettingValue, err := protojson.Marshal(&storepb.DataClassificationSetting{})
if err != nil {
- return "", 0, errors.Wrap(err, "failed to marshal initial data classification setting")
+ return "", errors.Wrap(err, "failed to marshal initial data classification setting")
}
if _, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{
Name: api.SettingDataClassification,
Value: string(dataClassificationSettingValue),
Description: "The data classification setting",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial workspace approval setting
approvalSettingValue, err := protojson.Marshal(&storepb.WorkspaceApprovalSetting{})
if err != nil {
- return "", 0, errors.Wrap(err, "failed to marshal initial workspace approval setting")
+ return "", errors.Wrap(err, "failed to marshal initial workspace approval setting")
}
if _, _, err := s.store.CreateSettingIfNotExistV2(ctx, &store.SettingMessage{
Name: api.SettingWorkspaceApproval,
@@ -189,13 +187,13 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
Value: string(approvalSettingValue),
Description: "The workspace approval setting",
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// initial workspace profile setting
workspaceProfileSetting, err := s.store.GetSettingV2(ctx, api.SettingWorkspaceProfile)
if err != nil {
- return "", 0, err
+ return "", err
}
workspaceProfilePayload := &storepb.WorkspaceProfileSetting{
@@ -204,7 +202,7 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
if workspaceProfileSetting != nil {
workspaceProfilePayload = new(storepb.WorkspaceProfileSetting)
if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(workspaceProfileSetting.Value), workspaceProfilePayload); err != nil {
- return "", 0, err
+ return "", err
}
if s.profile.ExternalURL != "" {
workspaceProfilePayload.ExternalUrl = s.profile.ExternalURL
@@ -213,14 +211,14 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
bytes, err := protojson.Marshal(workspaceProfilePayload)
if err != nil {
- return "", 0, err
+ return "", err
}
if _, err := s.store.UpsertSettingV2(ctx, &store.SetSettingMessage{
Name: api.SettingWorkspaceProfile,
Value: string(bytes),
}, api.SystemBotID); err != nil {
- return "", 0, err
+ return "", err
}
// Init workspace IAM policy
@@ -231,7 +229,7 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
},
UpdaterUID: api.SystemBotID,
}); err != nil {
- return "", 0, err
+ return "", err
}
if _, err := s.store.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{
Member: api.AllUsers,
@@ -240,36 +238,10 @@ func (s *Server) getInitSetting(ctx context.Context) (string, time.Duration, err
},
UpdaterUID: api.SystemBotID,
}); err != nil {
- return "", 0, err
+ return "", err
}
- // Get token duration.
- workspaceProfile, err := s.store.GetWorkspaceGeneralSetting(ctx)
- if err != nil {
- return "", 0, err
- }
- passwordRestriction, err := s.store.GetPasswordRestrictionSetting(ctx)
- if err != nil {
- return "", 0, err
- }
-
- tokenDuration := auth.DefaultTokenDuration
- if workspaceProfile.TokenDuration != nil && workspaceProfile.TokenDuration.GetSeconds() > 0 {
- tokenDuration = workspaceProfile.TokenDuration.AsDuration()
- }
- // Currently we implement the password rotation restriction in a simple way:
- // 1. Only check if users need to reset their password during login.
- // 2. For the 1st time login, if `RequireResetPasswordForFirstLogin` is true, `require_reset_password` in the response will be true
- // 3. Otherwise if the `PasswordRotation` exists, check the password last updated time to decide if the `require_reset_password` is true.
- // So we will use the minimum value between (`workspaceProfile.TokenDuration`, `passwordRestriction.PasswordRotation`) to force to expire the token.
- if passwordRestriction.PasswordRotation != nil && passwordRestriction.PasswordRotation.GetSeconds() > 0 {
- passwordRotation := passwordRestriction.PasswordRotation.AsDuration()
- if passwordRotation.Seconds() < tokenDuration.Seconds() {
- tokenDuration = passwordRotation
- }
- }
-
- return secret, tokenDuration, nil
+ return secret, nil
}
// initMetricReporter will initial the metric scheduler.
diff --git a/backend/server/server.go b/backend/server/server.go
index 3d2f9aafff..6754f2ecd8 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -227,7 +227,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
// Cache the license.
s.licenseService.LoadSubscription(ctx)
- secret, tokenDuration, err := s.getInitSetting(ctx)
+ secret, err := s.getInitSetting(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to init config")
}
@@ -254,7 +254,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
// Note: the gateway response modifier takes the token duration on server startup. If the value is changed,
// the user has to restart the server to take the latest value.
- gatewayModifier := auth.GatewayResponseModifier{TokenDuration: tokenDuration}
+ gatewayModifier := auth.GatewayResponseModifier{Store: s.store}
mux := grpcruntime.NewServeMux(grpcruntime.WithForwardResponseOption(gatewayModifier.Modify))
s.metricReporter = metricreport.NewReporter(s.store, s.licenseService, s.profile, false)
@@ -291,7 +291,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
}
// Setup the gRPC and grpc-gateway.
- authProvider := auth.New(s.store, s.secret, tokenDuration, s.licenseService, s.stateCfg, s.profile)
+ authProvider := auth.New(s.store, s.secret, s.licenseService, s.stateCfg, s.profile)
auditProvider := apiv1.NewAuditInterceptor(s.store)
aclProvider := apiv1.NewACLInterceptor(s.store, s.secret, s.iamManager, s.profile)
debugProvider := apiv1.NewDebugInterceptor(s.metricReporter)
@@ -346,7 +346,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
}
return nil
}
- planService, rolloutService, issueService, sqlService, err := configureGrpcRouters(ctx, mux, s.grpcServer, s.store, s.sheetManager, s.dbFactory, s.licenseService, s.profile, s.metricReporter, s.stateCfg, s.schemaSyncer, s.webhookManager, s.iamManager, s.relayRunner, s.planCheckScheduler, postCreateUser, s.secret, tokenDuration)
+ planService, rolloutService, issueService, sqlService, err := configureGrpcRouters(ctx, mux, s.grpcServer, s.store, s.sheetManager, s.dbFactory, s.licenseService, s.profile, s.metricReporter, s.stateCfg, s.schemaSyncer, s.webhookManager, s.iamManager, s.relayRunner, s.planCheckScheduler, postCreateUser, s.secret)
if err != nil {
return nil, err
}
diff --git a/frontend/src/AuthContext.vue b/frontend/src/AuthContext.vue
index bf9443038a..29de320aab 100644
--- a/frontend/src/AuthContext.vue
+++ b/frontend/src/AuthContext.vue
@@ -7,7 +7,6 @@ import { useDialog, type DialogReactive } from "naive-ui";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { t } from "./plugins/i18n";
-import { AUTH_SIGNIN_MODULE } from "./router/auth";
import { WORKSPACE_ROOT_MODULE } from "./router/dashboard/workspaceRoutes";
import { useActuatorV1Store, useAuthStore } from "./store";
@@ -35,9 +34,7 @@ onMounted(() => {
if (prevLoggedIn.value != loggedIn) {
prevLoggedIn.value = loggedIn;
if (!loggedIn) {
- authStore.logout().then(() => {
- router.push({ name: AUTH_SIGNIN_MODULE });
- });
+ authStore.logout();
}
}
if (
diff --git a/frontend/src/components/ProfileDropdown.vue b/frontend/src/components/ProfileDropdown.vue
index d9d74a593c..08c91b6548 100644
--- a/frontend/src/components/ProfileDropdown.vue
+++ b/frontend/src/components/ProfileDropdown.vue
@@ -19,9 +19,7 @@ import { NSwitch, NDropdown } from "naive-ui";
import { storeToRefs } from "pinia";
import { computed, ref, h } from "vue";
import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
import { useLanguage } from "@/composables/useLanguage";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
import {
useActuatorV1Store,
useAppFeature,
@@ -51,7 +49,6 @@ const actuatorStore = useActuatorV1Store();
const authStore = useAuthStore();
const subscriptionStore = useSubscriptionV1Store();
const uiStateStore = useUIStateStore();
-const router = useRouter();
const { setLocale, locale } = useLanguage();
const currentUserV1 = useCurrentUserV1();
const showDropdown = ref(false);
@@ -74,9 +71,7 @@ const allowToggleDebug = computed(() => {
const { currentPlan } = storeToRefs(subscriptionStore);
const logout = () => {
- authStore.logout().then(() => {
- router.push({ name: AUTH_SIGNIN_MODULE });
- });
+ authStore.logout();
};
const resetQuickstart = () => {
diff --git a/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts b/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts
index b1fdbe82a0..f8228b5585 100644
--- a/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts
+++ b/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts
@@ -1,7 +1,6 @@
import { ClientError, ServerError, Status } from "nice-grpc-common";
import type { ClientMiddleware } from "nice-grpc-web";
import { router } from "@/router";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
import { useAuthStore } from "@/store";
export type IgnoreErrorsOptions = {
@@ -38,13 +37,7 @@ export const authInterceptorMiddleware: ClientMiddleware<IgnoreErrorsOptions> =
} else {
if (code === Status.UNAUTHENTICATED) {
// "Kick out" sign in status if access token expires.
- try {
- await useAuthStore().logout();
- } finally {
- router.push({ name: AUTH_SIGNIN_MODULE }).then(() => {
- window.location.reload();
- });
- }
+ await useAuthStore().logout();
} else if (code === Status.PERMISSION_DENIED) {
// Jump to 403 page
router.push({ name: "error.403" });
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 56d79d4642..b65aa8098b 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -15,7 +15,6 @@ import i18n from "./plugins/i18n";
import NaiveUI from "./plugins/naive-ui";
import { isSilent } from "./plugins/silent-request";
import { router } from "./router";
-import { AUTH_SIGNIN_MODULE } from "./router/auth";
import { pinia, pushNotification, useAuthStore } from "./store";
import {
humanizeTs,
@@ -77,11 +76,7 @@ axios.interceptors.response.use(
// we know this is a request to Bytebase API endpoint (not an external service).
// Means that the auth session is error or expired.
// So we need to "kick out" here.
- try {
- await useAuthStore().logout();
- } finally {
- router.push({ name: AUTH_SIGNIN_MODULE });
- }
+ await useAuthStore().logout();
}
}
diff --git a/frontend/src/store/modules/auth.ts b/frontend/src/store/modules/auth.ts
index f615884aae..7cc15fd653 100644
--- a/frontend/src/store/modules/auth.ts
+++ b/frontend/src/store/modules/auth.ts
@@ -4,6 +4,8 @@ import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { restartAppRoot } from "@/AppRootContext";
import { authServiceClient } from "@/grpcweb";
+import { router } from "@/router";
+import { AUTH_SIGNIN_MODULE } from "@/router/auth";
import { unknownUser } from "@/types";
import type { LoginRequest, User } from "@/types/proto/v1/auth_service";
import { LoginResponse } from "@/types/proto/v1/auth_service";
@@ -88,6 +90,21 @@ export const useAuthStore = defineStore("auth_v1", () => {
} finally {
currentUserId.value = undefined;
restartAppRoot();
+
+ const query = new URLSearchParams(window.location.search);
+ const redirect = query.get("redirect");
+ const pathname = location.pathname;
+ router
+ .push({
+ name: AUTH_SIGNIN_MODULE,
+ query: {
+ redirect:
+ redirect || (pathname.startsWith("/auth") ? undefined : pathname),
+ },
+ })
+ .then(() => {
+ window.location.reload();
+ });
}
};
diff --git a/frontend/src/views/Setup/ProvideSetupContext.vue b/frontend/src/views/Setup/ProvideSetupContext.vue
index 997d248283..7d5a6541ce 100644
--- a/frontend/src/views/Setup/ProvideSetupContext.vue
+++ b/frontend/src/views/Setup/ProvideSetupContext.vue
@@ -10,8 +10,12 @@ import {
type RouteLocationNormalizedLoadedGeneric,
} from "vue-router";
import MaskSpinner from "@/components/misc/MaskSpinner.vue";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
-import { usePolicyV1Store, useRoleStore, useSettingV1Store } from "@/store";
+import {
+ usePolicyV1Store,
+ useRoleStore,
+ useSettingV1Store,
+ useAuthStore,
+} from "@/store";
import { PolicyResourceType } from "@/types/proto/v1/org_policy_service";
import { hasWorkspacePermissionV2 } from "@/utils";
@@ -46,10 +50,7 @@ onMounted(async () => {
(route) => {
if (!checkPermissions(route)) {
ready.value = false;
- router.replace({
- name: AUTH_SIGNIN_MODULE,
- });
- return;
+ return useAuthStore().logout();
}
ready.value = true;
},
diff --git a/frontend/src/views/TwoFactorRequired.vue b/frontend/src/views/TwoFactorRequired.vue
index 1f9e1a8dc8..f3a12903e0 100644
--- a/frontend/src/views/TwoFactorRequired.vue
+++ b/frontend/src/views/TwoFactorRequired.vue
@@ -10,18 +10,13 @@
</template>
<script lang="ts" setup>
-import { useRouter } from "vue-router";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
+import { BBAttention } from "@/bbkit";
import { useAuthStore } from "@/store";
import TwoFactorSetup from "./TwoFactorSetup.vue";
-import { BBAttention } from "@/bbkit";
-const router = useRouter();
const authStore = useAuthStore();
const handleSetupCancel = () => {
- authStore.logout().then(() => {
- router.push({ name: AUTH_SIGNIN_MODULE });
- });
+ authStore.logout();
};
</script>
diff --git a/frontend/src/views/auth/PasswordForgot.vue b/frontend/src/views/auth/PasswordForgot.vue
index 155d886410..a972f94487 100644
--- a/frontend/src/views/auth/PasswordForgot.vue
+++ b/frontend/src/views/auth/PasswordForgot.vue
@@ -37,7 +37,7 @@
</div>
<div class="relative flex justify-center text-sm">
<router-link
- :to="{ name: AUTH_SIGNIN_MODULE }"
+ :to="{ name: AUTH_SIGNIN_MODULE, query: $route.query }"
class="accent-link bg-white px-2"
>
{{ $t("auth.password-forget.return-to-sign-in") }}
diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vue
index 4de66e1d3e..a46d5b1899 100644
--- a/frontend/src/views/auth/Signin.vue
+++ b/frontend/src/views/auth/Signin.vue
@@ -42,7 +42,7 @@
{{ $t("auth.sign-in.new-user") }}
</span>
<router-link
- :to="{ name: AUTH_SIGNUP_MODULE }"
+ :to="{ name: AUTH_SIGNUP_MODULE, query: $route.query }"
class="accent-link px-2"
>
{{ $t("common.sign-up") }}
diff --git a/frontend/src/views/auth/Signup.vue b/frontend/src/views/auth/Signup.vue
index b414f0823f..f94ad9369c 100644
--- a/frontend/src/views/auth/Signup.vue
+++ b/frontend/src/views/auth/Signup.vue
@@ -131,7 +131,7 @@
{{ $t("auth.sign-up.existing-user") }}
</span>
<router-link
- :to="{ name: AUTH_SIGNIN_MODULE }"
+ :to="{ name: AUTH_SIGNIN_MODULE, query: $route.query }"
class="accent-link px-2 bg-white"
>
{{ $t("common.sign-in") }}