feat(rbac): tenant member management + invite_only gate (PR 3 of 3, #1303)

Wire the human-facing surface for the tenant-RBAC system that PR 1
introduced and PR 2 enforced: REST endpoints + UI for managing tenant
members, plus the long-pending invite_only registration gate.

Backend
- internal/handler/auth.go: Register now rejects with 403 when
  auth.registration_mode=invite_only. PR 1 already exposes the mode via
  /auth/config so the frontend hides the sign-up link; this is the
  server-side enforcement for direct API calls.
- internal/handler/tenant_member.go: new TenantMemberHandler with
  ListMembers / AddMember / UpdateMemberRole / RemoveMember. Maps
  service-layer sentinels onto HTTP semantics (ErrLastOwner -> 409,
  ErrMembershipAlreadyExists -> 409, ErrUserNotFound on AddMember -> 404,
  ErrInvalidTenantRole -> 400). AddMember requires the invitee to
  already have an account; SMTP-driven email invites are deferred.
- internal/types/tenant_member.go: new TenantMemberResponse projection
  carrying the fields the management UI renders (email, username,
  avatar, role, joined_at).
- internal/router/router.go: four routes under /tenants/:id/members
  gated per the matrix (Viewer+ for list, Owner+ for every mutation).
- internal/container/container.go: dig provider for the new handler.

Tests
- handler/tenant_member_test.go: 12 table-driven cases covering happy
  path, dangling-user tolerance, ErrLastOwner -> 409, ErrMembershipNotFound
  -> 404, ErrMembershipAlreadyExists -> 409, unknown email -> 404,
  invalid role rejected before user lookup, bad tenant id -> 400.
- handler/auth_register_invite_only_test.go: invite_only -> 403,
  self_serve -> 201, nil Auth config falls through.

Frontend
- src/api/tenant/members.ts: typed client (TenantRole/TenantMember/...)
  for the four endpoints.
- src/views/settings/TenantMembers.vue: members table with add dialog,
  inline role select, confirm-remove modal. All mutation widgets gated
  behind currentTenantRole === 'owner'; server still enforces.
- src/views/settings/Settings.vue: register the Members tab; show only
  when currentTenantRole is loaded (avoids tab flash on cold nav).
- i18n in en-US/zh-CN/ko-KR/ru-RU: new tenantMember namespace covering
  all UI strings and structured error messages (lastOwner / userNotFound
  / alreadyMember / invalidRole etc).

This completes the #1303 RBAC rollout. With cfg.Tenant.EnableRBAC=true
operators now have a full management surface; with EnableRBAC=false
the routes still exist but mutations log-and-pass per PR 2 contract.
This commit is contained in:
wizardchen
2026-05-13 22:23:59 +08:00
committed by lyingbug
parent 0f0f7e4339
commit 3f7150cb5c
14 changed files with 1570 additions and 17 deletions
+43 -15
View File
@@ -142,6 +142,11 @@
<TenantInfo />
</div>
<!-- 成员管理 (#1303 PR 3) -->
<div v-if="currentSection === 'members'" class="section">
<TenantMembers />
</div>
<!-- API 信息 -->
<div v-if="currentSection === 'api'" class="section">
<ApiInfo />
@@ -164,6 +169,7 @@
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
import { useI18n } from 'vue-i18n'
import SystemInfo from './SystemInfo.vue'
import TenantInfo from './TenantInfo.vue'
@@ -178,31 +184,53 @@ import VectorStoreSettings from './VectorStoreSettings.vue'
import ParserEngineSettings from './ParserEngineSettings.vue'
import StorageEngineSettings from './StorageEngineSettings.vue'
import WeKnoraCloudSettings from './WeKnoraCloudSettings.vue'
import TenantMembers from './TenantMembers.vue'
const route = useRoute()
const router = useRouter()
const uiStore = useUIStore()
const authStore = useAuthStore()
const { t } = useI18n()
const currentSection = ref<string>('general')
const currentSubSection = ref<string>('')
const expandedMenus = ref<string[]>([])
const navItems = computed(() => [
{ key: 'general', icon: 'setting', label: t('general.title') },
{ key: 'ollama', icon: 'server', label: 'Ollama' },
{ key: 'weknoracloud', icon: '', label: 'WeKnora Cloud' },
{ key: 'models', icon: 'control-platform', label: t('settings.modelManagement') },
{ key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') },
{ key: 'chathistory', icon: 'chat', label: t('chatHistorySettings.title') },
{ key: 'vectorstore', icon: 'data-base', label: t('settings.vectorStoreEngine') },
{ key: 'parser', icon: 'file-search', label: t('settings.parserEngine') },
{ 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: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },
{ key: 'api', icon: 'secured', label: t('settings.apiInfo') }
])
const navItems = computed(() => {
// Optional `children` keeps the existing template's submenu plumbing
// happy (it iterates `item.children`); none of the current tabs use
// it, but staying compatible avoids introducing a new typing-only
// diff scattered across the template.
type NavItem = {
key: string
icon: string
label: string
children?: Array<{ key: string; label: string }>
}
const items: NavItem[] = [
{ key: 'general', icon: 'setting', label: t('general.title') },
{ key: 'ollama', icon: 'server', label: 'Ollama' },
{ key: 'weknoracloud', icon: '', label: 'WeKnora Cloud' },
{ key: 'models', icon: 'control-platform', label: t('settings.modelManagement') },
{ key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') },
{ key: 'chathistory', icon: 'chat', label: t('chatHistorySettings.title') },
{ key: 'vectorstore', icon: 'data-base', label: t('settings.vectorStoreEngine') },
{ key: 'parser', icon: 'file-search', label: t('settings.parserEngine') },
{ 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: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },
]
// 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') })
}
items.push({ key: 'api', icon: 'secured', label: t('settings.apiInfo') })
return items
})
// 导航项点击处理
const handleNavClick = (item: any) => {
@@ -0,0 +1,374 @@
<template>
<div class="tenant-members">
<div class="section-header">
<h2>{{ $t('tenantMember.title') }}</h2>
<p class="section-description">{{ $t('tenantMember.sectionDescription') }}</p>
</div>
<!-- Action bar: count + add-member button (Owner only). -->
<div class="action-bar">
<span class="count">
{{ $t('tenantMember.totalCount', { n: members.length }) }}
</span>
<t-button
v-if="canManage"
theme="primary"
size="small"
@click="openAddDialog"
>
{{ $t('tenantMember.add.button') }}
</t-button>
</div>
<!-- Loading -->
<div v-if="loading" class="loading-inline">
<t-loading size="small" />
<span>{{ $t('tenantMember.loading') }}</span>
</div>
<!-- Error -->
<div v-else-if="error" class="error-inline">
<t-alert theme="error" :message="error">
<template #operation>
<t-button size="small" @click="loadMembers">{{ $t('tenantMember.retry') }}</t-button>
</template>
</t-alert>
</div>
<!-- Member table -->
<t-table
v-else
row-key="user_id"
:data="members"
:columns="columns"
size="medium"
hover
stripe
>
<template #role="{ row }">
<t-select
v-if="canManage && row.user_id !== authStore.user?.id"
:model-value="row.role"
:options="roleOptions"
size="small"
style="width: 130px"
@change="(val: string) => onRoleChange(row, val)"
/>
<t-tag v-else :theme="roleTagTheme(row.role)" size="medium">
{{ $t('tenantMember.role.' + row.role) }}
</t-tag>
</template>
<template #joined_at="{ row }">{{ formatDate(row.joined_at) }}</template>
<template #actions="{ row }">
<t-button
v-if="canManage && row.user_id !== authStore.user?.id"
theme="danger"
variant="text"
size="small"
@click="confirmRemove(row)"
>
{{ $t('tenantMember.remove.button') }}
</t-button>
</template>
</t-table>
<!-- Add dialog -->
<t-dialog
v-model:visible="addDialogVisible"
:header="$t('tenantMember.add.dialogTitle')"
:on-confirm="submitAdd"
:confirm-btn="{ content: $t('tenantMember.add.submit'), loading: adding }"
:cancel-btn="{ content: $t('common.cancel') }"
width="480px"
>
<t-form ref="addFormRef" :data="addForm" :rules="addFormRules" :label-width="80">
<t-form-item :label="$t('tenantMember.add.emailLabel')" name="email">
<t-input
v-model="addForm.email"
:placeholder="$t('tenantMember.add.emailPlaceholder')"
clearable
/>
</t-form-item>
<t-form-item :label="$t('tenantMember.add.roleLabel')" name="role">
<t-select v-model="addForm.role" :options="roleOptions" />
</t-form-item>
</t-form>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useAuthStore } from '@/stores/auth'
import {
listMembers,
addMember,
updateMemberRole,
removeMember,
type TenantMember,
type TenantRole,
} from '@/api/tenant/members'
const { t, locale } = useI18n()
const authStore = useAuthStore()
// State
const members = ref<TenantMember[]>([])
const loading = ref(false)
const error = ref('')
const adding = ref(false)
const addDialogVisible = ref(false)
const addFormRef = ref<any>(null)
// Add dialog model — reset on each open. Default role is contributor:
// inviting a fresh member with viewer is too restrictive for the
// expected "let them collaborate on KBs" use case, and admin/owner
// should be a deliberate promote step after the user accepts.
const addForm = reactive<{ email: string; role: TenantRole }>({
email: '',
role: 'contributor',
})
// canManage gates every mutation widget. The server enforces the same
// rule (Owner+); the UI gate just hides controls that would 403 anyway,
// matching the security note in stores/auth.ts.
const canManage = computed(() => authStore.currentTenantRole === 'owner')
// Use the active tenant id from the auth store; the route only allows
// :id == active tenant (auth middleware enforces membership), so we
// don't expose a tenant picker here.
const activeTenantId = computed(() => Number(authStore.currentTenantId ?? 0))
const roleOptions = computed(() => [
{ label: t('tenantMember.role.owner'), value: 'owner' },
{ label: t('tenantMember.role.admin'), value: 'admin' },
{ label: t('tenantMember.role.contributor'), value: 'contributor' },
{ label: t('tenantMember.role.viewer'), value: 'viewer' },
])
const columns = computed(() => [
{ colKey: 'username', title: t('tenantMember.columns.username'), ellipsis: true },
{ colKey: 'email', title: t('tenantMember.columns.email'), ellipsis: true },
{ colKey: 'role', title: t('tenantMember.columns.role'), width: 160 },
{ colKey: 'joined_at', title: t('tenantMember.columns.joinedAt'), width: 180 },
{ colKey: 'actions', title: '', width: 100, align: 'right' },
])
const addFormRules = {
email: [
{ required: true, message: t('tenantMember.errors.emailRequired'), trigger: 'blur' },
{ email: true, message: t('tenantMember.errors.emailFormat'), trigger: 'blur' },
],
role: [{ required: true, message: t('tenantMember.errors.roleRequired'), trigger: 'change' }],
}
// Pretty role tag colour: Owner stands out, Admin is warning, the rest
// stay neutral so the table doesn't become a confetti cannon.
function roleTagTheme(role: TenantRole): 'primary' | 'warning' | 'success' | 'default' {
switch (role) {
case 'owner':
return 'primary'
case 'admin':
return 'warning'
case 'contributor':
return 'success'
default:
return 'default'
}
}
function formatDate(s: string | undefined): string {
if (!s) return '-'
try {
const d = new Date(s)
return new Intl.DateTimeFormat(locale.value || 'zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(d)
} catch {
return s
}
}
async function loadMembers() {
if (!activeTenantId.value) {
error.value = t('tenantMember.errors.noTenant')
return
}
loading.value = true
error.value = ''
try {
const resp = await listMembers(activeTenantId.value)
if (resp.success && resp.data) {
members.value = resp.data.members
} else {
error.value = resp.message || t('tenantMember.errors.generic')
}
} catch (err: any) {
error.value = err?.message || t('tenantMember.errors.generic')
} finally {
loading.value = false
}
}
function openAddDialog() {
addForm.email = ''
addForm.role = 'contributor'
addDialogVisible.value = true
}
async function submitAdd() {
// t-form's validate returns true on success or an object of field
// errors on failure. We treat anything non-true as a validation
// failure — keeps the dialog open with the inline messages shown.
const valid = await addFormRef.value?.validate?.()
if (valid !== true) return
adding.value = true
try {
const resp = await addMember(activeTenantId.value, {
email: addForm.email.trim(),
role: addForm.role,
})
if (resp.success && resp.data) {
members.value = [...members.value, resp.data]
addDialogVisible.value = false
MessagePlugin.success(t('tenantMember.add.success'))
} else {
MessagePlugin.error(resp.message || t('tenantMember.errors.generic'))
}
} catch (err: any) {
// Map the server's structured error responses (404 / 409 / 400) to
// human-readable messages. The Axios layer surfaces them as
// err.response?.data?.error in this codebase.
const status = err?.response?.status
const apiMsg = err?.response?.data?.error || err?.message
if (status === 404) {
MessagePlugin.error(t('tenantMember.errors.userNotFound'))
} else if (status === 409) {
MessagePlugin.error(t('tenantMember.errors.alreadyMember'))
} else {
MessagePlugin.error(apiMsg || t('tenantMember.errors.generic'))
}
} finally {
adding.value = false
}
}
async function onRoleChange(row: TenantMember, newRole: string) {
const prev = row.role
const next = newRole as TenantRole
if (prev === next) return
try {
const resp = await updateMemberRole(activeTenantId.value, row.user_id, next)
if (resp.success) {
row.role = next
MessagePlugin.success(t('tenantMember.roleChange.success'))
return
}
MessagePlugin.error(resp.message || t('tenantMember.errors.generic'))
} catch (err: any) {
const status = err?.response?.status
if (status === 409) {
MessagePlugin.error(t('tenantMember.errors.lastOwner'))
} else if (status === 404) {
MessagePlugin.error(t('tenantMember.errors.notFound'))
} else {
MessagePlugin.error(err?.response?.data?.error || err?.message || t('tenantMember.errors.generic'))
}
// Force the t-select to revert visually by mutating then restoring.
// Vue's reactive system needs a real change to refire the bind.
row.role = '' as TenantRole
setTimeout(() => {
row.role = prev
}, 0)
}
}
function confirmRemove(row: TenantMember) {
// Use DialogPlugin.confirm rather than t-popconfirm so we can describe
// the consequences in a multi-line modal (matches the pattern used in
// ApiInfo.vue's reset-API-key flow).
const dlg = DialogPlugin.confirm({
header: t('tenantMember.remove.confirmTitle'),
body: t('tenantMember.remove.confirmBody', { name: row.username || row.email }),
confirmBtn: { content: t('tenantMember.remove.confirm'), theme: 'danger' },
cancelBtn: t('common.cancel'),
onConfirm: async () => {
try {
const resp = await removeMember(activeTenantId.value, row.user_id)
if (resp.success) {
members.value = members.value.filter((m) => m.user_id !== row.user_id)
MessagePlugin.success(t('tenantMember.remove.success'))
} else {
MessagePlugin.error(resp.message || t('tenantMember.errors.generic'))
}
} catch (err: any) {
const status = err?.response?.status
if (status === 409) {
MessagePlugin.error(t('tenantMember.errors.lastOwner'))
} else if (status === 404) {
MessagePlugin.error(t('tenantMember.errors.notFound'))
} else {
MessagePlugin.error(err?.response?.data?.error || err?.message || t('tenantMember.errors.generic'))
}
} finally {
dlg.destroy()
}
},
onClose: () => dlg.destroy(),
})
}
onMounted(() => {
loadMembers()
})
</script>
<style lang="less" scoped>
.tenant-members {
width: 100%;
}
.section-header {
margin-bottom: 24px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
margin: 0 0 8px 0;
}
.section-description {
color: var(--td-text-color-secondary);
font-size: 13px;
margin: 0;
}
}
.action-bar {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
.count {
font-size: 13px;
color: var(--td-text-color-secondary);
}
}
.loading-inline,
.error-inline {
display: flex;
align-items: center;
gap: 8px;
padding: 16px 0;
}
</style>