feat(rbac-ui): rework tenant identity surfaces

Polish the role-aware UI surfaces wired up in #1303 so role / tenant
context is discoverable from the main shell rather than buried in a
hover-only switcher or the settings drawer.

UserMenu sidebar trigger:
- Replace username + email with `tenant name / username · role-icon
  role-name` so the active tenant + current role are always visible at
  the bottom of the sidebar; long usernames elide before the role label.
- Single-tenant users keep the old username + email layout.

UserMenu dropdown:
- Promote the tenant switcher to a clickable header row at the top of
  the dropdown (tenant name + swap icon, role caption underneath).
- Drop the standalone "Switch tenant" submenu entry — the header row
  hosts the same hover panel.
- Switcher panel rows now lead the role label with a role icon
  (owner / admin / contributor / viewer) and surface the home tenant
  via a small home dot on the avatar instead of a separate badge, so
  the right-edge "current" badge column lines up across rows.

Settings:
- Add SECTION_MIN_ROLE so settings nav entries are gated by the same
  role matrix the backend enforces (chathistory + ollama + websearch +
  vectorstore + parser + storage + mcp → admin; api → owner; rest →
  viewer). UserMenu quickNav uses the same map.
- Render a role-denied empty state when a user deep-links into a
  section their role can't reach.
- Split account info (id / username / email / created_at) out of the
  owner-only API Info page into a new viewer-accessible UserProfile
  section.

Composable:
- New useRoleLabel composable centralises role → label and role → icon
  mapping (consumed by UserMenu trigger / dropdown / switcher panel).
- useHomeTenant derives the home tenant id from `user.tenant_id` (the
  immutable signup-time field), not `tenant.id` which now reflects the
  active tenant after a switch.

Lists:
- KnowledgeBaseList / AgentList default the sidebar selection to "all"
  for viewers (who typically own nothing) so the empty "Mine" state no
  longer hides the shared content they actually have access to;
  contributor+ keeps "Mine" as the default.

i18n:
- Tenant role labels: 拥有者/贡献者/查看者 → 所有者/编辑/访客 (all four
  locales updated, plus new userProfile / roleDenied / homeBadge keys).

