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:
@@ -175,6 +175,29 @@ export async function getOIDCConfig(): Promise<OIDCConfigResponse> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取认证配置(仅返回前端渲染需要的公开字段,例如注册模式)。
|
||||
*
|
||||
* 后端通过 `auth.registration_mode` 控制是否允许自助注册:
|
||||
* - "self_serve" 保留现有自助注册入口(默认)
|
||||
* - "invite_only" 关闭注册,要求管理员邀请
|
||||
*
|
||||
* 失败时回落到 self_serve,避免接口异常导致注册入口直接消失。
|
||||
*/
|
||||
export interface AuthConfigResponse {
|
||||
success: boolean
|
||||
registration_mode: 'self_serve' | 'invite_only' | string
|
||||
}
|
||||
|
||||
export async function getAuthConfig(): Promise<AuthConfigResponse> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/config')
|
||||
return response as unknown as AuthConfigResponse
|
||||
} catch {
|
||||
return { success: false, registration_mode: 'self_serve' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户注册
|
||||
*/
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
{{ loading ? $t('auth.loggingIn') : $t('auth.login') }}
|
||||
</t-button>
|
||||
|
||||
<div class="form-footer login-form-footer">
|
||||
<div class="form-footer login-form-footer" v-if="registrationEnabled">
|
||||
<span>{{ $t('auth.noAccount') }}</span>
|
||||
<a href="#" @click.prevent="toggleMode" class="link-button">
|
||||
{{ $t('auth.registerNow') }}
|
||||
@@ -273,7 +273,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Register Card -->
|
||||
<div class="form-card" v-if="isRegisterMode">
|
||||
<div class="form-card" v-if="isRegisterMode && registrationEnabled">
|
||||
<div class="form-header">
|
||||
<h2 class="form-title">{{ $t('auth.createAccount') }}</h2>
|
||||
<p class="form-subtitle">{{ $t('auth.registerSubtitle') }}</p>
|
||||
@@ -377,7 +377,7 @@ import { Autoplay, EffectFade, Pagination } from 'swiper/modules'
|
||||
import 'swiper/css'
|
||||
import 'swiper/css/effect-fade'
|
||||
import 'swiper/css/pagination'
|
||||
import { login, register, getOIDCAuthorizationURL, getOIDCConfig, autoSetup } from '@/api/auth'
|
||||
import { login, register, getOIDCAuthorizationURL, getOIDCConfig, autoSetup, getAuthConfig } from '@/api/auth'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -423,6 +423,10 @@ const isRegisterMode = ref(false)
|
||||
const showLanguageMenu = ref(false)
|
||||
const oidcEnabled = ref(false)
|
||||
const oidcProviderName = ref('')
|
||||
// registrationEnabled defaults to true so that on first paint the Register
|
||||
// link is visible; the actual mode is fetched from /auth/config in onMounted.
|
||||
// In invite_only mode the link/card are hidden.
|
||||
const registrationEnabled = ref(true)
|
||||
|
||||
// Language options
|
||||
const languageOptions = [
|
||||
@@ -543,13 +547,18 @@ onBeforeUnmount(() => {
|
||||
})
|
||||
|
||||
const persistLoginResponse = async (response: any) => {
|
||||
if (response.user && response.tenant && response.token) {
|
||||
// Backend renamed `tenant` to `active_tenant` and added `memberships`
|
||||
// when tenant-level RBAC landed (issue #1303). The two are otherwise
|
||||
// identical — `active_tenant` is the tenant whose ID is encoded in the
|
||||
// JWT, defaulting to the user's home tenant on a fresh login.
|
||||
const activeTenant = response.active_tenant || response.tenant
|
||||
if (response.user && activeTenant && 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) || '',
|
||||
tenant_id: String(activeTenant.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()
|
||||
@@ -559,13 +568,16 @@ const persistLoginResponse = async (response: any) => {
|
||||
authStore.setRefreshToken(response.refresh_token)
|
||||
}
|
||||
authStore.setTenant({
|
||||
id: String(response.tenant.id) || '',
|
||||
name: response.tenant.name || '',
|
||||
api_key: response.tenant.api_key || '',
|
||||
id: String(activeTenant.id) || '',
|
||||
name: activeTenant.name || '',
|
||||
api_key: activeTenant.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()
|
||||
created_at: activeTenant.created_at || new Date().toISOString(),
|
||||
updated_at: activeTenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
if (Array.isArray(response.memberships)) {
|
||||
authStore.setMemberships(response.memberships)
|
||||
}
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
@@ -585,6 +597,18 @@ const loadOIDCConfig = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// loadAuthConfig fetches /auth/config and caches whether self-service
|
||||
// registration is allowed. Failures fall back to "enabled" so a transient
|
||||
// network glitch doesn't lock new users out of an open deployment.
|
||||
const loadAuthConfig = async () => {
|
||||
try {
|
||||
const response = await getAuthConfig()
|
||||
registrationEnabled.value = response.registration_mode !== 'invite_only'
|
||||
} catch {
|
||||
registrationEnabled.value = true
|
||||
}
|
||||
}
|
||||
|
||||
const handleOIDCLogin = async () => {
|
||||
try {
|
||||
oidcLoading.value = true
|
||||
@@ -692,6 +716,7 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
loadOIDCConfig()
|
||||
loadAuthConfig()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user