fix(rbac): polish tenant member UI; add /leave endpoint

Self-review of PR 3's TenantMembers.vue surfaced a handful of real bugs
and a few rough edges. This commit fixes them and adds the self-leave
endpoint that PR 3's design called out as a follow-up.

Frontend bug fixes
- Read err.status (not err.response.status). The axios interceptor in
  utils/request.ts already flattens errors into { status, message,
  ... }, so the original branch-by-status code never matched and every
  4xx fell through to the generic toast. Fixes 404/409 surfacing as
  "userNotFound" / "alreadyMember" / "lastOwner" instead of "Something
  went wrong".
- t-dialog @confirm replaces :on-confirm so the dialog stays open on
  validation failure and on API error. Users can fix and retry without
  retyping the email.
- Drop the t-select revert hack; with :model-value the rendered value
  is already source-of-truth-on-row.role, so no setTimeout dance is
  needed.
- Don't toast "no active tenant" on cold mount; watch the activeTenantId
  ref and load once the auth store hydrates.

Frontend UX additions
- Empty state via t-empty (also covers the search-no-results case).
- Compact role-permissions matrix above the table, mirroring
  OrganizationSettingsModal so Owners can see what each role grants
  before promoting/inviting.
- Search box filtering by username/email (client-side, sufficient for
  expected per-tenant member counts).
- "Leave Tenant" button — visible to any active member except the
  last-Owner case (server still enforces).

Backend
- New POST /tenants/:id/leave route. Calls TenantMemberService.RemoveMember
  with the caller's own user id so non-Owners can quit on their own.
  Gated Viewer+ in the matrix; the existing last-Owner invariant in the
  service still rejects last-Owner self-leave with 409.
- 3 new handler tests cover the happy path, the last-Owner 409 path,
  and the missing-caller-id 401 path (defensive — auth middleware
  always attaches a user, but the test pins the contract).

i18n
- Add tenantMember.permissions / search / leave / empty strings in all
  four locales (en/zh/ko/ru).
