Files
Enterprise-Knowledge-Base/frontend/src/router/index.ts
T
wizardchen 1a46fcf8ca fix(rbac): role-aware UI gates leaked write affordances after tenant switch
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.

Five distinct root causes, all on the client / server boundary:

1. `currentTenantRole` (frontend/src/stores/auth.ts) read
   `tenant.value.id` — the user's *home* tenant — instead of the active
   tenant id. After switching to A, the helper still returned B's home
   role (Owner), so every `hasRole(...)` gate in the codebase silently
   short-circuited. Fix: read `selectedTenantId` first, fall back to
   `tenant.id`.

2. `setMemberships` was only called once, on /auth/login. Hard reloads
   (which the tenant switcher triggers) re-ran `getCurrentUser()` via
   `App.vue` and `router/index.ts`, but those callers discarded the
   `memberships` field of the response, so the auth store kept the
   login-time snapshot forever. Role changes between sessions stayed
   invisible. Fix: extract memberships in both /auth/me consumers and
   feed them into `setMemberships`.

3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
   active tenant id, so any KB inside the current tenant was treated
   as "owned by the caller" — bypassing every role gate below. Fix:
   compare against `kb.creator_id` (the field PR 5 introduced) and
   require an actual creator match. `canEdit` / `canManage` now layer
   `hasRole('admin')` on top so a non-creator with sufficient role can
   still manage.

4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
   more-menu (Settings, Delete, Edit) unconditionally. With the
   ownership column from PR 5 this is straightforward to gate on the
   client: Settings/Delete now require creator-match or `hasRole('admin')`
   per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.

