From 0cdb922d84abeb5e535bdcb0d7c26a0b233ce00d Mon Sep 17 00:00:00 2001 From: wizardchen Date: Mon, 18 May 2026 19:48:59 +0800 Subject: [PATCH] feat(tenant): remember user's last-active workspace across logins Until now a fresh login (new device, expired refresh token, cleared browser) always dropped the user into their home tenant, even if they spend most of their time in a peer workspace. The session-local X-Tenant-ID override in localStorage gave a "same browser sticky" effect, but never crossed devices or new sessions. This adds a small server-side preference, `users.preferences. last_active_tenant_id`, persisted in the existing jsonb column (no new migration), and threads it through: * Backend * `UserPreferences` gains `LastActiveTenantID *uint64` with sentinel semantics (`*0` from the PATCH endpoint = clear preference). * `resolveLoginTenantID` validates the stored id (tenant still exists + active membership, or CanAccessAllTenants) and falls back to home on any failure, best-effort clearing the stale preference so subsequent logins don't pay for it again. * `Login` and `LoginWithOIDC` resolve once and use the result for both the JWT `tenant_id` claim and the returned `active_tenant`, keeping the two in sync. `RefreshToken` rides through `GenerateTokens` so refresh rotations also land the user back in their preferred tenant instead of bouncing to home. * `UpdateUserPreferences` learns to merge the new key. * `PUT /auth/me/preferences` accepts the new field. * Frontend * `Login.vue` now writes the user's HOME tenant id into `user.tenant_id` (matching the field's documented semantics) and expresses any active-vs-home divergence via `setSelectedTenant`, so `useHomeTenant` and the "current"/"home" badges stay correct after the backend honours a remembered preference. `App.vue`'s OIDC sync does the same reconciliation. * `TenantSelector`, `UserMenu` and the post-tenant-create handlers fire `persistLastActiveTenantPreference` after every successful user-initiated switch (switching to home sends `0` to clear). The call is raced against the existing reload-grace window so most writes finish before the page tears down; lost writes are recoverable on the next switch. No new UI. Users will simply notice that, after re-logging in on another device, they land back in the workspace they were last using rather than always in their home tenant. Note: `make docs` is unrelated-broken on `main` (audit_log.go references `errors.AppError` which swag can't resolve), so the Swagger artifacts under docs/ are intentionally not regenerated in this PR. The handler code is the source of truth. --- frontend/src/App.vue | 11 ++ frontend/src/api/auth/index.ts | 4 + frontend/src/components/TenantSelector.vue | 28 +++-- frontend/src/components/UserMenu.vue | 32 +++--- frontend/src/utils/tenantSwitch.ts | 35 ++++++ frontend/src/views/auth/Login.vue | 20 +++- internal/application/service/user.go | 119 +++++++++++++++++++-- internal/handler/auth.go | 9 +- internal/types/user.go | 16 +++ 9 files changed, 239 insertions(+), 35 deletions(-) diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 32431221..3d7f4910 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -81,6 +81,17 @@ const syncOIDCUserContext = async () => { if (Array.isArray(memberships)) { authStore.setMemberships(memberships) } + // Same active-vs-home reconciliation as Login.vue: if the OIDC login + // landed us in a non-home tenant (because the backend honoured a + // remembered last-active-tenant preference) make sure X-Tenant-ID + // override is set; otherwise drop any stale override. + const activeIdNum = tenant?.id != null ? Number(tenant.id) : NaN + const homeIdNum = user.tenant_id != null ? Number(user.tenant_id) : NaN + if (Number.isFinite(activeIdNum) && Number.isFinite(homeIdNum) && activeIdNum !== homeIdNum) { + authStore.setSelectedTenant(activeIdNum, tenant?.name || null) + } else { + authStore.setSelectedTenant(null, null) + } } const persistOIDCLoginResponse = async (response: any) => { diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.ts index 9456bd01..12b812a4 100644 --- a/frontend/src/api/auth/index.ts +++ b/frontend/src/api/auth/index.ts @@ -82,6 +82,10 @@ export interface RegisterResponse { // 处理;前端调用方按需读 / 默认值降级。 export interface UserPreferences { enable_memory?: boolean + // last_active_tenant_id 持久化「刷新 / 换设备 / 重新登录后回到上次的空间」 + // 偏好;后端在 Login / RefreshToken 时校验 membership 有效后才会沿用, + // 否则回退到 home 并清掉这个字段。传 0 给 PATCH 表示「清除偏好」。 + last_active_tenant_id?: number | null } // 用户信息接口 diff --git a/frontend/src/components/TenantSelector.vue b/frontend/src/components/TenantSelector.vue index 1d248a9c..89103e99 100644 --- a/frontend/src/components/TenantSelector.vue +++ b/frontend/src/components/TenantSelector.vue @@ -76,7 +76,11 @@ import { useAuthStore } from '@/stores/auth' import { searchTenants, type TenantInfo } from '@/api/tenant' import { useI18n } from 'vue-i18n' import { MessagePlugin } from 'tdesign-vue-next' -import { navigateAfterTenantSwitch, stashTenantSwitchToast } from '@/utils/tenantSwitch' +import { + navigateAfterTenantSwitch, + persistLastActiveTenantPreference, + stashTenantSwitchToast, +} from '@/utils/tenantSwitch' import CreateTenantDialog from '@/components/CreateTenantDialog.vue' import { useRoleLabel } from '@/composables/useRoleLabel' @@ -160,7 +164,8 @@ const selectTenant = (tenantId: number) => { // 找到选中的租户信息 const selectedTenant = tenants.value.find(t => t.id === tenantId) - if (tenantId === defaultTenantId.value) { + const switchingToHome = tenantId === defaultTenantId.value + if (switchingToHome) { authStore.setSelectedTenant(null, null) } else { authStore.setSelectedTenant(tenantId, selectedTenant?.name || null) @@ -176,10 +181,13 @@ const selectTenant = (tenantId: number) => { const roleLabel = membership ? formatRole(membership.role) : '' // Toast 在 reload 后由 App.vue 弹出(直接在这里弹会被 hard reload 干掉)。 stashTenantSwitchToast({ name: displayName, role: roleLabel || undefined }) - // 切换租户后跳转到新租户下安全的入口(详见 tenantSwitch.ts 注释)。 - setTimeout(() => { - navigateAfterTenantSwitch() - }, 500) + // Persist "last active tenant" preference (switching to home clears + // it). Fire-and-forget, but race it against the existing 500ms grace + // window so most writes finish before the hard reload tears the page + // down. 切换租户后跳转到新租户下安全的入口(详见 tenantSwitch.ts 注释)。 + const persist = persistLastActiveTenantPreference(switchingToHome ? null : tenantId) + Promise.race([persist, new Promise((r) => setTimeout(r, 500))]) + .finally(() => navigateAfterTenantSwitch()) } const loadTenants = async (append = false) => { @@ -265,9 +273,11 @@ const onTenantCreated = async (newTenant: TenantInfo) => { authStore.setAllTenants(tenants.value) await authStore.refreshFromAuthMe() authStore.setSelectedTenant(newTenant.id, newTenant.name) - setTimeout(() => { - navigateAfterTenantSwitch() - }, 300) + // Newly-created tenant becomes the user's "last active" so re-login + // lands here. Race against the existing grace window before reload. + const persist = persistLastActiveTenantPreference(newTenant.id) + Promise.race([persist, new Promise((r) => setTimeout(r, 300))]) + .finally(() => navigateAfterTenantSwitch()) } onMounted(() => { diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue index 47d7cef0..7a01f648 100644 --- a/frontend/src/components/UserMenu.vue +++ b/frontend/src/components/UserMenu.vue @@ -236,7 +236,11 @@ import { useI18n } from 'vue-i18n' import IMChannelsOverviewPanel from '@/components/IMChannelsOverviewPanel.vue' import CreateTenantDialog from '@/components/CreateTenantDialog.vue' import { listAllIMChannels, type IMChannelOverview } from '@/api/agent' -import { navigateAfterTenantSwitch, stashTenantSwitchToast } from '@/utils/tenantSwitch' +import { + navigateAfterTenantSwitch, + persistLastActiveTenantPreference, + stashTenantSwitchToast, +} from '@/utils/tenantSwitch' import type { TenantInfo } from '@/api/tenant' import { useRoleLabel, useHomeTenant } from '@/composables/useRoleLabel' @@ -381,9 +385,9 @@ const openCreateTenantDialog = () => { const onTenantCreated = async (newTenant: TenantInfo) => { await authStore.refreshFromAuthMe() authStore.setSelectedTenant(newTenant.id, newTenant.name) - setTimeout(() => { - navigateAfterTenantSwitch() - }, 300) + const persist = persistLastActiveTenantPreference(newTenant.id) + Promise.race([persist, new Promise((r) => setTimeout(r, 300))]) + .finally(() => navigateAfterTenantSwitch()) } // ---------- Tenant switcher submenu ---------- @@ -440,7 +444,8 @@ const switchToTenant = (m: Membership) => { // override" so request.ts stops attaching X-Tenant-ID. This mirrors // what TenantSelector.vue does in selectTenant(). const home = homeTenantId.value - if (home !== null && home === m.tenant_id) { + const switchingToHome = home !== null && home === m.tenant_id + if (switchingToHome) { authStore.setSelectedTenant(null, null) } else { authStore.setSelectedTenant(m.tenant_id, tenantDisplayName(m)) @@ -451,14 +456,15 @@ const switchToTenant = (m: Membership) => { name: tenantDisplayName(m), role: formatRole(m.role) || undefined, }) - // Hard reload so every cached store / open SSE stream / in-flight - // request gets re-keyed under the new tenant. If the current path - // embeds a tenant-scoped resource id, reload would white-screen the - // user; navigateAfterTenantSwitch redirects to the platform home in - // that case. Same helper as TenantSelector.vue. - setTimeout(() => { - navigateAfterTenantSwitch() - }, 400) + // Persist "last active tenant" preference (switching to home clears + // it). Hard reload so every cached store / open SSE stream / in-flight + // request gets re-keyed under the new tenant; navigateAfterTenantSwitch + // redirects to the platform home so tenant-scoped resource paths don't + // white-screen. Race the persist against the existing 400ms grace + // window so most writes complete before the page tears down. + const persist = persistLastActiveTenantPreference(switchingToHome ? null : m.tenant_id) + Promise.race([persist, new Promise((r) => setTimeout(r, 400))]) + .finally(() => navigateAfterTenantSwitch()) } let lastTenantSubmenuMembershipRefresh = 0 diff --git a/frontend/src/utils/tenantSwitch.ts b/frontend/src/utils/tenantSwitch.ts index 099261d6..e4f8ebdb 100644 --- a/frontend/src/utils/tenantSwitch.ts +++ b/frontend/src/utils/tenantSwitch.ts @@ -6,6 +6,8 @@ // 对应数据出现空状态,体验跟跳到固定首页其实差不多——干脆统一跳到 KB 列表, // 用一次 full navigation 把所有 store / SSE / 请求都重置一遍。 +import { updateMyPreferences } from '@/api/auth' + const SAFE_FALLBACK_PATH = '/platform/knowledge-bases' /** @@ -55,3 +57,36 @@ export function consumePendingTenantSwitchToast(): PendingTenantSwitchToast | nu return null } } + +/** + * Persist the user's "last active tenant" preference server-side so a + * fresh login (new device, new refresh token, cleared browser) drops + * them back into this workspace instead of always bouncing to their + * home tenant. + * + * Conventions: + * - Pass the target tenant id when switching to a peer tenant. + * - Pass `null` (which sends `0`) when switching back to the home + * tenant — that clears the preference and reverts the user to the + * "always start at home" default. + * + * Fire-and-forget: callers usually trigger a full-page reload right + * after; this returns the in-flight promise so callers can race it + * against a small budget if they want best-effort completion before + * navigation. Failures are logged but never thrown — losing one + * persist is recoverable on the next switch. + */ +export function persistLastActiveTenantPreference( + tenantId: number | null, +): Promise { + const payload = { last_active_tenant_id: tenantId == null ? 0 : tenantId } + return updateMyPreferences(payload) + .then((res) => { + if (!res.success) { + console.warn('persistLastActiveTenantPreference: server rejected update', res.message) + } + }) + .catch((err) => { + console.warn('persistLastActiveTenantPreference: network/serialization error', err) + }) +} diff --git a/frontend/src/views/auth/Login.vue b/frontend/src/views/auth/Login.vue index 3709565a..d1455991 100755 --- a/frontend/src/views/auth/Login.vue +++ b/frontend/src/views/auth/Login.vue @@ -553,12 +553,18 @@ const persistLoginResponse = async (response: any) => { // JWT, defaulting to the user's home tenant on a fresh login. const activeTenant = response.active_tenant || response.tenant if (response.user && activeTenant && response.token) { + // user.tenant_id must be the user's HOME tenant (the immutable row + // on the users table); useHomeTenant() and the home-badge logic both + // assume so. The ACTIVE tenant (which can differ from home when the + // server honoured a remembered last-active-tenant preference) is + // expressed separately via setSelectedTenant below. + const homeTenantIdRaw = response.user.tenant_id ?? activeTenant.id authStore.setUser({ id: response.user.id || '', username: response.user.username || '', email: response.user.email || '', avatar: response.user.avatar, - tenant_id: String(activeTenant.id) || '', + tenant_id: String(homeTenantIdRaw) || '', can_access_all_tenants: response.user.can_access_all_tenants || false, preferences: response.user.preferences, created_at: response.user.created_at || new Date().toISOString(), @@ -579,6 +585,18 @@ const persistLoginResponse = async (response: any) => { if (Array.isArray(response.memberships)) { authStore.setMemberships(response.memberships) } + // If the backend dropped us into a non-home tenant (honoured a + // remembered "last active tenant" preference), set the override so + // subsequent requests carry X-Tenant-ID and the UI stays consistent. + // Otherwise clear any stale override left in localStorage by a + // previous session for a different account. + const activeIdNum = Number(activeTenant.id) + const homeIdNum = Number(homeTenantIdRaw) + if (Number.isFinite(activeIdNum) && Number.isFinite(homeIdNum) && activeIdNum !== homeIdNum) { + authStore.setSelectedTenant(activeIdNum, activeTenant.name || null) + } else { + authStore.setSelectedTenant(null, null) + } } await nextTick() diff --git a/internal/application/service/user.go b/internal/application/service/user.go index 2476f7fc..f194c1b3 100644 --- a/internal/application/service/user.go +++ b/internal/application/service/user.go @@ -195,9 +195,13 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type } logger.Info(ctx, "Password verification successful") - // Generate tokens + // Generate tokens. Resolve the target tenant once so the JWT claim + // and the tenant we return below agree — otherwise an honoured + // "last active tenant" preference would mint a token for tenant N + // but tell the client they're in their home tenant. logger.Info(ctx, "Generating tokens") - accessToken, refreshToken, err := s.GenerateTokens(ctx, user) + resolvedTenantID := s.resolveLoginTenantID(ctx, user) + accessToken, refreshToken, err := s.generateTokensForTenant(ctx, user, resolvedTenantID) if err != nil { logger.Errorf(ctx, "Failed to generate tokens: %v", err) return &types.LoginResponse{ @@ -208,7 +212,7 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type logger.Info(ctx, "Tokens generated successfully") // Get tenant information - tenant, err := s.tenantService.GetTenantByID(ctx, user.TenantID) + tenant, err := s.tenantService.GetTenantByID(ctx, resolvedTenantID) if err != nil { logger.Warn(ctx, "Failed to get tenant info") } else { @@ -432,7 +436,10 @@ func (s *userService) LoginWithOIDC(ctx context.Context, code, redirectURI strin return &types.OIDCCallbackResponse{Success: false, Message: "Account is disabled"}, nil } - accessToken, refreshToken, err := s.GenerateTokens(ctx, user) + // Resolve target tenant once so the JWT claim and the tenant we + // return below stay in sync; see Login for the rationale. + resolvedTenantID := s.resolveLoginTenantID(ctx, user) + accessToken, refreshToken, err := s.generateTokensForTenant(ctx, user, resolvedTenantID) if err != nil { return nil, fmt.Errorf("failed to generate local tokens: %w", err) } @@ -440,12 +447,12 @@ func (s *userService) LoginWithOIDC(ctx context.Context, code, redirectURI strin // 拉取 tenant + memberships,让 OIDC 登录的返回结构与本地登录一致, // 前端无须为 OIDC 单独走一次 /auth/me 才能拿到角色。 var tenant *types.Tenant - if user.TenantID > 0 { - if t, terr := s.tenantService.GetTenantByID(ctx, user.TenantID); terr == nil { + if resolvedTenantID > 0 { + if t, terr := s.tenantService.GetTenantByID(ctx, resolvedTenantID); terr == nil { tenant = t } else { logger.Warnf(ctx, "OIDC login: failed to load tenant %d for user %s: %v", - user.TenantID, user.ID, terr) + resolvedTenantID, user.ID, terr) } } memberships := s.buildMembershipsForUser(ctx, user, tenant) @@ -516,6 +523,18 @@ func (s *userService) UpdateUserPreferences( v := *patch.EnableMemory merged.EnableMemory = &v } + if patch.LastActiveTenantID != nil { + // *0 = "forget my preference, fall back to home on next login"; + // any positive value = set/replace. We do not validate membership + // here — invalid values get culled on the next login via + // resolveLoginTenantID, keeping this endpoint cheap. + if *patch.LastActiveTenantID == 0 { + merged.LastActiveTenantID = nil + } else { + v := *patch.LastActiveTenantID + merged.LastActiveTenantID = &v + } + } user.Preferences = merged user.UpdatedAt = time.Now() @@ -566,14 +585,92 @@ func (s *userService) ValidatePassword(ctx context.Context, userID string, passw } // GenerateTokens generates access and refresh tokens for user. The -// access token's tenant_id claim is set to user.TenantID — i.e. login -// always lands in the user's home tenant. SwitchTenant is the tool for -// pointing tokens at a different membership. +// access token's tenant_id claim defaults to user.TenantID (home), but +// if the user has persisted a still-valid "last active tenant" +// preference we honour it instead — so login (and the refresh-token +// rotation path that also calls into here) lands the user back where +// they left off across devices. SwitchTenant remains the explicit tool +// for switching to an arbitrary membership. func (s *userService) GenerateTokens( ctx context.Context, user *types.User, ) (accessToken, refreshToken string, err error) { - return s.generateTokensForTenant(ctx, user, user.TenantID) + return s.generateTokensForTenant(ctx, user, s.resolveLoginTenantID(ctx, user)) +} + +// resolveLoginTenantID picks the tenant whose ID should be encoded in a +// freshly minted access token. The contract: +// +// 1. If the user has no LastActiveTenantID preference set (or it points +// at home), return home — the historical behaviour. +// 2. Otherwise validate the preference: the tenant must still exist and +// the user must still have an active membership (or be a cross-tenant +// superuser). Validation failure logs a warning, best-effort clears +// the stale preference (so we don't waste a DB round-trip on every +// subsequent login), and falls back to home. +// +// This is intentionally a private method on userService so it can reach +// memberService / tenantService / userRepo. Errors from the validation +// path never fail login; the worst case is the user lands in home. +func (s *userService) resolveLoginTenantID(ctx context.Context, user *types.User) uint64 { + if user == nil { + return 0 + } + pref := user.Preferences.LastActiveTenantID + if pref == nil || *pref == 0 || *pref == user.TenantID { + return user.TenantID + } + preferred := *pref + + // Tenant must still exist. + if s.tenantService != nil { + if _, err := s.tenantService.GetTenantByID(ctx, preferred); err != nil { + logger.Warnf(ctx, + "resolveLoginTenantID: preferred tenant %d not loadable for user %s, "+ + "clearing preference and falling back to home: %v", + preferred, user.ID, err) + s.clearLastActiveTenantPreference(ctx, user) + return user.TenantID + } + } + + // Membership (or cross-tenant superuser) must still be valid. Mirrors + // the gate in SwitchTenant so the two entry points stay consistent. + if !user.CanAccessAllTenants { + if s.memberService == nil { + logger.Warnf(ctx, + "resolveLoginTenantID: member service unavailable; falling back to home for user %s", + user.ID) + return user.TenantID + } + member, err := s.memberService.GetMembership(ctx, user.ID, preferred) + if err != nil || member == nil || member.Status != types.TenantMemberStatusActive { + logger.Warnf(ctx, + "resolveLoginTenantID: user %s no longer has active membership in tenant %d, "+ + "clearing preference and falling back to home (err=%v)", + user.ID, preferred, err) + s.clearLastActiveTenantPreference(ctx, user) + return user.TenantID + } + } + + return preferred +} + +// clearLastActiveTenantPreference is the best-effort cleanup half of +// resolveLoginTenantID. Failures here are logged but never propagated: +// the in-memory user already has the preference cleared for this login, +// and the next login will re-attempt the cleanup. +func (s *userService) clearLastActiveTenantPreference(ctx context.Context, user *types.User) { + if user == nil { + return + } + user.Preferences.LastActiveTenantID = nil + if err := s.userRepo.UpdateUser(ctx, user); err != nil { + logger.Warnf(ctx, + "clearLastActiveTenantPreference: failed to persist cleared preference for user %s: %v", + user.ID, err) + } } // generateTokensForTenant is the shared implementation behind diff --git a/internal/handler/auth.go b/internal/handler/auth.go index 94d0c6a7..c586b94d 100644 --- a/internal/handler/auth.go +++ b/internal/handler/auth.go @@ -496,6 +496,12 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) { // types.UserPreferences for the persistence-layer counterpart. type updateMyPreferencesRequest struct { EnableMemory *bool `json:"enable_memory"` + // LastActiveTenantID lets the SPA persist "after a fresh login, + // drop me back into this workspace" across devices. Send a positive + // tenant id to set / replace, or 0 to clear. Membership is validated + // at next login, not here. Nil = field omitted from the PATCH and + // stays untouched. + LastActiveTenantID *uint64 `json:"last_active_tenant_id"` } // UpdateMyPreferences godoc @@ -529,7 +535,8 @@ func (h *AuthHandler) UpdateMyPreferences(c *gin.Context) { } patch := types.UserPreferences{ - EnableMemory: req.EnableMemory, + EnableMemory: req.EnableMemory, + LastActiveTenantID: req.LastActiveTenantID, } prefs, err := h.userService.UpdateUserPreferences(ctx, user.ID, patch) if err != nil { diff --git a/internal/types/user.go b/internal/types/user.go index 50c732db..3f740b08 100644 --- a/internal/types/user.go +++ b/internal/types/user.go @@ -25,6 +25,22 @@ type UserPreferences struct { // nil = preference never set (treat as feature default = false) // *false / *true = user explicitly set the toggle. EnableMemory *bool `json:"enable_memory,omitempty"` + + // LastActiveTenantID remembers the last tenant the user actively + // switched into, so a fresh login (new device, cleared browser, new + // refresh token) lands them back in that workspace instead of always + // bouncing to their home tenant. Login / RefreshToken validate that + // the tenant still exists and the user still has an active membership + // (or CanAccessAllTenants) before honouring this preference; an + // invalid pointer is best-effort cleared and the user falls back to + // home. + // + // nil = no preference (use user.TenantID, i.e. home) + // *0 = "clear preference" sentinel for the partial-update endpoint + // (UpdateUserPreferences turns this into nil). Otherwise treat + // a stored *0 the same as nil. + // *N = preferred tenant id. + LastActiveTenantID *uint64 `json:"last_active_tenant_id,omitempty"` } // Value implements driver.Valuer so GORM persists UserPreferences as