This commit is contained in:
wizardchen
2026-05-13 22:55:15 +08:00
committed by lyingbug
parent 3f7150cb5c
commit ae7cd02cd6
9 changed files with 532 additions and 43 deletions
+328 -39
View File
@@ -5,19 +5,72 @@
<p class="section-description">{{ $t('tenantMember.sectionDescription') }}</p>
</div>
<!-- Action bar: count + add-member button (Owner only). -->
<!-- Compact role-permissions matrix. Mirrors the OrganizationSettingsModal
pattern so Owners (and Admins, who can't add members) understand
what each role can actually do before they invite or promote. -->
<div class="permissions-compact">
<div class="permissions-compact-header">
<span class="permissions-compact-title">{{ $t('tenantMember.permissions.title') }}</span>
<span class="permissions-compact-desc">{{ $t('tenantMember.permissions.desc') }}</span>
</div>
<div class="permissions-compact-grid">
<div
v-for="r in roleMatrixOrder"
:key="r"
:class="['perm-role-block', r, { 'is-me': currentRole === r }]"
>
<div class="perm-role-tag">
<t-icon :name="roleMatrixIcon(r)" size="12px" />
<span>{{ $t('tenantMember.role.' + r) }}</span>
<span v-if="currentRole === r" class="me-badge">{{ $t('common.me') }}</span>
</div>
<div class="perm-items">
<span
v-for="(perm, i) in roleMatrix[r]"
:key="i"
:class="['perm-item', perm.has ? 'has' : 'no']"
>
<t-icon :name="perm.has ? 'check' : 'close'" size="12px" />
{{ $t('tenantMember.permissions.' + perm.key) }}
</span>
</div>
</div>
</div>
</div>
<!-- Action bar: count + search + 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 class="action-bar-right">
<t-input
v-model="searchQuery"
:placeholder="$t('tenantMember.searchPlaceholder')"
clearable
size="small"
style="width: 220px"
>
<template #prefix-icon><t-icon name="search" /></template>
</t-input>
<t-button
v-if="canManage"
theme="primary"
size="small"
@click="openAddDialog"
>
{{ $t('tenantMember.add.button') }}
</t-button>
<t-button
v-if="canLeave"
theme="danger"
variant="outline"
size="small"
@click="confirmLeaveTenant"
>
{{ $t('tenantMember.leave.button') }}
</t-button>
</div>
</div>
<!-- Loading -->
@@ -35,11 +88,23 @@
</t-alert>
</div>
<!-- Empty state when there are no members at all OR the search query
filters everything out. -->
<div v-else-if="filteredMembers.length === 0" class="empty-state">
<t-empty
:description="
searchQuery
? $t('tenantMember.emptySearch', { q: searchQuery })
: $t('tenantMember.empty')
"
/>
</div>
<!-- Member table -->
<t-table
v-else
row-key="user_id"
:data="members"
:data="filteredMembers"
:columns="columns"
size="medium"
hover
@@ -47,7 +112,7 @@
>
<template #role="{ row }">
<t-select
v-if="canManage && row.user_id !== authStore.user?.id"
v-if="canManage && row.user_id !== currentUserId"
:model-value="row.role"
:options="roleOptions"
size="small"
@@ -61,7 +126,7 @@
<template #joined_at="{ row }">{{ formatDate(row.joined_at) }}</template>
<template #actions="{ row }">
<t-button
v-if="canManage && row.user_id !== authStore.user?.id"
v-if="canManage && row.user_id !== currentUserId"
theme="danger"
variant="text"
size="small"
@@ -72,14 +137,16 @@
</template>
</t-table>
<!-- Add dialog -->
<!-- Add dialog. We use @confirm rather than :on-confirm so we can
keep the dialog open on validation failure / API error and let
the user retry without retyping. -->
<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"
@confirm="submitAdd"
>
<t-form ref="addFormRef" :data="addForm" :rules="addFormRules" :label-width="80">
<t-form-item :label="$t('tenantMember.add.emailLabel')" name="email">
@@ -98,7 +165,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useAuthStore } from '@/stores/auth'
@@ -107,6 +174,7 @@ import {
addMember,
updateMemberRole,
removeMember,
leaveTenant,
type TenantMember,
type TenantRole,
} from '@/api/tenant/members'
@@ -121,6 +189,7 @@ const error = ref('')
const adding = ref(false)
const addDialogVisible = ref(false)
const addFormRef = ref<any>(null)
const searchQuery = ref('')
// Add dialog model — reset on each open. Default role is contributor:
// inviting a fresh member with viewer is too restrictive for the
@@ -131,10 +200,21 @@ const addForm = reactive<{ email: string; role: TenantRole }>({
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')
// Role-aware gates. The server enforces every mutation; UI gates here
// are presentational only, matching the security note in stores/auth.ts.
const currentRole = computed<TenantRole | ''>(() => (authStore.currentTenantRole || '') as TenantRole | '')
const canManage = computed(() => currentRole.value === 'owner')
// Anyone except the last Owner can leave; we additionally hide the
// button for Owner-the-only-one because clicking would just bounce off
// the server's last-Owner check. The server is still the source of
// truth.
const canLeave = computed(() => {
if (!currentRole.value) return false
if (currentRole.value !== 'owner') return true
const owners = members.value.filter((m) => m.role === 'owner').length
return owners > 1
})
const currentUserId = computed(() => authStore.user?.id ?? '')
// Use the active tenant id from the auth store; the route only allows
// :id == active tenant (auth middleware enforces membership), so we
@@ -148,6 +228,57 @@ const roleOptions = computed(() => [
{ label: t('tenantMember.role.viewer'), value: 'viewer' },
])
// Static role-permissions matrix. The keys reference i18n strings under
// `tenantMember.permissions.*` so each locale can rephrase per culture.
// Keep this aligned with the design-doc §4.3 matrix and the actual
// PR 2 enforcement; if a permission moves between roles, update both
// sides in the same PR.
type RolePerm = { key: string; has: boolean }
const roleMatrixOrder: TenantRole[] = ['owner', 'admin', 'contributor', 'viewer']
const roleMatrix: Record<TenantRole, RolePerm[]> = {
owner: [
{ key: 'manageMembers', has: true },
{ key: 'manageTenantConfig', has: true },
{ key: 'manageInfra', has: true },
{ key: 'createOwnKB', has: true },
{ key: 'readAll', has: true },
],
admin: [
{ key: 'manageMembers', has: false },
{ key: 'manageTenantConfig', has: false },
{ key: 'manageInfra', has: true },
{ key: 'createOwnKB', has: true },
{ key: 'readAll', has: true },
],
contributor: [
{ key: 'manageMembers', has: false },
{ key: 'manageTenantConfig', has: false },
{ key: 'manageInfra', has: false },
{ key: 'createOwnKB', has: true },
{ key: 'readAll', has: true },
],
viewer: [
{ key: 'manageMembers', has: false },
{ key: 'manageTenantConfig', has: false },
{ key: 'manageInfra', has: false },
{ key: 'createOwnKB', has: false },
{ key: 'readAll', has: true },
],
}
function roleMatrixIcon(role: TenantRole): string {
switch (role) {
case 'owner':
return 'crown'
case 'admin':
return 'user-safety'
case 'contributor':
return 'edit'
default:
return 'browse'
}
}
const columns = computed(() => [
{ colKey: 'username', title: t('tenantMember.columns.username'), ellipsis: true },
{ colKey: 'email', title: t('tenantMember.columns.email'), ellipsis: true },
@@ -195,9 +326,26 @@ function formatDate(s: string | undefined): string {
}
}
// Client-side filter by username/email; case-insensitive substring
// match keeps the implementation tiny while covering the common
// "find this person quickly" use case. Server-side search is overkill
// for the expected per-tenant member counts.
const filteredMembers = computed(() => {
const q = searchQuery.value.trim().toLowerCase()
if (!q) return members.value
return members.value.filter((m) => {
return (
(m.username || '').toLowerCase().includes(q) ||
(m.email || '').toLowerCase().includes(q)
)
})
})
async function loadMembers() {
if (!activeTenantId.value) {
error.value = t('tenantMember.errors.noTenant')
// No active tenant yet — keep silent; the watch below will retry
// once the auth store finishes hydrating. Showing an error toast
// on cold-mount would flash on every refresh.
return
}
loading.value = true
@@ -224,8 +372,9 @@ function openAddDialog() {
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.
// errors on failure. Anything other than `true` => keep dialog open
// with the inline messages shown. The @confirm event lets us control
// visibility manually; :on-confirm would close on every return.
const valid = await addFormRef.value?.validate?.()
if (valid !== true) return
@@ -243,17 +392,18 @@ async function submitAdd() {
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
// The axios interceptor already flattens errors to
// { status, message, error?, ... }, so we read err.status directly
// — err.response.status is undefined here.
const status = err?.status
if (status === 404) {
MessagePlugin.error(t('tenantMember.errors.userNotFound'))
} else if (status === 409) {
MessagePlugin.error(t('tenantMember.errors.alreadyMember'))
} else if (status === 400) {
MessagePlugin.error(err?.message || t('tenantMember.errors.invalidRole'))
} else {
MessagePlugin.error(apiMsg || t('tenantMember.errors.generic'))
MessagePlugin.error(err?.message || t('tenantMember.errors.generic'))
}
} finally {
adding.value = false
@@ -274,20 +424,16 @@ async function onRoleChange(row: TenantMember, newRole: string) {
}
MessagePlugin.error(resp.message || t('tenantMember.errors.generic'))
} catch (err: any) {
const status = err?.response?.status
const status = err?.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'))
MessagePlugin.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)
// The t-select is bound via :model-value (one-way), so its rendered
// value stays at `prev` automatically — no DOM hack needed.
}
}
@@ -310,13 +456,13 @@ function confirmRemove(row: TenantMember) {
MessagePlugin.error(resp.message || t('tenantMember.errors.generic'))
}
} catch (err: any) {
const status = err?.response?.status
const status = err?.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'))
MessagePlugin.error(err?.message || t('tenantMember.errors.generic'))
}
} finally {
dlg.destroy()
@@ -326,8 +472,55 @@ function confirmRemove(row: TenantMember) {
})
}
function confirmLeaveTenant() {
const dlg = DialogPlugin.confirm({
header: t('tenantMember.leave.confirmTitle'),
body: t('tenantMember.leave.confirmBody'),
confirmBtn: { content: t('tenantMember.leave.confirm'), theme: 'danger' },
cancelBtn: t('common.cancel'),
onConfirm: async () => {
try {
const resp = await leaveTenant(activeTenantId.value)
if (resp.success) {
MessagePlugin.success(t('tenantMember.leave.success'))
// The user is now no longer a member of this tenant. Logging
// them out is the simplest correct behaviour; their next
// login will land them in whatever home tenant they have
// left, with PR 1's auto-promote covering the orphan case.
authStore.logout()
window.location.href = '/login'
} else {
MessagePlugin.error(resp.message || t('tenantMember.errors.generic'))
}
} catch (err: any) {
const status = err?.status
if (status === 409) {
MessagePlugin.error(t('tenantMember.errors.lastOwner'))
} else {
MessagePlugin.error(err?.message || t('tenantMember.errors.generic'))
}
} finally {
dlg.destroy()
}
},
onClose: () => dlg.destroy(),
})
}
// Re-load whenever the active tenant resolves (or changes via the
// tenant switcher). onMounted alone would race with auth-store
// hydration — currentTenantId is often 0 at the moment this component
// mounts on a cold reload.
watch(
activeTenantId,
(id) => {
if (id) loadMembers()
},
{ immediate: true },
)
onMounted(() => {
loadMembers()
if (activeTenantId.value) loadMembers()
})
</script>
@@ -352,16 +545,106 @@ onMounted(() => {
}
}
.permissions-compact {
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-border-level-1-color);
border-radius: 6px;
padding: 12px 14px;
margin-bottom: 20px;
.permissions-compact-header {
display: flex;
flex-direction: column;
gap: 2px;
margin-bottom: 10px;
.permissions-compact-title {
font-size: 13px;
font-weight: 600;
color: var(--td-text-color-primary);
}
.permissions-compact-desc {
font-size: 12px;
color: var(--td-text-color-secondary);
}
}
.permissions-compact-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
}
.perm-role-block {
border: 1px solid var(--td-border-level-1-color);
border-radius: 4px;
padding: 8px 10px;
background: var(--td-bg-color-container);
&.is-me {
border-color: var(--td-brand-color);
}
.perm-role-tag {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px;
font-weight: 600;
color: var(--td-text-color-primary);
margin-bottom: 6px;
.me-badge {
margin-left: auto;
font-size: 11px;
font-weight: 400;
color: var(--td-brand-color);
padding: 1px 6px;
background: var(--td-brand-color-light);
border-radius: 8px;
}
}
.perm-items {
display: flex;
flex-direction: column;
gap: 3px;
.perm-item {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px;
&.has {
color: var(--td-text-color-primary);
}
&.no {
color: var(--td-text-color-disabled);
text-decoration: line-through;
}
}
}
}
}
.action-bar {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
gap: 12px;
.count {
font-size: 13px;
color: var(--td-text-color-secondary);
}
.action-bar-right {
display: flex;
align-items: center;
gap: 8px;
}
}
.loading-inline,
@@ -371,4 +654,10 @@ onMounted(() => {
gap: 8px;
padding: 16px 0;
}
.empty-state {
padding: 40px 0;
display: flex;
justify-content: center;
}
</style>