5. The axios interceptor (frontend/src/utils/request.ts) had a
   "selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
   short-circuit. Any code that wrote the active tenant into
   `weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
   hydrate) made the two values equal, after which the header silently
   stopped attaching and subsequent navigation requests landed on the
   home tenant. Fix: drop the short-circuit; always attach when
   selectedTenantId is set.

Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.

The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.
2026-05-18 17:28:58 +08:00

327 lines
10 KiB
TypeScript

import { createRouter, createWebHistory } from 'vue-router'
import type { RouteLocationNormalized } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { autoSetup, getCurrentUser } from '@/api/auth'
/** Lite /桌面 WebView 硬刷新时可能只打开 `/`,用 session 记住上次页面以便恢复 */
const LITE_LAST_PATH_KEY = 'weknora_lite_last_path'
const AUTO_SETUP_FAILED_KEY = 'weknora_auto_setup_failed'
function shouldTryAutoSetup() {
return localStorage.getItem(AUTO_SETUP_FAILED_KEY) !== 'true'
}
function markAutoSetupFailed() {
localStorage.setItem(AUTO_SETUP_FAILED_KEY, 'true')
}
function isLiteEdition(authStore: ReturnType<typeof useAuthStore>) {
return authStore.isLiteMode || localStorage.getItem('weknora_lite_mode') === 'true'
}
function isLiteSpaDefaultEntry(to: RouteLocationNormalized) {
return (
to.path === '/' ||
to.path === '/platform' ||
to.path === '/platform/knowledge-bases' ||
to.name === 'knowledgeBaseList'
)
}
function isSafeLiteRestoreTarget(path: string) {
return path.startsWith('/platform/') && !path.startsWith('/platform/organizations')
}
function hasPendingOIDCCallback() {
if (typeof window === 'undefined') return false
const hash = window.location.hash || ''
return hash.includes('oidc_result=') || hash.includes('oidc_error=')
}
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/",
redirect: "/platform/knowledge-bases",
},
{
path: "/login",
name: "login",
component: () => import("../views/auth/Login.vue"),
meta: { requiresAuth: false, requiresInit: false }
},
{
path: "/join",
name: "joinOrganization",
// 重定向到组织列表页,并将 code 参数转换为 invite_code
redirect: (to) => {
const code = to.query.code as string
return {
path: '/platform/organizations',
query: code ? { invite_code: code } : {}
}
},
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "/knowledgeBase",
name: "home",
component: () => import("../views/knowledge/KnowledgeBase.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "/platform",
name: "Platform",
redirect: "/platform/knowledge-bases",
component: () => import("../views/platform/index.vue"),
meta: { requiresInit: true, requiresAuth: true },
children: [
{
path: "tenant",
redirect: "/platform/settings"
},
{
path: "settings",
name: "settings",
component: () => import("../views/settings/Settings.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-bases",
name: "knowledgeBaseList",
component: () => import("../views/knowledge/KnowledgeBaseList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-bases/:kbId",
name: "knowledgeBaseDetail",
component: () => import("../views/knowledge/KnowledgeBase.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-search",
// 旧路径保留为重定向,打开全局命令面板(⌘K),带上可选的 q 参数
redirect: (to) => {
const q = to.query.q
return {
path: '/platform/knowledge-bases',
query: typeof q === 'string' ? { cmdk: q } : { cmdk: '' },
}
},
},
{
path: "agents",
name: "agentList",
component: () => import("../views/agent/AgentList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "creatChat",
name: "globalCreatChat",
component: () => import("../views/creatChat/creatChat.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "knowledge-bases/:kbId/creatChat",
name: "kbCreatChat",
component: () => import("../views/creatChat/creatChat.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "chat/:chatid",
name: "chat",
component: () => import("../views/chat/index.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
path: "organizations",
name: "organizationList",
component: () => import("../views/organization/OrganizationList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
],
},
// Dev-only markdown rendering test page
...(import.meta.env.DEV ? [{
path: '/platform/dev/markdown',
name: 'markdownTest',
component: () => import('../views/dev/MarkdownTestPage.vue'),
meta: { requiresAuth: false, requiresInit: false }
}] : []),
],
});
// 持久化 auto-setup / login 返回的认证信息到 store
function persistLoginResponse(authStore: ReturnType<typeof useAuthStore>, response: any) {
if (response.user && response.tenant && response.token) {
authStore.setUser({
id: response.user.id || '',
username: response.user.username || '',
email: response.user.email || '',
avatar: response.user.avatar,
tenant_id: String(response.tenant.id) || '',
can_access_all_tenants: response.user.can_access_all_tenants || false,
created_at: response.user.created_at || new Date().toISOString(),
updated_at: response.user.updated_at || new Date().toISOString()
})
authStore.setToken(response.token)
if (response.refresh_token) {
authStore.setRefreshToken(response.refresh_token)
}
authStore.setTenant({
id: String(response.tenant.id) || '',
name: response.tenant.name || '',
api_key: response.tenant.api_key || '',
owner_id: response.user.id || '',
created_at: response.tenant.created_at || new Date().toISOString(),
updated_at: response.tenant.updated_at || new Date().toISOString()
})
}
}
async function hydrateSessionFromToken(authStore: ReturnType<typeof useAuthStore>) {
const token = localStorage.getItem('weknora_token')
if (!token) return false
if (!authStore.token) {
authStore.setToken(token)
}
const storedRefreshToken = localStorage.getItem('weknora_refresh_token')
if (storedRefreshToken && !authStore.refreshToken) {
authStore.setRefreshToken(storedRefreshToken)
}
try {
const response = await getCurrentUser()
const user = response.data?.user
if (!response.success || !user) {
return false
}
authStore.setUser({
id: user.id || '',
username: user.username || '',
email: user.email || '',
avatar: user.avatar,
tenant_id: String(user.tenant_id || response.data?.tenant?.id || ''),
can_access_all_tenants: user.can_access_all_tenants || false,
created_at: user.created_at || new Date().toISOString(),
updated_at: user.updated_at || new Date().toISOString(),
})
const tenant = response.data?.tenant
if (tenant) {
authStore.setTenant({
id: String(tenant.id) || '',
name: tenant.name || '',
api_key: tenant.api_key || '',
owner_id: tenant.owner_id || user.id || '',
description: tenant.description,
status: tenant.status,
business: tenant.business,
storage_quota: tenant.storage_quota,
storage_used: tenant.storage_used,
created_at: tenant.created_at || new Date().toISOString(),
updated_at: tenant.updated_at || new Date().toISOString(),
})
}
// Refresh memberships on every page load — same reason as
// App.vue's syncOIDCUserContext: without this the auth store
// would only ever see the snapshot from the original /auth/login
// call, so role changes (and tenant-switch role lookups) would
// be silently stale until the user logged out and back in.
const memberships = response.data?.memberships
if (Array.isArray(memberships)) {
authStore.setMemberships(memberships)
}
return true
} catch {
return false
}
}
let autoSetupAttempted = false
let liteDeepLinkRestoreDone = false
// 路由守卫:检查认证状态和系统初始化状态
router.beforeEach(async (to, from, next) => {
const authStore = useAuthStore()
// OIDC 回跳登录结果依赖 App.vue 在挂载后消费 URL hash。
// 如果这里先按“未登录”拦截到 /login,会导致回调结果没有机会落盘。
if (hasPendingOIDCCallback()) {
next()
return
}
// Lite:硬刷新后若落在默认首页,恢复本次会话中最后访问的 /platform 子路径
if (!liteDeepLinkRestoreDone) {
liteDeepLinkRestoreDone = true
if (isLiteEdition(authStore)) {
const saved = sessionStorage.getItem(LITE_LAST_PATH_KEY)
if (saved && isSafeLiteRestoreTarget(saved) && isLiteSpaDefaultEntry(to)) {
if (saved !== to.fullPath) {
next(saved)
return
}
}
}
}
// 如果访问的是登录页面或初始化页面,直接放行
if (to.meta.requiresAuth === false || to.meta.requiresInit === false) {
// 如果已登录用户访问登录页面,重定向到知识库列表页面
if (to.path === '/login' && authStore.isLoggedIn) {
next('/platform/knowledge-bases')
return
}
next()
return
}
// 检查用户认证状态
if (to.meta.requiresAuth !== false) {
if (!authStore.isLoggedIn) {
const restored = await hydrateSessionFromToken(authStore)
if (restored) {
next(to.fullPath)
return
}
if (!autoSetupAttempted && shouldTryAutoSetup()) {
autoSetupAttempted = true
try {
const response = await autoSetup()
if (response.success) {
persistLoginResponse(authStore, response)
authStore.setLiteMode(true)
next(to.fullPath)
return
} else {
markAutoSetupFailed()
}
} catch {
markAutoSetupFailed()
}
}
next('/login')
return
}
}
next()
})
router.afterEach((to) => {
if (!isLiteEdition(useAuthStore())) return
if (to.path === '/login') return
if (!to.path.startsWith('/platform')) return
sessionStorage.setItem(LITE_LAST_PATH_KEY, to.fullPath)
})
export default router