feat(rbac): add tenant_members schema and auth wiring (PR 1 of 3, #1303)

Lay the foundation for tenant-level RBAC without enforcing it yet.
Schema, types, middleware lookup, and login-flow shape changes ship now;
RequireRole/route annotations and member-management endpoints follow in
PR 2 and PR 3.

Highlights:
- New tenant_members table (Postgres + SQLite) with (user_id, tenant_id)
  unique key and (owner|admin|contributor|viewer) role values. Migration
  000043 backfills one row per existing user, marking the earliest-created
  active user in each tenant as Owner and the rest as Contributor.
- KnowledgeBase.creator_id and CustomAgent.runnable_by_viewer added so
  PR 2 can wire ownership-based and Viewer-runtime checks.
- Auth middleware loads the active TenantMember row, sets a new
  TenantRoleContextKey, and falls back via three escape hatches:
  cross-tenant superusers (CanAccessAllTenants) get Admin in the target
  tenant; orphan tenants (zero members) auto-promote the first authenticating
  human to Owner; and when tenant.enable_rbac is false (the v1 default)
  unmatched lookups fail open with Admin to preserve current behaviour.
- Register / OIDC provisioning now insert an Owner membership for the
  registrant via TenantMemberService.EnsureOwner.
- LoginResponse renamed tenant -> active_tenant and gained a memberships
  array. POST /auth/switch-tenant issues a fresh token pair scoped to a
  target membership; GET /auth/config exposes auth.registration_mode for
  the frontend register-tab gating.
- New config keys: auth.registration_mode (self_serve | invite_only,
  defaults to self_serve) and tenant.enable_rbac (defaults to false).
  Both have WEKNORA_* env overrides.
- Frontend store persists memberships and exposes currentTenantRole;
  Login.vue calls /auth/config and hides the Register tab in invite_only
  mode. Go SDK types updated to match the new LoginResponse shape.
This commit is contained in:
wizardchen
2026-05-13 19:47:48 +08:00
committed by lyingbug
parent 3214e3d952
commit 7f7a48880f
26 changed files with 1295 additions and 46 deletions
+41 -2
View File
@@ -27,6 +27,11 @@ export const useAuthStore = defineStore('auth', () => {
const selectedTenantId = ref<number | null>(null)
const selectedTenantName = ref<string | null>(null)
const allTenants = ref<TenantInfoFromAPI[]>([])
// memberships lists every tenant the user can authenticate into,
// along with their role in each. Populated from /auth/login response.
// v1 deployments will typically have length 1; the field is wired now
// so PR 3 can render a tenant-switcher UI without a store migration.
const memberships = ref<Array<{ tenant_id: number; tenant_name?: string; role: string }>>([])
const isLiteMode = ref(false)
// 计算属性
@@ -50,6 +55,17 @@ export const useAuthStore = defineStore('auth', () => {
return user.value?.can_access_all_tenants || false
})
// currentTenantRole returns the user's role in the active tenant
// (defaulting to '' when memberships have not been loaded). Used by
// role-aware UI gating; PR 2 wires backend enforcement, PR 3 uses
// this for menu/button visibility.
const currentTenantRole = computed(() => {
const tid = tenant.value?.id ? String(tenant.value.id) : ''
if (!tid) return ''
const match = memberships.value.find((m) => String(m.tenant_id) === tid)
return match?.role || ''
})
const effectiveTenantId = computed(() => {
// 如果选择了其他租户,使用选择的租户ID,否则使用用户默认租户ID
return selectedTenantId.value || (tenant.value?.id ? Number(tenant.value.id) : null)
@@ -115,6 +131,13 @@ export const useAuthStore = defineStore('auth', () => {
allTenants.value = tenants
}
const setMemberships = (
list: Array<{ tenant_id: number; tenant_name?: string; role: string }>
) => {
memberships.value = Array.isArray(list) ? list : []
localStorage.setItem('weknora_memberships', JSON.stringify(memberships.value))
}
const getSelectedTenant = () => {
return selectedTenantId.value
}
@@ -139,6 +162,7 @@ export const useAuthStore = defineStore('auth', () => {
selectedTenantId.value = null
selectedTenantName.value = null
allTenants.value = []
memberships.value = []
// 清空localStorage
localStorage.removeItem('weknora_user')
@@ -149,6 +173,7 @@ export const useAuthStore = defineStore('auth', () => {
localStorage.removeItem('weknora_current_kb')
localStorage.removeItem('weknora_selected_tenant_id')
localStorage.removeItem('weknora_selected_tenant_name')
localStorage.removeItem('weknora_memberships')
localStorage.removeItem('weknora_lite_mode')
isLiteMode.value = false
try {
@@ -225,6 +250,17 @@ export const useAuthStore = defineStore('auth', () => {
}
}
const storedMemberships = localStorage.getItem('weknora_memberships')
if (storedMemberships) {
try {
const parsed = JSON.parse(storedMemberships)
memberships.value = Array.isArray(parsed) ? parsed : []
} catch (e) {
console.error('Failed to parse memberships', e)
memberships.value = []
}
}
isLiteMode.value = localStorage.getItem('weknora_lite_mode') === 'true'
}
@@ -242,16 +278,18 @@ export const useAuthStore = defineStore('auth', () => {
selectedTenantId,
selectedTenantName,
allTenants,
memberships,
// 计算属性
isLoggedIn,
hasValidTenant,
currentTenantId,
currentUserId,
canAccessAllTenants,
currentTenantRole,
effectiveTenantId,
isLiteMode,
// 方法
setUser,
setTenant,
@@ -261,6 +299,7 @@ export const useAuthStore = defineStore('auth', () => {
setCurrentKnowledgeBase,
setSelectedTenant,
setAllTenants,
setMemberships,
getSelectedTenant,
setLiteMode,
logout,