The org-vs-tenant scope question raised during review is intentionally
out of scope here — that needs an RFC before any UI/backend changes.
This commit is contained in:
wizardchen
2026-05-15 17:49:16 +08:00
committed by lyingbug
parent 2c34446425
commit e7f9a6580a
11 changed files with 780 additions and 134 deletions
+6 -2
View File
@@ -582,8 +582,12 @@ interface AgentWithUI extends CustomAgent {
/** Merged agent for "all" tab: my agents (isMine: true) or shared (isMine: false, org_name, source_tenant_id, share_id, disabled_by_me?) */
type DisplayAgent = (AgentWithUI & { isMine: true }) | (CustomAgent & { isMine: false; org_name: string; source_tenant_id: number; share_id: string; showMore?: boolean; disabled_by_me?: boolean })
// 左侧空间选择:我的 / 空间 ID(已去掉「全部」)
const spaceSelection = ref<'all' | 'mine' | string>('mine')
// 左侧空间选择:默认根据当前角色决定。
// 与 KnowledgeBaseList 同款逻辑:Viewer 在当前租户里通常没有自建智能体,
// 默认落到 "all" 才能看到内置 + 共享给我的;Contributor 以上仍默认 "mine"。
const initialSpaceSelection = (): 'all' | 'mine' =>
authStore.hasRole('contributor') ? 'mine' : 'all'
const spaceSelection = ref<'all' | 'mine' | string>(initialSpaceSelection())
const agents = ref<AgentWithUI[]>([])
const sharedAgents = computed<SharedAgentInfo[]>(() => orgStore.sharedAgents || [])
const allAgentsCount = computed(() => agents.value.length + sharedAgents.value.length)
@@ -669,8 +669,13 @@ const authStore = useAuthStore()
const orgStore = useOrganizationStore()
const { t } = useI18n()
// 左侧空间选择:我的 / 空间 ID(已去掉「全部」)
const spaceSelection = ref<'all' | 'mine' | 'shared' | string>('mine')
// 左侧空间选择:默认根据当前角色决定。
// Viewer 在该租户里通常 0 KB owned,"我的"会显示空状态、又把共享 KB 藏起来,
// 体验非常误导;所以 Viewer 默认落到 "all"(我的 + 共享给我都显示)。
// Contributor 及以上一进来主要管理自己创建的 KB,仍默认 "mine"。
const initialSpaceSelection = (): 'all' | 'mine' =>
authStore.hasRole('contributor') ? 'mine' : 'all'
const spaceSelection = ref<'all' | 'mine' | 'shared' | string>(initialSpaceSelection())
interface KB {
id: string;
+7 -71
View File
@@ -172,73 +172,28 @@
</p>
</div>
</div>
<!-- User info -->
<div class="info-section-title">{{ $t('tenant.api.userSectionTitle') }}</div>
<!-- User ID -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('tenant.api.userIdLabel') }}</label>
<p class="desc">{{ $t('tenant.api.userIdDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.id || '-' }}</span>
</div>
</div>
<!-- Username -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('tenant.api.usernameLabel') }}</label>
<p class="desc">{{ $t('tenant.api.usernameDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.username || '-' }}</span>
</div>
</div>
<!-- Email -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('tenant.api.emailLabel') }}</label>
<p class="desc">{{ $t('tenant.api.emailDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.email || '-' }}</span>
</div>
</div>
<!-- Created at -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('tenant.api.createdAtLabel') }}</label>
<p class="desc">{{ $t('tenant.api.createdAtDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ formatDate(userInfo?.created_at) }}</span>
</div>
</div>
<!-- 用户信息原本嵌在这一页底部,但 api 信息页是 owner-only(要看
api key + reset),把用户基本信息(id / 用户名 / 邮箱 / 注册
时间)也卡在这里意味着 viewer / contributor 看不到自己的账户
信息。已拆到独立的 UserProfile.vue(settings 里 viewer 可见)。 -->
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getCurrentUser, type TenantInfo, type UserInfo } from '@/api/auth'
import { getCurrentUser, type TenantInfo } from '@/api/auth'
import { resetTenantApiKey } from '@/api/tenant'
import { getApiBaseUrl } from '@/utils/api-base'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
const { t, locale } = useI18n()
const { t } = useI18n()
const authStore = useAuthStore()
// Reactive state
const tenantInfo = ref<TenantInfo | null>(null)
const userInfo = ref<UserInfo | null>(null)
const loading = ref(true)
const error = ref('')
const showApiKey = ref(false)
@@ -430,9 +385,8 @@ const loadInfo = async () => {
error.value = ''
const userResponse = await getCurrentUser()
if ((userResponse as any).success && userResponse.data) {
userInfo.value = userResponse.data.user
tenantInfo.value = userResponse.data.tenant
} else {
error.value = userResponse.message || t('tenant.messages.fetchFailed')
@@ -546,24 +500,6 @@ const copyApiUrl = async () => {
}
}
const formatDate = (dateStr: string | undefined) => {
if (!dateStr) return t('tenant.unknown')
try {
const date = new Date(dateStr)
const formatter = new Intl.DateTimeFormat(locale.value || 'zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
return formatter.format(date)
} catch {
return t('tenant.formatError')
}
}
// Lifecycle
onMounted(async () => {
await tryLoadWailsApiBaseURL()
+110 -10
View File
@@ -90,6 +90,17 @@
<!-- 右侧内容区域 -->
<div class="settings-content">
<div class="content-wrapper">
<!-- 角色不允许访问当前 section(deep-link 进来 / 跨租户切换后角色降级)—— 优先于具体 section 渲染。
正常导航走 navItems filter 不会到这里,但 watch(navItems) 的 fallback 会在角色降级
的瞬间触发;这一段做兜底兼容旧 URL。 -->
<div v-if="!canSeeSection(currentSection)" class="section role-denied">
<div class="role-denied-icon">
<t-icon name="lock-on" size="48px" />
</div>
<div class="role-denied-title">{{ $t('settings.roleDenied.title') }}</div>
<div class="role-denied-desc">{{ $t('settings.roleDenied.desc') }}</div>
</div>
<template v-else>
<!-- 常规设置 -->
<div v-if="currentSection === 'general'" class="section">
<GeneralSettings />
@@ -140,6 +151,13 @@
<SystemInfo />
</div>
<!-- 用户信息(账户基础信息:ID / 用户名 / 邮箱 / 注册时间)。
从 ApiInfo.vue 拆出来,原页面挂的是 owner-only 入口,
用户的基本信息不该跟 owner 权限绑定。 -->
<div v-if="currentSection === 'userprofile'" class="section">
<UserProfile />
</div>
<!-- 租户信息 -->
<div v-if="currentSection === 'tenant'" class="section">
<TenantInfo />
@@ -159,6 +177,7 @@
<div v-if="currentSection === 'mcp'" class="section">
<McpSettings />
</div>
</template>
</div>
</div>
</div>
@@ -177,6 +196,7 @@ import { useI18n } from 'vue-i18n'
import SystemInfo from './SystemInfo.vue'
import TenantInfo from './TenantInfo.vue'
import ApiInfo from './ApiInfo.vue'
import UserProfile from './UserProfile.vue'
import GeneralSettings from './GeneralSettings.vue'
import ModelSettings from './ModelSettings.vue'
import OllamaSettings from './OllamaSettings.vue'
@@ -212,8 +232,52 @@ type NavGroup = {
items: NavItem[]
}
// 设置二级导航的最低可见角色:和 internal/router/router.go 的守卫矩阵对齐。
// 以「页面里至少有 1 个有意义的写操作所要求的最低角色」为基准,把基础设
// 施配置(models 写、ollama 下载、websearch 写、parser/storage/vector/mcp
// CRUD、chat-history 配置)统一收到 admin;只读类(general / system info /
// tenant-info / members 名册)保留 viewer 可见;最高敏感的 reset api
// key 是 owner-only。改这张表前请在 router.go 里复核对应路由组。
//
// 特别说明:
// - chathistory 页面唯一的「启用消息索引」开关 PUT /tenants/kv/chat-history-config
// 后端走 g.Admin()。给 viewer/contributor 看到入口、点开开关、保存时
// 403,体验很差,所以入口本身归 admin。
// - models 列表 viewer 可读,页面内的「+ 添加模型 / 编辑 / 删除」按钮在
// ModelSettings.vue 里另用 hasRole('admin') 自己 gate,所以入口保留
// viewer 是合理的(contributor 也能浏览模型列表)。
type RoleKey = 'viewer' | 'contributor' | 'admin' | 'owner'
const SECTION_MIN_ROLE: Record<string, RoleKey> = {
general: 'viewer',
ollama: 'admin',
weknoracloud: 'admin',
models: 'viewer',
websearch: 'admin',
chathistory: 'admin',
vectorstore: 'admin',
parser: 'admin',
storage: 'admin',
mcp: 'admin',
system: 'viewer',
userprofile: 'viewer',
tenant: 'viewer',
members: 'viewer',
api: 'owner',
}
const canSeeSection = (key: string): boolean => {
const min = SECTION_MIN_ROLE[key] ?? 'viewer'
// canAccessAllTenants(superuser)和路由层一样必须 bypass,否则 cross-tenant
// 管理员看不到自己有权操作的入口(参考 TenantMembers.vue 的 canManage)。
if (authStore.canAccessAllTenants) return true
return authStore.hasRole(min)
}
const navItems = computed(() => {
const items: NavItem[] = [
// 一律走 SECTION_MIN_ROLE 表,避免 ad-hoc isAdmin/isOwner 散落在多处。
// 服务端在每条路由上仍以 g.Viewer/Admin/Owner 为准,这里只决定 UI 是
// 否露入口;改动入口规则请同步更新 SECTION_MIN_ROLE 注释里的对照路由。
const all: NavItem[] = [
{ key: 'general', icon: 'setting', label: t('general.title') },
{ key: 'ollama', icon: 'server', label: 'Ollama' },
{ key: 'weknoracloud', icon: '', label: 'WeKnora Cloud' },
@@ -225,17 +289,18 @@ const navItems = computed(() => {
{ key: 'storage', icon: 'cloud', label: t('settings.storageEngine') },
{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },
{ key: 'system', icon: 'info-circle', label: t('settings.systemSettings') },
{ key: 'userprofile', icon: 'user', label: t('userProfile.title') },
{ key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },
{ key: 'members', icon: 'usergroup', label: t('tenantMember.title') },
{ key: 'api', icon: 'secured', label: t('settings.apiInfo') },
]
// Member management is hidden until the auth middleware resolves a
// real tenant role for the user. Empty string means "membership not
// loaded yet" — better to suppress the tab than to flash it on cold
// navigation. Server still enforces every mutation.
if (authStore.currentTenantRole) {
items.push({ key: 'members', icon: 'usergroup', label: t('tenantMember.title') })
// currentTenantRole 为空表示「membership 还没加载」—— 比起渲染整套
// viewer 入口然后角色一返回又消失,先卡住不渲染更稳,跟原先 members
// 入口的策略一致。
if (!authStore.currentTenantRole && !authStore.canAccessAllTenants) {
return [] as NavItem[]
}
items.push({ key: 'api', icon: 'secured', label: t('settings.apiInfo') })
return items
return all.filter((it) => canSeeSection(it.key))
})
const navGroups = computed<NavGroup[]>(() => {
@@ -245,7 +310,7 @@ const navGroups = computed<NavGroup[]>(() => {
{ key: 'basic', label: t('settings.navGroups.basic'), items: pickItems(['general']) },
{ key: 'ai', label: t('settings.navGroups.ai'), items: pickItems(['models', 'ollama', 'weknoracloud', 'websearch', 'mcp']) },
{ key: 'data', label: t('settings.navGroups.data'), items: pickItems(['vectorstore', 'parser', 'storage']) },
{ key: 'workspace', label: t('settings.navGroups.workspace'), items: pickItems(['tenant', 'members']) },
{ key: 'workspace', label: t('settings.navGroups.workspace'), items: pickItems(['userprofile', 'tenant', 'members']) },
{ key: 'system', label: t('settings.navGroups.system'), items: pickItems(['chathistory', 'system', 'api']) },
].filter((group) => group.items.length > 0)
})
@@ -321,6 +386,15 @@ watch(() => uiStore.settingsInitialSection, (section) => {
}
}, { immediate: true })
// 切换租户后角色可能变化,原本可见的 admin-only 面板可能消失。
// 如果 currentSection 落到了不再显示的 key 上,就回退到第一个可见项。
watch(navItems, (items) => {
if (!items.some((item) => item.key === currentSection.value)) {
currentSection.value = items[0]?.key || 'general'
currentSubSection.value = ''
}
})
// ESC 键关闭
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && visible.value) {
@@ -634,5 +708,31 @@ onUnmounted(() => {
.settings-content::-webkit-scrollbar-thumb:hover {
background: var(--td-gray-color-6);
}
.role-denied {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 64px 24px;
gap: 12px;
min-height: 240px;
.role-denied-icon {
color: var(--td-text-color-placeholder);
}
.role-denied-title {
font-size: 16px;
font-weight: 600;
color: var(--td-text-color-primary);
}
.role-denied-desc {
font-size: 13px;
color: var(--td-text-color-secondary);
max-width: 360px;
line-height: 1.6;
}
}
</style>
+210
View File
@@ -0,0 +1,210 @@
<template>
<div class="user-profile">
<div class="section-header">
<h2>{{ $t('userProfile.title') }}</h2>
<p class="section-description">{{ $t('userProfile.description') }}</p>
</div>
<!-- Loading -->
<div v-if="loading" class="loading-inline">
<t-loading size="small" />
<span>{{ $t('tenant.loadingInfo') }}</span>
</div>
<!-- Error -->
<div v-else-if="error" class="error-inline">
<t-alert theme="error" :message="error">
<template #operation>
<t-button size="small" @click="loadInfo">{{ $t('tenant.retry') }}</t-button>
</template>
</t-alert>
</div>
<!-- Content -->
<div v-else class="settings-group">
<!-- 用户 ID -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('tenant.api.userIdLabel') }}</label>
<p class="desc">{{ $t('tenant.api.userIdDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.id || '-' }}</span>
</div>
</div>
<!-- 用户名 -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('tenant.api.usernameLabel') }}</label>
<p class="desc">{{ $t('tenant.api.usernameDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.username || '-' }}</span>
</div>
</div>
<!-- 邮箱 -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('tenant.api.emailLabel') }}</label>
<p class="desc">{{ $t('tenant.api.emailDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.email || '-' }}</span>
</div>
</div>
<!-- 注册时间 -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('tenant.api.createdAtLabel') }}</label>
<p class="desc">{{ $t('tenant.api.createdAtDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ formatDate(userInfo?.created_at) }}</span>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getCurrentUser, type UserInfo } from '@/api/auth'
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
const userInfo = ref<UserInfo | null>(null)
const loading = ref(true)
const error = ref('')
const loadInfo = async () => {
try {
loading.value = true
error.value = ''
const resp = await getCurrentUser()
if ((resp as any).success && resp.data) {
userInfo.value = resp.data.user
} else {
error.value = resp.message || t('tenant.messages.fetchFailed')
}
} catch (err: any) {
error.value = err?.message || t('tenant.messages.networkError')
} finally {
loading.value = false
}
}
const formatDate = (dateStr: string | undefined) => {
if (!dateStr) return t('tenant.unknown')
try {
const d = new Date(dateStr)
const fmt = new Intl.DateTimeFormat(locale.value || 'zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
return fmt.format(d)
} catch {
return t('tenant.formatError')
}
}
onMounted(loadInfo)
</script>
<style lang="less" scoped>
.user-profile {
width: 100%;
}
.section-header {
margin-bottom: 32px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
margin: 0 0 8px 0;
}
.section-description {
font-size: 14px;
color: var(--td-text-color-secondary);
margin: 0;
line-height: 1.5;
}
}
.loading-inline {
display: flex;
align-items: center;
gap: 12px;
padding: 40px 0;
justify-content: center;
color: var(--td-text-color-secondary);
font-size: 14px;
}
.error-inline {
padding: 20px 0;
}
.settings-group {
display: flex;
flex-direction: column;
gap: 0;
}
.setting-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 20px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
border-bottom: none;
}
}
.setting-info {
flex: 1;
max-width: 65%;
padding-right: 24px;
label {
font-size: 15px;
font-weight: 500;
color: var(--td-text-color-primary);
display: block;
margin-bottom: 4px;
}
.desc {
font-size: 13px;
color: var(--td-text-color-secondary);
margin: 0;
line-height: 1.5;
}
}
.setting-control {
flex-shrink: 0;
min-width: 280px;
display: flex;
justify-content: flex-end;
align-items: flex-start;
.info-value {
font-size: 14px;
color: var(--td-text-color-primary);
text-align: right;
word-break: break-word;
}
}
</style>