feat(auth): support tenantless provisioning and gated self-service workspace creation
Allow deployments to register users without auto-creating a personal tenant, expose creation policy via /auth/me, and guide tenantless accounts through a workspace onboarding flow.
This commit is contained in:
@@ -142,6 +142,14 @@ TZ=Asia/Shanghai
|
||||
# 禁止新用户注册(生产环境建议设为 true)
|
||||
DISABLE_REGISTRATION=false
|
||||
|
||||
# 公开注册后的默认空间策略:create_personal(默认,自动创建个人空间)
|
||||
# 或 tenantless(仅创建账户,等待邀请或用户主动创建空间)。
|
||||
# WEKNORA_AUTH_DEFAULT_TENANT_MODE=create_personal
|
||||
|
||||
# 是否允许普通用户登录后主动创建空间。设为 false 时只能通过邀请加入已有空间,
|
||||
# 跨租户超管不受影响。默认 true。
|
||||
# WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED=true
|
||||
|
||||
# Ollama 服务的基准 URL,用于连接本地/其他服务器上运行的 Ollama 服务
|
||||
OLLAMA_BASE_URL=http://host.docker.internal:11434
|
||||
|
||||
@@ -708,6 +716,9 @@ DOCREADER_TRANSPORT=grpc
|
||||
|
||||
# OIDC_AUTH_SCOPES="openid profile email"
|
||||
|
||||
# OIDC 首次自动开户后的空间策略:create_personal(默认)或 tenantless。
|
||||
# OIDC_AUTH_DEFAULT_TENANT_MODE=create_personal
|
||||
|
||||
# 用于OIDC用于信息中提取用户数据
|
||||
# OIDC_USER_INFO_MAPPING_USER_NAME=name
|
||||
# OIDC_USER_INFO_MAPPING_EMAIL=email
|
||||
|
||||
@@ -73,6 +73,9 @@ services:
|
||||
- COS_ENABLE_OLD_DOMAIN=${COS_ENABLE_OLD_DOMAIN:-}
|
||||
- GIN_MODE=${GIN_MODE:-release}
|
||||
- DISABLE_REGISTRATION=${DISABLE_REGISTRATION:-false}
|
||||
- WEKNORA_AUTH_DEFAULT_TENANT_MODE=${WEKNORA_AUTH_DEFAULT_TENANT_MODE:-}
|
||||
- WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED=${WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED:-}
|
||||
- OIDC_AUTH_DEFAULT_TENANT_MODE=${OIDC_AUTH_DEFAULT_TENANT_MODE:-}
|
||||
- DB_DRIVER=${DB_DRIVER:-postgres}
|
||||
- DB_HOST=${DB_HOST:-postgres}
|
||||
- DB_PORT=${DB_PORT:-5432}
|
||||
|
||||
@@ -52,7 +52,7 @@ const syncOIDCUserContext = async () => {
|
||||
throw new Error(currentUserResponse.message || 'Failed to get user information')
|
||||
}
|
||||
|
||||
const { user, tenant, memberships } = currentUserResponse.data
|
||||
const { user, tenant, memberships, capabilities } = currentUserResponse.data
|
||||
authStore.setUser(userInfoFromApi(user, tenant?.id))
|
||||
if (tenant) {
|
||||
authStore.setTenant({
|
||||
@@ -67,6 +67,8 @@ const syncOIDCUserContext = async () => {
|
||||
created_at: tenant.created_at || new Date().toISOString(),
|
||||
updated_at: tenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
} else {
|
||||
authStore.setTenant(null)
|
||||
}
|
||||
// Refresh memberships so currentTenantRole reflects any role change
|
||||
// since the last login (e.g. an Owner demoted us to Viewer in a
|
||||
@@ -75,6 +77,9 @@ const syncOIDCUserContext = async () => {
|
||||
if (Array.isArray(memberships)) {
|
||||
authStore.setMemberships(memberships)
|
||||
}
|
||||
if (typeof capabilities?.can_create_tenant === 'boolean') {
|
||||
authStore.setCanCreateTenant(capabilities.can_create_tenant)
|
||||
}
|
||||
// Same active-vs-home reconciliation as Login.vue: if the OIDC login
|
||||
// landed us in a non-home tenant (because the backend honoured a
|
||||
// remembered last-active-tenant preference) make sure X-Tenant-ID
|
||||
@@ -101,7 +106,7 @@ const persistOIDCLoginResponse = async (response: any) => {
|
||||
await syncOIDCUserContext()
|
||||
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
}
|
||||
|
||||
const handleGlobalOIDCCallback = async () => {
|
||||
|
||||
@@ -34,7 +34,7 @@ export interface LoginResponse {
|
||||
storage_used: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
} | null
|
||||
// active_tenant mirrors `tenant` for endpoints that distinguish home
|
||||
// tenant from current tenant (e.g. /auth/register-by-invite). Only
|
||||
// one of `tenant` / `active_tenant` is populated by any given endpoint.
|
||||
@@ -48,7 +48,8 @@ export interface LoginResponse {
|
||||
storage_used?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
} | null
|
||||
memberships?: MembershipInfo[]
|
||||
token?: string
|
||||
refresh_token?: string
|
||||
}
|
||||
@@ -137,10 +138,11 @@ export function userInfoFromApi(
|
||||
u: any,
|
||||
fallbackTenantId?: string | number | null,
|
||||
): UserInfo {
|
||||
const tid =
|
||||
const rawTenantId =
|
||||
u?.tenant_id !== undefined && u?.tenant_id !== null && u.tenant_id !== ''
|
||||
? u.tenant_id
|
||||
: fallbackTenantId ?? ''
|
||||
const tid = Number(rawTenantId) > 0 ? rawTenantId : ''
|
||||
return {
|
||||
id: u?.id || '',
|
||||
username: u?.username || '',
|
||||
@@ -316,10 +318,14 @@ export interface MembershipInfo {
|
||||
/**
|
||||
* 获取当前用户信息
|
||||
*/
|
||||
export async function getCurrentUser(): Promise<{ success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[] }; message?: string }> {
|
||||
export interface AuthCapabilities {
|
||||
can_create_tenant: boolean
|
||||
}
|
||||
|
||||
export async function getCurrentUser(): Promise<{ success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[]; tenant_required?: boolean; capabilities?: AuthCapabilities }; message?: string }> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/me')
|
||||
return response as unknown as { success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[] }; message?: string }
|
||||
return response as unknown as { success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[]; tenant_required?: boolean; capabilities?: AuthCapabilities }; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
|
||||
@@ -284,9 +284,12 @@ export async function createTenant(
|
||||
const response = await post('/api/v1/tenants', payload)
|
||||
return response as unknown as { success: boolean; data?: TenantInfo; message?: string }
|
||||
} catch (error: any) {
|
||||
const code = error?.error?.code ?? error?.code
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.createFailed'),
|
||||
message: code === 2005
|
||||
? t('tenant.create.disabled')
|
||||
: (error.message || t('error.tenant.createFailed')),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,9 +53,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 自助创建新工作区入口:任意已登录用户可点击,后端会把当前用户
|
||||
写成新租户的 Owner(见 internal/handler/tenant.go CreateTenant)。 -->
|
||||
<div class="tenant-create-action" @click="openCreateDialog">
|
||||
<!-- 自助创建入口与 /auth/me 返回的后端能力保持一致。 -->
|
||||
<div v-if="authStore.canCreateTenant" class="tenant-create-action" @click="openCreateDialog">
|
||||
<t-icon name="add" class="tenant-create-icon" />
|
||||
<span class="tenant-create-label">{{ $t('tenant.create.action') }}</span>
|
||||
</div>
|
||||
@@ -276,6 +275,10 @@ const createDialogVisible = ref(false)
|
||||
|
||||
const openCreateDialog = () => {
|
||||
closeDropdown()
|
||||
if (!authStore.canCreateTenant) {
|
||||
MessagePlugin.info(t('tenant.create.disabled'))
|
||||
return
|
||||
}
|
||||
createDialogVisible.value = true
|
||||
}
|
||||
|
||||
|
||||
@@ -185,11 +185,8 @@
|
||||
{{ $t('tenant.switcher.empty') }}
|
||||
</div>
|
||||
</div>
|
||||
<!-- 自助创建新工作区入口:放在租户列表底部,所有能 hover 出这个
|
||||
子菜单的用户都能看到(包括单租户用户)。后端 router 已对
|
||||
POST /api/v1/tenants 去掉跨租户超管守卫,handler 内部会把
|
||||
当前用户 EnsureOwner 成新租户的 Owner。 -->
|
||||
<div class="tenant-submenu-create" @click="openCreateTenantDialog">
|
||||
<!-- 自助创建入口与 /auth/me 返回的后端能力保持一致。 -->
|
||||
<div v-if="authStore.canCreateTenant" class="tenant-submenu-create" @click="openCreateTenantDialog">
|
||||
<t-icon name="add" class="tenant-submenu-create-icon" />
|
||||
<span class="tenant-submenu-create-label">{{ $t('tenant.create.action') }}</span>
|
||||
</div>
|
||||
@@ -344,6 +341,10 @@ const createTenantDialogVisible = ref(false)
|
||||
|
||||
const openCreateTenantDialog = () => {
|
||||
closeAll()
|
||||
if (!authStore.canCreateTenant) {
|
||||
MessagePlugin.info(t('tenant.create.disabled'))
|
||||
return
|
||||
}
|
||||
createTenantDialogVisible.value = true
|
||||
}
|
||||
|
||||
@@ -569,6 +570,10 @@ const loadUserInfo = async () => {
|
||||
if (Array.isArray(membershipsSync)) {
|
||||
authStore.setMemberships(membershipsSync)
|
||||
}
|
||||
const canCreateTenant = response.data.capabilities?.can_create_tenant
|
||||
if (typeof canCreateTenant === 'boolean') {
|
||||
authStore.setCanCreateTenant(canCreateTenant)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load user info:', error)
|
||||
|
||||
@@ -1944,10 +1944,10 @@ export default {
|
||||
registerNow: 'Register Now',
|
||||
loginHint: 'Sign in to continue, or create an account below if this is your first time.',
|
||||
firstTime: 'New to WeKnora?',
|
||||
registerSuccess: 'Registration successful! The system has created an exclusive tenant for you, please login',
|
||||
registerSuccess: 'Registration successful. Please sign in',
|
||||
registerFailed: 'Registration failed',
|
||||
subtitle: 'RAG Q&A, ReAct Agent and Wiki — an LLM-powered enterprise knowledge framework',
|
||||
registerSubtitle: 'The system will create an exclusive tenant for you after registration',
|
||||
registerSubtitle: 'Create your account and start using WeKnora',
|
||||
emailPlaceholder: 'Enter email address',
|
||||
passwordPlaceholder: 'Enter password (8-32 characters, including letters and numbers)',
|
||||
confirmPasswordPlaceholder: 'Enter password again',
|
||||
@@ -1968,7 +1968,21 @@ export default {
|
||||
loginError: 'Login error, please check email or password',
|
||||
loginErrorRetry: 'Login error, please try again later',
|
||||
registerError: 'Registration error, please try again later',
|
||||
forgotPasswordNotAvailable: 'Password recovery function is temporarily unavailable, please contact administrator'
|
||||
forgotPasswordNotAvailable: 'Password recovery function is temporarily unavailable, please contact administrator',
|
||||
workspaceOnboarding: {
|
||||
title: 'Choose your workspace',
|
||||
description: 'Your account does not belong to a workspace yet. Create one or accept an invitation from an administrator.',
|
||||
create: 'Create workspace',
|
||||
invitations: 'View invitations',
|
||||
help: 'If no invitation is available, ask a system administrator to add you to an existing workspace.',
|
||||
loadingPolicy: 'Checking the available workspace options…',
|
||||
policyLoadFailed: 'Workspace permissions could not be loaded. Check your connection and try again.',
|
||||
retry: 'Reload',
|
||||
inviteOnlyTitle: 'Waiting for a workspace invitation',
|
||||
inviteOnlyDescription: 'Personal workspace creation is disabled. View and accept an invitation from a workspace administrator.',
|
||||
inviteOnlyNotice: 'This account can only join an existing workspace by invitation',
|
||||
inviteOnlyHelp: 'No invitation yet? Send your registered email address to a workspace administrator and ask them to invite you.',
|
||||
}
|
||||
},
|
||||
authStore: {
|
||||
errors: {
|
||||
@@ -3316,6 +3330,7 @@ export default {
|
||||
cancel: 'Cancel',
|
||||
success: 'Workspace created successfully',
|
||||
failed: 'Failed to create workspace',
|
||||
disabled: 'This system only allows joining workspaces by invitation. You cannot create one yourself.',
|
||||
},
|
||||
details: {
|
||||
idLabel: 'Tenant ID',
|
||||
@@ -3584,12 +3599,14 @@ export default {
|
||||
keyLabels: {
|
||||
auth: {
|
||||
registration_mode: 'Self-service registration mode',
|
||||
default_tenant_mode: 'Default workspace provisioning',
|
||||
},
|
||||
ssrf: {
|
||||
whitelist: 'SSRF protection allowlist',
|
||||
},
|
||||
tenant: {
|
||||
max_owned_per_user: 'Max tenants owned per user',
|
||||
self_service_creation_enabled: 'Allow self-service workspace creation',
|
||||
default_storage_quota_gb: 'Default storage quota for new tenants (GB)',
|
||||
},
|
||||
asynq: {
|
||||
@@ -3608,6 +3625,8 @@ export default {
|
||||
auth: {
|
||||
registration_mode:
|
||||
'Self-service registration mode. self_serve = anyone can register an account; invite_only = public registration is disabled and only Owners/Admins can invite. Takes effect immediately after saving, but use self_serve with care (the public internet will send spam sign-ups).',
|
||||
default_tenant_mode:
|
||||
'Workspace provisioning after public registration. create_personal creates an Owner workspace; tenantless creates only the account until the user accepts an invitation or creates a workspace. Applies to new users only.',
|
||||
},
|
||||
ssrf: {
|
||||
whitelist:
|
||||
@@ -3616,6 +3635,8 @@ export default {
|
||||
tenant: {
|
||||
max_owned_per_user:
|
||||
'Maximum number of tenants a non-superuser may own via self-service creation. Read on every tenant creation and takes effect immediately after saving. 0 uses the built-in default of 10; a negative value disables the cap entirely (not recommended on public deployments).',
|
||||
self_service_creation_enabled:
|
||||
'Whether non-superusers may create workspaces themselves. When disabled, regular users can only join existing workspaces by invitation; cross-tenant superusers remain exempt. Takes effect immediately.',
|
||||
default_storage_quota_gb:
|
||||
'Default storage quota (GB) assigned when a new tenant is created, covering vectors, originals, text, indexes, and related data. Read only at creation time — changes apply to newly created tenants only and do not retroactively update existing tenants. 0 or a negative value uses the built-in default of 10 GB.',
|
||||
},
|
||||
@@ -3639,6 +3660,10 @@ export default {
|
||||
self_serve: 'Self-service (anyone can register)',
|
||||
invite_only: 'Invite only (public registration disabled)',
|
||||
},
|
||||
default_tenant_mode: {
|
||||
create_personal: 'Create personal workspace',
|
||||
tenantless: 'Do not create a workspace',
|
||||
},
|
||||
},
|
||||
},
|
||||
confirm: {
|
||||
|
||||
@@ -1794,10 +1794,10 @@ export default {
|
||||
registerNow: "지금 가입하기",
|
||||
loginHint: "로그인하여 계속하세요. 처음이시라면 아래에서 계정을 만드세요.",
|
||||
firstTime: "WeKnora가 처음이신가요?",
|
||||
registerSuccess: "가입 성공! 시스템이 전용 테넌트를 생성했습니다. 로그인해주세요",
|
||||
registerSuccess: "가입이 완료되었습니다. 로그인해주세요",
|
||||
registerFailed: "가입 실패",
|
||||
subtitle: "RAG Q&A, ReAct 에이전트, Wiki 지식베이스 — 대규모 언어 모델 기반 엔터프라이즈 지식 프레임워크",
|
||||
registerSubtitle: "가입 후 시스템이 전용 테넌트를 생성합니다",
|
||||
registerSubtitle: "계정을 만들고 WeKnora를 시작하세요",
|
||||
emailPlaceholder: "이메일 주소 입력",
|
||||
passwordPlaceholder: "비밀번호 입력 (8-32자, 문자와 숫자 포함)",
|
||||
confirmPasswordPlaceholder: "비밀번호 다시 입력",
|
||||
@@ -1820,6 +1820,20 @@ export default {
|
||||
registerError: "가입 오류, 나중에 다시 시도해주세요",
|
||||
forgotPasswordNotAvailable:
|
||||
"비밀번호 찾기 기능을 현재 사용할 수 없습니다. 관리자에게 문의해주세요",
|
||||
workspaceOnboarding: {
|
||||
title: "작업 공간 선택",
|
||||
description: "아직 참여한 공간이 없습니다. 새 공간을 만들거나 관리자의 초대를 수락하세요.",
|
||||
create: "공간 만들기",
|
||||
invitations: "초대 보기",
|
||||
help: "사용 가능한 초대가 없다면 시스템 관리자에게 기존 공간 추가를 요청하세요.",
|
||||
loadingPolicy: "사용 가능한 공간 참여 방식을 확인하고 있습니다…",
|
||||
policyLoadFailed: "공간 권한을 불러올 수 없습니다. 네트워크를 확인한 후 다시 시도하세요.",
|
||||
retry: "다시 불러오기",
|
||||
inviteOnlyTitle: "작업 공간 초대 대기",
|
||||
inviteOnlyDescription: "개인 공간 만들기가 비활성화되어 있습니다. 관리자가 보낸 초대를 확인하고 수락하세요.",
|
||||
inviteOnlyNotice: "이 계정은 초대를 통해서만 기존 공간에 참여할 수 있습니다",
|
||||
inviteOnlyHelp: "초대가 없다면 등록 이메일을 공간 관리자에게 전달하고 초대를 요청하세요.",
|
||||
},
|
||||
},
|
||||
authStore: {
|
||||
errors: {
|
||||
@@ -2312,6 +2326,7 @@ export default {
|
||||
cancel: "취소",
|
||||
success: "워크스페이스가 생성되었습니다",
|
||||
failed: "워크스페이스 생성 실패",
|
||||
disabled: "현재 시스템에서는 초대를 통해서만 공간에 참여할 수 있으며 직접 만들 수 없습니다.",
|
||||
},
|
||||
details: {
|
||||
idLabel: "테넌트 ID",
|
||||
@@ -2569,12 +2584,14 @@ export default {
|
||||
keyLabels: {
|
||||
auth: {
|
||||
registration_mode: "셀프 가입 모드",
|
||||
default_tenant_mode: "기본 공간 프로비저닝",
|
||||
},
|
||||
ssrf: {
|
||||
whitelist: "SSRF 보호 허용 목록",
|
||||
},
|
||||
tenant: {
|
||||
max_owned_per_user: "사용자당 최대 테넌트 수",
|
||||
self_service_creation_enabled: "사용자 공간 직접 생성 허용",
|
||||
default_storage_quota_gb: "신규 테넌트 기본 저장 용량 (GB)",
|
||||
},
|
||||
asynq: {
|
||||
@@ -2593,6 +2610,8 @@ export default {
|
||||
auth: {
|
||||
registration_mode:
|
||||
"셀프 가입 모드입니다. self_serve = 누구나 계정을 만들 수 있음; invite_only = 공개 가입을 끄고 Owner/Admin만 초대 가능. 저장 즉시 적용되며, self_serve는 스팸 가입이 들어올 수 있으니 신중히 사용하세요.",
|
||||
default_tenant_mode:
|
||||
"공개 가입 후 공간 초기화 정책입니다. create_personal은 개인 공간을 만들고 Owner를 부여하며, tenantless는 초대 수락 또는 직접 공간 생성 전까지 계정만 만듭니다.",
|
||||
},
|
||||
ssrf: {
|
||||
whitelist:
|
||||
@@ -2601,6 +2620,8 @@ export default {
|
||||
tenant: {
|
||||
max_owned_per_user:
|
||||
"슈퍼유저가 아닌 사용자가 셀프 서비스로 소유할 수 있는 최대 테넌트 수입니다. 테넌트 생성 시마다 읽으며 저장 즉시 적용됩니다. 0은 내장 기본값 10을 사용하고, 음수는 제한을 완전히 해제합니다(공개 배포에는 권장하지 않음).",
|
||||
self_service_creation_enabled:
|
||||
"비슈퍼유저가 공간을 직접 만들 수 있는지 설정합니다. 비활성화하면 일반 사용자는 초대로만 기존 공간에 참여할 수 있으며, 크로스 테넌트 슈퍼유저는 계속 만들 수 있습니다.",
|
||||
default_storage_quota_gb:
|
||||
"신규 테넌트 생성 시 기본으로 할당되는 저장 용량(GB)으로, 벡터·원본·텍스트·인덱스 등을 포함합니다. 생성 시에만 읽으며, 변경은 이후 생성되는 테넌트에만 적용되고 기존 테넌트에는 소급되지 않습니다. 0 또는 음수는 내장 기본값 10GB를 사용합니다.",
|
||||
},
|
||||
@@ -2624,6 +2645,10 @@ export default {
|
||||
self_serve: "셀프 가입 (누구나 가입 가능)",
|
||||
invite_only: "초대 전용 (공개 가입 비활성)",
|
||||
},
|
||||
default_tenant_mode: {
|
||||
create_personal: "개인 공간 자동 생성",
|
||||
tenantless: "공간을 자동 생성하지 않음",
|
||||
},
|
||||
},
|
||||
},
|
||||
confirm: {
|
||||
|
||||
@@ -1814,10 +1814,10 @@ export default {
|
||||
registerNow: 'Зарегистрироваться',
|
||||
loginHint: 'Войдите, чтобы продолжить, или создайте аккаунт ниже, если вы впервые здесь.',
|
||||
firstTime: 'Впервые в WeKnora?',
|
||||
registerSuccess: 'Регистрация успешна! Система создала для вас эксклюзивного арендатора, пожалуйста, войдите',
|
||||
registerSuccess: 'Регистрация завершена. Войдите в систему',
|
||||
registerFailed: 'Ошибка регистрации',
|
||||
subtitle: 'RAG, ReAct-агент и Wiki — корпоративный фреймворк знаний на основе больших моделей',
|
||||
registerSubtitle: 'После регистрации система создаст для вас эксклюзивного арендатора',
|
||||
registerSubtitle: 'Создайте аккаунт и начните работу с WeKnora',
|
||||
emailPlaceholder: 'Введите адрес электронной почты',
|
||||
passwordPlaceholder: 'Введите пароль (8-32 символа, включая буквы и цифры)',
|
||||
confirmPasswordPlaceholder: 'Введите пароль ещё раз',
|
||||
@@ -1838,7 +1838,21 @@ export default {
|
||||
loginError: 'Ошибка входа, пожалуйста, проверьте электронную почту или пароль',
|
||||
loginErrorRetry: 'Ошибка входа, пожалуйста, повторите попытку позже',
|
||||
registerError: 'Ошибка регистрации, пожалуйста, повторите попытку позже',
|
||||
forgotPasswordNotAvailable: 'Функция восстановления пароля временно недоступна, пожалуйста, свяжитесь с администратором'
|
||||
forgotPasswordNotAvailable: 'Функция восстановления пароля временно недоступна, пожалуйста, свяжитесь с администратором',
|
||||
workspaceOnboarding: {
|
||||
title: 'Выберите рабочее пространство',
|
||||
description: 'Ваш аккаунт пока не состоит ни в одном пространстве. Создайте новое или примите приглашение администратора.',
|
||||
create: 'Создать пространство',
|
||||
invitations: 'Посмотреть приглашения',
|
||||
help: 'Если приглашений нет, попросите системного администратора добавить вас в существующее пространство.',
|
||||
loadingPolicy: 'Проверяем доступные способы присоединения…',
|
||||
policyLoadFailed: 'Не удалось загрузить разрешения пространства. Проверьте подключение и повторите попытку.',
|
||||
retry: 'Повторить',
|
||||
inviteOnlyTitle: 'Ожидание приглашения в пространство',
|
||||
inviteOnlyDescription: 'Создание личных пространств отключено. Просмотрите и примите приглашение администратора.',
|
||||
inviteOnlyNotice: 'Этот аккаунт может присоединиться к существующему пространству только по приглашению',
|
||||
inviteOnlyHelp: 'Нет приглашения? Сообщите администратору пространства свой регистрационный адрес электронной почты.',
|
||||
}
|
||||
},
|
||||
authStore: {
|
||||
errors: {
|
||||
@@ -2011,6 +2025,7 @@ export default {
|
||||
cancel: 'Отмена',
|
||||
success: 'Рабочее пространство создано',
|
||||
failed: 'Не удалось создать рабочее пространство',
|
||||
disabled: 'В этой системе присоединиться к пространству можно только по приглашению; создать его самостоятельно нельзя.',
|
||||
},
|
||||
details: {
|
||||
idLabel: 'ID арендатора',
|
||||
@@ -2267,12 +2282,14 @@ export default {
|
||||
keyLabels: {
|
||||
auth: {
|
||||
registration_mode: 'Режим самостоятельной регистрации',
|
||||
default_tenant_mode: 'Создание пространства по умолчанию',
|
||||
},
|
||||
ssrf: {
|
||||
whitelist: 'Белый список SSRF-защиты',
|
||||
},
|
||||
tenant: {
|
||||
max_owned_per_user: 'Максимум тенантов на пользователя',
|
||||
self_service_creation_enabled: 'Разрешить самостоятельное создание пространств',
|
||||
default_storage_quota_gb: 'Квота хранилища для новых тенантов по умолчанию (ГБ)',
|
||||
},
|
||||
asynq: {
|
||||
@@ -2291,6 +2308,8 @@ export default {
|
||||
auth: {
|
||||
registration_mode:
|
||||
'Режим самостоятельной регистрации. self_serve = любой может создать аккаунт; invite_only = открытая регистрация отключена, приглашать могут только Owner/Admin. Вступает в силу сразу после сохранения; используйте self_serve осторожно (в публичном интернете появятся спам-регистрации).',
|
||||
default_tenant_mode:
|
||||
'Политика пространства после открытой регистрации. create_personal создаёт личное пространство с ролью Owner; tenantless создаёт только аккаунт до принятия приглашения или самостоятельного создания пространства.',
|
||||
},
|
||||
ssrf: {
|
||||
whitelist:
|
||||
@@ -2299,6 +2318,8 @@ export default {
|
||||
tenant: {
|
||||
max_owned_per_user:
|
||||
'Максимальное число тенантов, которыми может владеть обычный (не супер) пользователь через самостоятельное создание. Читается при каждом создании тенанта и вступает в силу сразу после сохранения. 0 — встроенное значение по умолчанию 10; отрицательное значение полностью снимает ограничение (не рекомендуется для публичных развёртываний).',
|
||||
self_service_creation_enabled:
|
||||
'Разрешает обычным пользователям самостоятельно создавать пространства. Если отключено, они могут только присоединяться по приглашению; межтенантные суперпользователи не ограничены.',
|
||||
default_storage_quota_gb:
|
||||
'Квота хранилища по умолчанию (ГБ) для нового тенанта: векторы, оригиналы, текст, индексы и т.д. Читается только при создании — изменения применяются только к новым тенантам и не перезаписывают существующие. 0 или отрицательное значение — встроенное значение по умолчанию 10 ГБ.',
|
||||
},
|
||||
@@ -2322,6 +2343,10 @@ export default {
|
||||
self_serve: 'Самостоятельная (любой может зарегистрироваться)',
|
||||
invite_only: 'Только по приглашению (открытая регистрация отключена)',
|
||||
},
|
||||
default_tenant_mode: {
|
||||
create_personal: 'Создавать личное пространство',
|
||||
tenantless: 'Не создавать пространство',
|
||||
},
|
||||
},
|
||||
},
|
||||
confirm: {
|
||||
|
||||
@@ -1801,10 +1801,10 @@ export default {
|
||||
registerNow: "立即注册",
|
||||
loginHint: "登录以继续使用;首次使用请在下方创建账户。",
|
||||
firstTime: "首次使用 WeKnora?",
|
||||
registerSuccess: "注册成功!系统已为您创建专属空间,请登录",
|
||||
registerSuccess: "注册成功,请登录",
|
||||
registerFailed: "注册失败",
|
||||
subtitle: "RAG 问答、ReAct 智能体与 Wiki 知识库,大模型驱动的企业级知识框架",
|
||||
registerSubtitle: "注册后系统将为您创建专属空间",
|
||||
registerSubtitle: "创建账户并开始使用 WeKnora",
|
||||
emailPlaceholder: "输入邮箱地址",
|
||||
passwordPlaceholder: "输入密码(8-32个字符,包含字母和数字)",
|
||||
confirmPasswordPlaceholder: "再次输入密码",
|
||||
@@ -1826,6 +1826,20 @@ export default {
|
||||
loginErrorRetry: "登录错误,请稍后重试",
|
||||
registerError: "注册错误,请稍后重试",
|
||||
forgotPasswordNotAvailable: "密码找回功能暂不可用,请联系管理员",
|
||||
workspaceOnboarding: {
|
||||
title: "选择你的工作空间",
|
||||
description: "你的账户尚未加入任何空间。你可以创建一个新空间,或接受管理员发来的邀请。",
|
||||
create: "创建空间",
|
||||
invitations: "查看邀请",
|
||||
help: "如果这里没有可用邀请,请联系系统管理员将你加入现有空间。",
|
||||
loadingPolicy: "正在确认可用的空间加入方式…",
|
||||
policyLoadFailed: "暂时无法获取空间权限,请检查网络后重试。",
|
||||
retry: "重新加载",
|
||||
inviteOnlyTitle: "等待加入工作空间",
|
||||
inviteOnlyDescription: "当前系统不开放个人创建空间。你可以查看并接受管理员发来的空间邀请。",
|
||||
inviteOnlyNotice: "此账户只能通过邀请加入已有空间",
|
||||
inviteOnlyHelp: "还没有邀请?请把你的注册邮箱提供给空间管理员,由管理员向你发送邀请。",
|
||||
},
|
||||
},
|
||||
authStore: {
|
||||
errors: {
|
||||
@@ -2304,6 +2318,7 @@ export default {
|
||||
cancel: "取消",
|
||||
success: "空间创建成功",
|
||||
failed: "空间创建失败",
|
||||
disabled: "当前系统只允许通过邀请加入空间,不能自行创建空间。",
|
||||
},
|
||||
details: {
|
||||
idLabel: "空间 ID",
|
||||
@@ -2572,12 +2587,14 @@ export default {
|
||||
keyLabels: {
|
||||
auth: {
|
||||
registration_mode: "自助注册模式",
|
||||
default_tenant_mode: "注册默认空间策略",
|
||||
},
|
||||
ssrf: {
|
||||
whitelist: "SSRF 防护白名单",
|
||||
},
|
||||
tenant: {
|
||||
max_owned_per_user: "每用户最大租户数",
|
||||
self_service_creation_enabled: "允许用户自助创建空间",
|
||||
default_storage_quota_gb: "新租户默认存储配额 (GB)",
|
||||
},
|
||||
asynq: {
|
||||
@@ -2597,6 +2614,9 @@ export default {
|
||||
registration_mode:
|
||||
"自助注册模式。self_serve = 任何人可注册账号;invite_only = 关闭公网注册," +
|
||||
"仅 Owner/Admin 可邀请。修改后立即生效,但谨慎对待 self_serve(公网会接受 spam)。",
|
||||
default_tenant_mode:
|
||||
"公开注册后的空间初始化策略。create_personal 会自动创建个人空间并授予 Owner;" +
|
||||
"tenantless 仅创建账户,用户需要接受邀请或主动创建空间。只影响之后注册的用户。",
|
||||
},
|
||||
ssrf: {
|
||||
whitelist:
|
||||
@@ -2607,6 +2627,9 @@ export default {
|
||||
max_owned_per_user:
|
||||
"每个非超管用户通过自助创建可拥有的最大租户数。每次创建租户时实时读取," +
|
||||
"修改后立即生效。0 表示使用内置默认值 10;负数表示完全关闭限制(不建议在公开部署使用)。",
|
||||
self_service_creation_enabled:
|
||||
"是否允许非超管用户主动创建空间。关闭后,普通用户只能通过邀请加入已有空间;" +
|
||||
"跨租户超管仍可创建。修改后立即生效。",
|
||||
default_storage_quota_gb:
|
||||
"新建租户时默认分配的存储配额(GB),包含向量、原文、文本、索引等。" +
|
||||
"仅在创建时读取,修改后只对之后新建的租户生效,不会回写已存在的租户。" +
|
||||
@@ -2635,6 +2658,10 @@ export default {
|
||||
self_serve: "自助注册(任何人可注册)",
|
||||
invite_only: "仅邀请(关闭公网注册)",
|
||||
},
|
||||
default_tenant_mode: {
|
||||
create_personal: "自动创建个人空间",
|
||||
tenantless: "不自动创建空间",
|
||||
},
|
||||
},
|
||||
},
|
||||
confirm: {
|
||||
|
||||
@@ -63,6 +63,12 @@ const router = createRouter({
|
||||
component: () => import("../views/auth/Login.vue"),
|
||||
meta: { requiresAuth: false, requiresInit: false }
|
||||
},
|
||||
{
|
||||
path: "/onboarding/workspace",
|
||||
name: "workspaceOnboarding",
|
||||
component: () => import("../views/auth/WorkspaceOnboarding.vue"),
|
||||
meta: { requiresAuth: true, requiresInit: false, requiresTenant: false }
|
||||
},
|
||||
{
|
||||
path: "/join",
|
||||
name: "joinOrganization",
|
||||
@@ -256,6 +262,8 @@ async function hydrateSessionFromToken(authStore: ReturnType<typeof useAuthStore
|
||||
created_at: tenant.created_at || new Date().toISOString(),
|
||||
updated_at: tenant.updated_at || new Date().toISOString(),
|
||||
})
|
||||
} else {
|
||||
authStore.setTenant(null)
|
||||
}
|
||||
|
||||
// Refresh memberships on every page load — same reason as
|
||||
@@ -268,6 +276,11 @@ async function hydrateSessionFromToken(authStore: ReturnType<typeof useAuthStore
|
||||
authStore.setMemberships(memberships)
|
||||
}
|
||||
|
||||
const canCreateTenant = response.data?.capabilities?.can_create_tenant
|
||||
if (typeof canCreateTenant === 'boolean') {
|
||||
authStore.setCanCreateTenant(canCreateTenant)
|
||||
}
|
||||
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
@@ -302,11 +315,29 @@ router.beforeEach(async (to, from, next) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Tenantless onboarding still requires a valid user token even though it
|
||||
// deliberately skips the normal tenant/system-initialization gates.
|
||||
if (to.path === '/onboarding/workspace') {
|
||||
if (!authStore.isLoggedIn) {
|
||||
const restored = await hydrateSessionFromToken(authStore)
|
||||
if (!restored) {
|
||||
next('/login')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (authStore.hasValidTenant) {
|
||||
next('/platform/knowledge-bases')
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 如果访问的是登录页面或初始化页面,直接放行
|
||||
if (to.meta.requiresAuth === false || to.meta.requiresInit === false) {
|
||||
// 如果已登录用户访问登录页面,重定向到知识库列表页面
|
||||
if (to.path === '/login' && authStore.isLoggedIn) {
|
||||
next('/platform/knowledge-bases')
|
||||
next(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
return
|
||||
}
|
||||
next()
|
||||
@@ -318,7 +349,11 @@ router.beforeEach(async (to, from, next) => {
|
||||
if (!authStore.isLoggedIn) {
|
||||
const restored = await hydrateSessionFromToken(authStore)
|
||||
if (restored) {
|
||||
next(to.fullPath)
|
||||
next(
|
||||
!authStore.hasValidTenant && to.meta.requiresTenant !== false
|
||||
? '/onboarding/workspace'
|
||||
: to.fullPath,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -343,6 +378,11 @@ router.beforeEach(async (to, from, next) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (to.meta.requiresTenant !== false && !authStore.hasValidTenant) {
|
||||
next('/onboarding/workspace')
|
||||
return
|
||||
}
|
||||
|
||||
// SystemAdmin gate — checked AFTER auth so a non-admin who's logged
|
||||
// out gets redirected to /login first (consistent with how the rest
|
||||
// of the auth flow works), and only an authenticated non-admin sees
|
||||
|
||||
@@ -52,6 +52,9 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
// (vs SSE) is fine — the count is checked rarely and a 1-2 minute
|
||||
// staleness window is acceptable for an inbox indicator.
|
||||
const pendingInvitationCount = ref<number>(0)
|
||||
// Authoritative deployment capability returned by /auth/me. Defaults to
|
||||
// true for compatibility with older backends that do not return it yet.
|
||||
const canCreateTenant = ref(true)
|
||||
|
||||
// 计算属性
|
||||
const isLoggedIn = computed(() => {
|
||||
@@ -199,10 +202,14 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
}
|
||||
}
|
||||
|
||||
const setTenant = (tenantData: TenantInfo) => {
|
||||
const setTenant = (tenantData: TenantInfo | null) => {
|
||||
tenant.value = tenantData
|
||||
// 保存到localStorage
|
||||
localStorage.setItem('weknora_tenant', JSON.stringify(tenantData))
|
||||
if (tenantData) {
|
||||
localStorage.setItem('weknora_tenant', JSON.stringify(tenantData))
|
||||
} else {
|
||||
localStorage.removeItem('weknora_tenant')
|
||||
setSelectedTenant(null, null)
|
||||
}
|
||||
}
|
||||
|
||||
const setToken = (tokenValue: string) => {
|
||||
@@ -303,6 +310,10 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
pendingInvitationCount.value = Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0
|
||||
}
|
||||
|
||||
const setCanCreateTenant = (allowed: boolean) => {
|
||||
canCreateTenant.value = allowed
|
||||
}
|
||||
|
||||
// fetchPendingInvitationCount hits the dedicated /me/invitations/
|
||||
// pending-count endpoint and updates the store. Errors are
|
||||
// swallowed — the badge degrades to its last-known value instead
|
||||
@@ -351,6 +362,8 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
created_at: tenantSnapshot.created_at || new Date().toISOString(),
|
||||
updated_at: tenantSnapshot.updated_at || new Date().toISOString(),
|
||||
})
|
||||
} else {
|
||||
setTenant(null)
|
||||
}
|
||||
|
||||
const list = response.data?.memberships
|
||||
@@ -358,6 +371,11 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
setMemberships(list)
|
||||
}
|
||||
|
||||
const createCapability = response.data?.capabilities?.can_create_tenant
|
||||
if (typeof createCapability === 'boolean') {
|
||||
setCanCreateTenant(createCapability)
|
||||
}
|
||||
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
@@ -390,6 +408,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
allTenants.value = []
|
||||
memberships.value = []
|
||||
pendingInvitationCount.value = 0
|
||||
canCreateTenant.value = true
|
||||
clearSessionResourceCaches()
|
||||
|
||||
// 清空localStorage
|
||||
@@ -512,6 +531,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
allTenants,
|
||||
memberships,
|
||||
pendingInvitationCount,
|
||||
canCreateTenant,
|
||||
|
||||
// 计算属性
|
||||
isLoggedIn,
|
||||
@@ -537,6 +557,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
setAllTenants,
|
||||
setMemberships,
|
||||
setPendingInvitationCount,
|
||||
setCanCreateTenant,
|
||||
fetchPendingInvitationCount,
|
||||
refreshFromAuthMe,
|
||||
getSelectedTenant,
|
||||
|
||||
@@ -24,8 +24,8 @@ interface LoginResponseLike {
|
||||
// Password-login response uses `active_tenant`; the OIDC callback
|
||||
// response uses `tenant` (legacy backward-compat name on the Go side).
|
||||
// Accept either so callers don't have to normalise.
|
||||
active_tenant?: { id?: number | string; name?: string }
|
||||
tenant?: { id?: number | string; name?: string }
|
||||
active_tenant?: { id?: number | string; name?: string } | null
|
||||
tenant?: { id?: number | string; name?: string } | null
|
||||
memberships?: Array<{ tenant_id?: number | string; role?: string }>
|
||||
}
|
||||
|
||||
|
||||
@@ -538,25 +538,29 @@ const persistLoginResponse = async (response: any) => {
|
||||
// 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) {
|
||||
if (response.user && response.token) {
|
||||
// user.tenant_id must be the user's HOME tenant (the immutable row
|
||||
// on the users table); useHomeTenant() and the home-badge logic both
|
||||
// assume so. The ACTIVE tenant (which can differ from home when the
|
||||
// server honoured a remembered last-active-tenant preference) is
|
||||
// expressed separately via setSelectedTenant below.
|
||||
const homeTenantIdRaw = response.user.tenant_id ?? activeTenant.id
|
||||
const homeTenantIdRaw = response.user.tenant_id ?? activeTenant?.id ?? ''
|
||||
authStore.setUser(userInfoFromApi(response.user, homeTenantIdRaw))
|
||||
authStore.setToken(response.token)
|
||||
if (response.refresh_token) {
|
||||
authStore.setRefreshToken(response.refresh_token)
|
||||
}
|
||||
authStore.setTenant({
|
||||
id: String(activeTenant.id) || '',
|
||||
name: activeTenant.name || '',
|
||||
owner_id: response.user.id || '',
|
||||
created_at: activeTenant.created_at || new Date().toISOString(),
|
||||
updated_at: activeTenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
if (activeTenant) {
|
||||
authStore.setTenant({
|
||||
id: String(activeTenant.id) || '',
|
||||
name: activeTenant.name || '',
|
||||
owner_id: response.user.id || '',
|
||||
created_at: activeTenant.created_at || new Date().toISOString(),
|
||||
updated_at: activeTenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
} else {
|
||||
authStore.setTenant(null)
|
||||
}
|
||||
if (Array.isArray(response.memberships)) {
|
||||
authStore.setMemberships(response.memberships)
|
||||
}
|
||||
@@ -565,17 +569,21 @@ const persistLoginResponse = async (response: any) => {
|
||||
// subsequent requests carry X-Tenant-ID and the UI stays consistent.
|
||||
// Otherwise clear any stale override left in localStorage by a
|
||||
// previous session for a different account.
|
||||
const activeIdNum = Number(activeTenant.id)
|
||||
const activeIdNum = Number(activeTenant?.id)
|
||||
const homeIdNum = Number(homeTenantIdRaw)
|
||||
if (Number.isFinite(activeIdNum) && Number.isFinite(homeIdNum) && activeIdNum !== homeIdNum) {
|
||||
authStore.setSelectedTenant(activeIdNum, activeTenant.name || null)
|
||||
authStore.setSelectedTenant(activeIdNum, activeTenant?.name || null)
|
||||
} else {
|
||||
authStore.setSelectedTenant(null, null)
|
||||
}
|
||||
}
|
||||
|
||||
// Pull runtime capabilities (including whether ordinary users may create
|
||||
// workspaces) before entering the main UI so create actions never flash
|
||||
// briefly when the deployment is invitation-only.
|
||||
await authStore.refreshFromAuthMe()
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
router.replace(authStore.hasValidTenant ? '/platform/knowledge-bases' : '/onboarding/workspace')
|
||||
}
|
||||
|
||||
const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback`
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
<template>
|
||||
<main class="workspace-onboarding">
|
||||
<section class="workspace-card">
|
||||
<div class="workspace-mark" aria-hidden="true">
|
||||
<t-icon name="system-sum" size="30px" />
|
||||
</div>
|
||||
<h1>
|
||||
{{
|
||||
$t(
|
||||
authStore.canCreateTenant
|
||||
? 'auth.workspaceOnboarding.title'
|
||||
: 'auth.workspaceOnboarding.inviteOnlyTitle',
|
||||
)
|
||||
}}
|
||||
</h1>
|
||||
<p class="workspace-description">
|
||||
{{
|
||||
$t(
|
||||
authStore.canCreateTenant
|
||||
? 'auth.workspaceOnboarding.description'
|
||||
: 'auth.workspaceOnboarding.inviteOnlyDescription',
|
||||
)
|
||||
}}
|
||||
</p>
|
||||
|
||||
<div v-if="policyLoading" class="policy-loading">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('auth.workspaceOnboarding.loadingPolicy') }}</span>
|
||||
</div>
|
||||
<div v-else-if="policyLoadFailed" class="policy-error" role="alert">
|
||||
<t-icon name="error-circle" size="20px" aria-hidden="true" />
|
||||
<span>{{ $t('auth.workspaceOnboarding.policyLoadFailed') }}</span>
|
||||
<t-button size="small" variant="text" @click="loadPolicy">
|
||||
{{ $t('auth.workspaceOnboarding.retry') }}
|
||||
</t-button>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<div v-if="!authStore.canCreateTenant" class="invite-only-notice">
|
||||
<t-icon name="lock-on" size="20px" aria-hidden="true" />
|
||||
<span>{{ $t('auth.workspaceOnboarding.inviteOnlyNotice') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="workspace-actions" :class="{ 'workspace-actions--single': !authStore.canCreateTenant }">
|
||||
<t-button v-if="authStore.canCreateTenant" theme="primary" size="large" @click="createVisible = true">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('auth.workspaceOnboarding.create') }}
|
||||
</t-button>
|
||||
<t-button
|
||||
:theme="authStore.canCreateTenant ? 'default' : 'primary'"
|
||||
:variant="authStore.canCreateTenant ? 'outline' : 'base'"
|
||||
size="large"
|
||||
@click="invitationsVisible = true"
|
||||
>
|
||||
<template #icon><t-icon name="mail" /></template>
|
||||
{{ $t('auth.workspaceOnboarding.invitations') }}
|
||||
<template v-if="authStore.pendingInvitationCount > 0">
|
||||
({{ authStore.pendingInvitationCount }})
|
||||
</template>
|
||||
</t-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<p v-if="!policyLoading && !policyLoadFailed" class="workspace-help">
|
||||
{{
|
||||
$t(
|
||||
authStore.canCreateTenant
|
||||
? 'auth.workspaceOnboarding.help'
|
||||
: 'auth.workspaceOnboarding.inviteOnlyHelp',
|
||||
)
|
||||
}}
|
||||
</p>
|
||||
<button class="logout-link" type="button" @click="handleLogout">
|
||||
{{ $t('auth.logout') }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<CreateTenantDialog v-model:visible="createVisible" @created="onTenantCreated" />
|
||||
<MyInvitationsDialog v-model:visible="invitationsVisible" />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
|
||||
import MyInvitationsDialog from '@/components/MyInvitationsDialog.vue'
|
||||
import { logout as logoutApi } from '@/api/auth'
|
||||
import type { TenantInfo } from '@/api/tenant'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
const createVisible = ref(false)
|
||||
const invitationsVisible = ref(false)
|
||||
const policyLoading = ref(true)
|
||||
const policyLoadFailed = ref(false)
|
||||
|
||||
async function loadPolicy() {
|
||||
policyLoading.value = true
|
||||
policyLoadFailed.value = false
|
||||
try {
|
||||
const refreshed = await authStore.refreshFromAuthMe()
|
||||
if (!refreshed) {
|
||||
policyLoadFailed.value = true
|
||||
return
|
||||
}
|
||||
await authStore.fetchPendingInvitationCount()
|
||||
} finally {
|
||||
policyLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadPolicy()
|
||||
})
|
||||
|
||||
watch(
|
||||
() => authStore.hasValidTenant,
|
||||
(ready) => {
|
||||
if (ready) router.replace('/platform/knowledge-bases')
|
||||
},
|
||||
)
|
||||
|
||||
async function onTenantCreated(tenant: TenantInfo) {
|
||||
await authStore.refreshFromAuthMe()
|
||||
authStore.setSelectedTenant(tenant.id, tenant.name)
|
||||
await router.replace('/platform/knowledge-bases')
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
await logoutApi()
|
||||
authStore.logout()
|
||||
await router.replace('/login')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.workspace-onboarding {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 32px 20px;
|
||||
background:
|
||||
radial-gradient(circle at 20% 10%, color-mix(in srgb, var(--td-brand-color) 12%, transparent), transparent 38%),
|
||||
var(--td-bg-color-page);
|
||||
}
|
||||
|
||||
.workspace-card {
|
||||
width: min(520px, 100%);
|
||||
padding: 44px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 20px;
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: var(--td-shadow-2);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.workspace-mark {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
margin: 0 auto 22px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 18px;
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-brand-color-light);
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: 26px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.workspace-description,
|
||||
.workspace-help {
|
||||
color: var(--td-text-color-secondary);
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.workspace-description {
|
||||
margin: 14px 0 28px;
|
||||
}
|
||||
|
||||
.workspace-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.workspace-actions--single {
|
||||
grid-template-columns: minmax(220px, 1fr);
|
||||
}
|
||||
|
||||
.policy-loading,
|
||||
.invite-only-notice,
|
||||
.policy-error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
min-height: 52px;
|
||||
margin-bottom: 18px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.policy-error {
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 16px;
|
||||
border-radius: 10px;
|
||||
color: var(--td-error-color);
|
||||
background: var(--td-error-color-light);
|
||||
}
|
||||
|
||||
.invite-only-notice {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 10px;
|
||||
color: var(--td-text-color-primary);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.invite-only-notice :deep(.t-icon) {
|
||||
flex: 0 0 auto;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.workspace-help {
|
||||
margin: 24px 0 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.logout-link {
|
||||
border: 0;
|
||||
padding: 6px 10px;
|
||||
color: var(--td-text-color-secondary);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.logout-link:hover {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.workspace-card {
|
||||
padding: 32px 22px;
|
||||
}
|
||||
|
||||
.workspace-actions {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -31,6 +31,14 @@ func NewUserRepository(db *gorm.DB) interfaces.UserRepository {
|
||||
|
||||
// CreateUser creates a user
|
||||
func (r *userRepository) CreateUser(ctx context.Context, user *types.User) error {
|
||||
// users.tenant_id is nullable in both PostgreSQL and SQLite. GORM would
|
||||
// otherwise serialise the uint64 zero value as 0, which violates the
|
||||
// PostgreSQL FK and loses the distinction between "not provisioned yet"
|
||||
// and a real tenant. Omitting the column stores SQL NULL; reads hydrate it
|
||||
// back as zero, the domain sentinel used by tenantless auth flows.
|
||||
if user != nil && user.TenantID == 0 {
|
||||
return r.db.WithContext(ctx).Omit("tenant_id").Create(user).Error
|
||||
}
|
||||
return r.db.WithContext(ctx).Create(user).Error
|
||||
}
|
||||
|
||||
@@ -104,6 +112,19 @@ func (r *userRepository) GetUserByTenantID(ctx context.Context, tenantID uint64)
|
||||
|
||||
// UpdateUser updates a user
|
||||
func (r *userRepository) UpdateUser(ctx context.Context, user *types.User) error {
|
||||
if user != nil && user.TenantID == 0 {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// Preserve Save's all-fields behaviour while keeping the nullable
|
||||
// tenant column out of the struct write, then explicitly store NULL.
|
||||
// Writing uint64(0) would violate the PostgreSQL tenant FK.
|
||||
if err := tx.Omit("tenant_id").Save(user).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&types.User{}).
|
||||
Where("id = ?", user.ID).
|
||||
UpdateColumn("tenant_id", nil).Error
|
||||
})
|
||||
}
|
||||
return r.db.WithContext(ctx).Save(user).Error
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestUserRepositoryTenantlessCreateAndUpdateKeepNullTenantID(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:user_tenantless?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&types.Tenant{}, &types.User{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
|
||||
repo := NewUserRepository(db)
|
||||
user := &types.User{
|
||||
ID: "tenantless-user",
|
||||
Username: "before-update",
|
||||
Email: "tenantless@example.com",
|
||||
PasswordHash: "hashed",
|
||||
TenantID: 0,
|
||||
IsActive: true,
|
||||
}
|
||||
if err := repo.CreateUser(context.Background(), user); err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
assertNullTenantID(t, db, user.ID)
|
||||
|
||||
user.Username = "after-update"
|
||||
if err := repo.UpdateUser(context.Background(), user); err != nil {
|
||||
t.Fatalf("UpdateUser: %v", err)
|
||||
}
|
||||
assertNullTenantID(t, db, user.ID)
|
||||
|
||||
var stored types.User
|
||||
if err := db.First(&stored, "id = ?", user.ID).Error; err != nil {
|
||||
t.Fatalf("reload user: %v", err)
|
||||
}
|
||||
if stored.Username != "after-update" || stored.TenantID != 0 {
|
||||
t.Fatalf("stored user = %#v", stored)
|
||||
}
|
||||
}
|
||||
|
||||
func assertNullTenantID(t *testing.T, db *gorm.DB, userID string) {
|
||||
t.Helper()
|
||||
var count int64
|
||||
if err := db.Table("users").Where("id = ? AND tenant_id IS NULL", userID).Count(&count).Error; err != nil {
|
||||
t.Fatalf("check tenant_id: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("tenant_id for user %s is not NULL", userID)
|
||||
}
|
||||
}
|
||||
@@ -135,6 +135,15 @@ var registry = map[string]settingSpec{
|
||||
Description: "自助注册模式。self_serve = 任何人可注册账号;invite_only = 关闭公网注册," +
|
||||
"仅 Owner/Admin 可邀请。修改后立即生效,但谨慎对待 self_serve(公网会接受 spam)。",
|
||||
},
|
||||
"auth.default_tenant_mode": {
|
||||
Type: "string",
|
||||
EnvName: "WEKNORA_AUTH_DEFAULT_TENANT_MODE",
|
||||
Default: "create_personal",
|
||||
Enum: []string{"create_personal", "tenantless"},
|
||||
Category: "auth",
|
||||
Description: "公开注册成功后的默认租户策略。create_personal = 自动创建个人租户并设为 Owner;" +
|
||||
"tenantless = 仅创建用户,等待接受邀请或主动创建租户。修改后只影响新注册用户。",
|
||||
},
|
||||
// tenant.max_owned_per_user caps how many tenants a single non-superuser
|
||||
// can create (and Own) via self-service POST /tenants. Read on every
|
||||
// request — UI edits take effect immediately, no restart required. The
|
||||
@@ -150,6 +159,14 @@ var registry = map[string]settingSpec{
|
||||
Description: "每个非超管用户通过自助创建可拥有的最大租户数。每次创建租户时实时读取," +
|
||||
"修改后立即生效。0 表示使用内置默认值 10;负数表示完全关闭限制(不建议在公开部署使用)。",
|
||||
},
|
||||
"tenant.self_service_creation_enabled": {
|
||||
Type: "bool",
|
||||
EnvName: "WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED",
|
||||
Default: true,
|
||||
Category: "tenant",
|
||||
Description: "是否允许非超管用户主动创建租户。关闭后,普通用户只能通过邀请加入已有租户;" +
|
||||
"跨租户超管仍可创建。修改后立即生效。",
|
||||
},
|
||||
// tenant.default_storage_quota_gb is the default storage quota (in GB)
|
||||
// applied to a newly-created tenant when the caller doesn't specify
|
||||
// one explicitly. Read at create time only — changing the value does
|
||||
|
||||
@@ -103,18 +103,29 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
|
||||
return nil, errors.New("failed to process password")
|
||||
}
|
||||
|
||||
// Create default tenant for the user
|
||||
// Note: RetrieverEngines is left empty - system will use defaults from RETRIEVE_DRIVER env
|
||||
tenant := &types.Tenant{
|
||||
Name: fmt.Sprintf("%s's Workspace", secutils.SanitizeForLog(req.Username)),
|
||||
Description: "Default workspace",
|
||||
Status: "active",
|
||||
provisioning := req.TenantProvisioning
|
||||
if provisioning == "" {
|
||||
provisioning = types.TenantProvisioningCreatePersonal
|
||||
}
|
||||
if !provisioning.IsValid() {
|
||||
return nil, fmt.Errorf("invalid tenant provisioning mode %q", provisioning)
|
||||
}
|
||||
|
||||
createdTenant, err := s.tenantService.CreateTenant(ctx, tenant)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create tenant")
|
||||
return nil, errors.New("failed to create workspace")
|
||||
var createdTenant *types.Tenant
|
||||
if provisioning == types.TenantProvisioningCreatePersonal {
|
||||
// Note: RetrieverEngines is left empty - system will use defaults
|
||||
// from RETRIEVE_DRIVER env.
|
||||
tenant := &types.Tenant{
|
||||
Name: fmt.Sprintf("%s's Workspace", secutils.SanitizeForLog(req.Username)),
|
||||
Description: "Default workspace",
|
||||
Status: "active",
|
||||
}
|
||||
|
||||
createdTenant, err = s.tenantService.CreateTenant(ctx, tenant)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create tenant")
|
||||
return nil, errors.New("failed to create workspace")
|
||||
}
|
||||
}
|
||||
|
||||
// Create user
|
||||
@@ -123,15 +134,23 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
|
||||
Username: req.Username,
|
||||
Email: req.Email,
|
||||
PasswordHash: string(hashedPassword),
|
||||
TenantID: createdTenant.ID,
|
||||
TenantID: 0,
|
||||
IsActive: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if createdTenant != nil {
|
||||
user.TenantID = createdTenant.ID
|
||||
}
|
||||
|
||||
err = s.userRepo.CreateUser(ctx, user)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create user: %v", err)
|
||||
if createdTenant != nil {
|
||||
if rollbackErr := s.tenantService.DeleteTenant(ctx, createdTenant.ID); rollbackErr != nil {
|
||||
logger.Errorf(ctx, "Failed to roll back tenant %d after user creation failure: %v", createdTenant.ID, rollbackErr)
|
||||
}
|
||||
}
|
||||
return nil, errors.New("failed to create user")
|
||||
}
|
||||
|
||||
@@ -139,10 +158,13 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
|
||||
// the tenant their account just created. Failure here only logs — the
|
||||
// user record exists and the auth middleware's orphan-tenant recovery
|
||||
// path will recreate the membership on next login.
|
||||
if s.memberService != nil {
|
||||
if createdTenant != nil && s.memberService != nil {
|
||||
if _, err := s.memberService.EnsureOwner(ctx, user.ID, createdTenant.ID); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create owner membership for user %s tenant %d: %v",
|
||||
user.ID, createdTenant.ID, err)
|
||||
_ = s.userRepo.DeleteUser(ctx, user.ID)
|
||||
_ = s.tenantService.DeleteTenant(ctx, createdTenant.ID)
|
||||
return nil, errors.New("failed to finalise workspace ownership")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,12 +228,16 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type
|
||||
}
|
||||
logger.Info(ctx, "Tokens generated successfully")
|
||||
|
||||
// Get tenant information
|
||||
tenant, err := s.tenantService.GetTenantByID(ctx, resolvedTenantID)
|
||||
if err != nil {
|
||||
logger.Warn(ctx, "Failed to get tenant info")
|
||||
} else {
|
||||
logger.Info(ctx, "Tenant information retrieved successfully")
|
||||
// Get tenant information. A zero resolved ID is a valid tenantless
|
||||
// identity, not a failed tenant lookup.
|
||||
var tenant *types.Tenant
|
||||
if resolvedTenantID > 0 {
|
||||
tenant, err = s.tenantService.GetTenantByID(ctx, resolvedTenantID)
|
||||
if err != nil {
|
||||
logger.Warn(ctx, "Failed to get tenant info")
|
||||
} else {
|
||||
logger.Info(ctx, "Tenant information retrieved successfully")
|
||||
}
|
||||
}
|
||||
|
||||
memberships := s.buildMembershipsForUser(ctx, user, tenant)
|
||||
@@ -625,7 +651,9 @@ func (s *userService) GenerateTokens(
|
||||
// freshly minted access token. The contract:
|
||||
//
|
||||
// 1. If the user has no LastActiveTenantID preference set (or it points
|
||||
// at home), return home — the historical behaviour.
|
||||
// at home), return home — the historical behaviour. A tenantless user
|
||||
// with an active membership adopts their earliest membership instead;
|
||||
// this repairs partial invitation/admin-assignment flows.
|
||||
// 2. Otherwise validate the preference: the tenant must still exist and
|
||||
// the user must still have an active membership (or be a cross-tenant
|
||||
// superuser). Validation failure logs a warning, best-effort clears
|
||||
@@ -641,6 +669,9 @@ func (s *userService) resolveLoginTenantID(ctx context.Context, user *types.User
|
||||
}
|
||||
pref := user.Preferences.LastActiveTenantID
|
||||
if pref == nil || *pref == 0 || *pref == user.TenantID {
|
||||
if user.TenantID == 0 {
|
||||
return s.resolveFirstMembershipTenant(ctx, user)
|
||||
}
|
||||
return user.TenantID
|
||||
}
|
||||
preferred := *pref
|
||||
@@ -680,6 +711,46 @@ func (s *userService) resolveLoginTenantID(ctx context.Context, user *types.User
|
||||
return preferred
|
||||
}
|
||||
|
||||
// resolveFirstMembershipTenant makes a tenantless identity usable when an
|
||||
// active membership already exists (for example, an invitation was accepted
|
||||
// but persisting the default tenant failed). ListByUser is stably ordered by
|
||||
// join time, so the earliest valid membership is deterministic. Persisting it
|
||||
// as home is best-effort: even if the repair write fails, the freshly issued
|
||||
// token can still be scoped to the membership and the next login retries.
|
||||
func (s *userService) resolveFirstMembershipTenant(ctx context.Context, user *types.User) uint64 {
|
||||
if user == nil || s.memberService == nil {
|
||||
return 0
|
||||
}
|
||||
members, err := s.memberService.ListByUser(ctx, user.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "resolveLoginTenantID: failed to list memberships for tenantless user %s: %v", user.ID, err)
|
||||
return 0
|
||||
}
|
||||
for _, member := range members {
|
||||
if member == nil || member.TenantID == 0 || member.Status != types.TenantMemberStatusActive {
|
||||
continue
|
||||
}
|
||||
if s.tenantService != nil {
|
||||
if _, err := s.tenantService.GetTenantByID(ctx, member.TenantID); err != nil {
|
||||
logger.Warnf(ctx, "resolveLoginTenantID: tenant %d for tenantless user %s is unavailable: %v",
|
||||
member.TenantID, user.ID, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
user.TenantID = member.TenantID
|
||||
if s.userRepo != nil {
|
||||
if err := s.userRepo.UpdateUser(ctx, user); err != nil {
|
||||
logger.Warnf(ctx, "resolveLoginTenantID: failed to persist tenant %d for tenantless user %s: %v",
|
||||
member.TenantID, user.ID, err)
|
||||
user.TenantID = 0
|
||||
}
|
||||
}
|
||||
return member.TenantID
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// clearLastActiveTenantPreference is the best-effort cleanup half of
|
||||
// resolveLoginTenantID. Failures here are logged but never propagated:
|
||||
// the in-memory user already has the preference cleared for this login,
|
||||
@@ -1261,10 +1332,17 @@ func (s *userService) provisionOIDCUser(ctx context.Context, info *types.OIDCUse
|
||||
return nil, fmt.Errorf("failed to generate password for OIDC user: %w", err)
|
||||
}
|
||||
|
||||
provisioning := types.TenantProvisioningCreatePersonal
|
||||
if s.config != nil && s.config.OIDCAuth != nil &&
|
||||
strings.TrimSpace(s.config.OIDCAuth.DefaultTenantMode) == config.AuthDefaultTenantModeTenantless {
|
||||
provisioning = types.TenantProvisioningTenantless
|
||||
}
|
||||
|
||||
user, err := s.Register(ctx, &types.RegisterRequest{
|
||||
Username: username,
|
||||
Email: info.Email,
|
||||
Password: randomPassword,
|
||||
Username: username,
|
||||
Email: info.Email,
|
||||
Password: randomPassword,
|
||||
TenantProvisioning: provisioning,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to auto-provision OIDC user: %w", err)
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
type provisioningUserRepo struct {
|
||||
interfaces.UserRepository
|
||||
created *types.User
|
||||
updatedTenant uint64
|
||||
}
|
||||
|
||||
func (r *provisioningUserRepo) GetUserByEmail(context.Context, string) (*types.User, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *provisioningUserRepo) GetUserByUsername(context.Context, string) (*types.User, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *provisioningUserRepo) CreateUser(_ context.Context, user *types.User) error {
|
||||
copy := *user
|
||||
r.created = ©
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *provisioningUserRepo) UpdateUser(_ context.Context, user *types.User) error {
|
||||
r.updatedTenant = user.TenantID
|
||||
return nil
|
||||
}
|
||||
|
||||
type provisioningTenantService struct {
|
||||
interfaces.TenantService
|
||||
createCalls int
|
||||
}
|
||||
|
||||
func (s *provisioningTenantService) CreateTenant(context.Context, *types.Tenant) (*types.Tenant, error) {
|
||||
s.createCalls++
|
||||
return &types.Tenant{ID: 99}, nil
|
||||
}
|
||||
|
||||
func (s *provisioningTenantService) GetTenantByID(_ context.Context, id uint64) (*types.Tenant, error) {
|
||||
return &types.Tenant{ID: id}, nil
|
||||
}
|
||||
|
||||
type provisioningMemberService struct {
|
||||
interfaces.TenantMemberService
|
||||
members []*types.TenantMember
|
||||
}
|
||||
|
||||
func (s *provisioningMemberService) ListByUser(context.Context, string) ([]*types.TenantMember, error) {
|
||||
return s.members, nil
|
||||
}
|
||||
|
||||
func TestUserServiceRegisterTenantlessSkipsTenantCreation(t *testing.T) {
|
||||
repo := &provisioningUserRepo{}
|
||||
tenantSvc := &provisioningTenantService{}
|
||||
svc := &userService{userRepo: repo, tenantService: tenantSvc}
|
||||
|
||||
user, err := svc.Register(context.Background(), &types.RegisterRequest{
|
||||
Username: "alice",
|
||||
Email: "alice@example.com",
|
||||
Password: "supersecret",
|
||||
TenantProvisioning: types.TenantProvisioningTenantless,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Register: %v", err)
|
||||
}
|
||||
if tenantSvc.createCalls != 0 {
|
||||
t.Fatalf("tenant create calls = %d, want 0", tenantSvc.createCalls)
|
||||
}
|
||||
if user.TenantID != 0 || repo.created == nil || repo.created.TenantID != 0 {
|
||||
t.Fatalf("tenantless user persisted with tenant: user=%d created=%v", user.TenantID, repo.created)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveLoginTenantIDRepairsTenantlessUserWithMembership(t *testing.T) {
|
||||
repo := &provisioningUserRepo{}
|
||||
tenantSvc := &provisioningTenantService{}
|
||||
memberSvc := &provisioningMemberService{members: []*types.TenantMember{
|
||||
{TenantID: 42, Status: types.TenantMemberStatusActive},
|
||||
}}
|
||||
svc := &userService{userRepo: repo, tenantService: tenantSvc, memberService: memberSvc}
|
||||
user := &types.User{ID: "alice", TenantID: 0}
|
||||
|
||||
if got := svc.resolveLoginTenantID(context.Background(), user); got != 42 {
|
||||
t.Fatalf("resolved tenant = %d, want 42", got)
|
||||
}
|
||||
if repo.updatedTenant != 42 || user.TenantID != 42 {
|
||||
t.Fatalf("repair was not persisted: repo=%d user=%d", repo.updatedTenant, user.TenantID)
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ func TestApplyAuthAndTenantDefaults_DisableRegistrationDrivesRegistrationMode(t
|
||||
// Other tenant env vars must not leak between cases.
|
||||
t.Setenv("WEKNORA_TENANT_ENABLE_RBAC", "")
|
||||
t.Setenv("WEKNORA_TENANT_MAX_OWNED_PER_USER", "")
|
||||
t.Setenv("WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED", "")
|
||||
|
||||
cfg := &Config{Auth: &AuthConfig{RegistrationMode: tc.cfgMode}}
|
||||
applyAuthAndTenantDefaults(cfg)
|
||||
@@ -41,3 +42,63 @@ func TestApplyAuthAndTenantDefaults_DisableRegistrationDrivesRegistrationMode(t
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyAuthAndTenantDefaults_SelfServiceTenantCreation(t *testing.T) {
|
||||
t.Run("defaults enabled", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED", "")
|
||||
cfg := &Config{Tenant: &TenantConfig{}}
|
||||
|
||||
applyAuthAndTenantDefaults(cfg)
|
||||
|
||||
if !cfg.Tenant.IsSelfServiceCreationEnabled() {
|
||||
t.Fatal("self-service tenant creation should default to enabled")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("environment disables yaml default", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED", "false")
|
||||
on := true
|
||||
cfg := &Config{Tenant: &TenantConfig{SelfServiceCreationEnabled: &on}}
|
||||
|
||||
applyAuthAndTenantDefaults(cfg)
|
||||
|
||||
if cfg.Tenant.IsSelfServiceCreationEnabled() {
|
||||
t.Fatal("environment override should disable self-service tenant creation")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyAuthAndTenantDefaults_DefaultTenantMode(t *testing.T) {
|
||||
t.Run("historical default creates a personal tenant", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_AUTH_DEFAULT_TENANT_MODE", "")
|
||||
cfg := &Config{Auth: &AuthConfig{}}
|
||||
|
||||
applyAuthAndTenantDefaults(cfg)
|
||||
|
||||
if cfg.Auth.DefaultTenantMode != AuthDefaultTenantModeCreatePersonal {
|
||||
t.Fatalf("default_tenant_mode = %q, want %q", cfg.Auth.DefaultTenantMode, AuthDefaultTenantModeCreatePersonal)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("environment overrides yaml", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_AUTH_DEFAULT_TENANT_MODE", AuthDefaultTenantModeTenantless)
|
||||
cfg := &Config{Auth: &AuthConfig{DefaultTenantMode: AuthDefaultTenantModeCreatePersonal}}
|
||||
|
||||
applyAuthAndTenantDefaults(cfg)
|
||||
|
||||
if cfg.Auth.DefaultTenantMode != AuthDefaultTenantModeTenantless {
|
||||
t.Fatalf("default_tenant_mode = %q, want %q", cfg.Auth.DefaultTenantMode, AuthDefaultTenantModeTenantless)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid environment value fails validation", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_AUTH_DEFAULT_TENANT_MODE", "create_magic")
|
||||
cfg := &Config{Auth: &AuthConfig{}}
|
||||
|
||||
applyAuthAndTenantDefaults(cfg)
|
||||
|
||||
if err := ValidateConfig(cfg); err == nil {
|
||||
t.Fatal("ValidateConfig unexpectedly accepted an invalid default tenant mode")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -226,6 +226,10 @@ type TenantConfig struct {
|
||||
// loosen / tighten the quota without a redeploy. See
|
||||
// applyAuthAndTenantDefaults for the semantics of <0 / 0 / >0.
|
||||
MaxOwnedPerUser int `yaml:"max_owned_per_user" json:"max_owned_per_user" mapstructure:"max_owned_per_user"`
|
||||
// SelfServiceCreationEnabled controls whether ordinary authenticated
|
||||
// users may create a workspace for themselves. Nil preserves the
|
||||
// historical default (enabled); cross-tenant superusers are exempt.
|
||||
SelfServiceCreationEnabled *bool `yaml:"self_service_creation_enabled" json:"self_service_creation_enabled" mapstructure:"self_service_creation_enabled"`
|
||||
}
|
||||
|
||||
// IsRBACEnforced reports whether tenant-level role enforcement is
|
||||
@@ -241,6 +245,12 @@ func (t *TenantConfig) IsRBACEnforced() bool {
|
||||
return *t.EnableRBAC
|
||||
}
|
||||
|
||||
// IsSelfServiceCreationEnabled reports whether ordinary users may create
|
||||
// tenants. Nil keeps the historical behaviour enabled.
|
||||
func (t *TenantConfig) IsSelfServiceCreationEnabled() bool {
|
||||
return t == nil || t.SelfServiceCreationEnabled == nil || *t.SelfServiceCreationEnabled
|
||||
}
|
||||
|
||||
// AuditConfig governs durable audit log behaviour. Writes happen on
|
||||
// every member-management mutation and on RBAC denials (when
|
||||
// EnableRBAC is true); the table grows monotonically unless this
|
||||
@@ -265,12 +275,19 @@ type AuthConfig struct {
|
||||
// users only enter through the invitation
|
||||
// flow added in PR 3.
|
||||
RegistrationMode string `yaml:"registration_mode" json:"registration_mode"`
|
||||
// DefaultTenantMode controls public password-registration provisioning.
|
||||
// create_personal preserves the historical one-user-one-workspace default;
|
||||
// tenantless creates only the identity and waits for an invitation or an
|
||||
// explicit self-service tenant creation.
|
||||
DefaultTenantMode string `yaml:"default_tenant_mode" json:"default_tenant_mode"`
|
||||
}
|
||||
|
||||
// AuthRegistrationMode constants used by handlers and middleware.
|
||||
const (
|
||||
AuthRegistrationModeSelfServe = "self_serve"
|
||||
AuthRegistrationModeInviteOnly = "invite_only"
|
||||
AuthRegistrationModeSelfServe = "self_serve"
|
||||
AuthRegistrationModeInviteOnly = "invite_only"
|
||||
AuthDefaultTenantModeCreatePersonal = "create_personal"
|
||||
AuthDefaultTenantModeTenantless = "tenantless"
|
||||
)
|
||||
|
||||
// IsInviteOnly returns true when registration is gated behind invitations.
|
||||
@@ -301,6 +318,9 @@ type OIDCAuthConfig struct {
|
||||
UserInfoEndpoint string `yaml:"user_info_endpoint" json:"user_info_endpoint"`
|
||||
Scopes []string `yaml:"scopes" json:"scopes"`
|
||||
UserInfoMapping *OIDCUserInfoMapping `yaml:"user_info_mapping" json:"user_info_mapping"`
|
||||
// DefaultTenantMode applies only when OIDC auto-provisions a new local
|
||||
// user. Existing users keep their current home tenant/memberships.
|
||||
DefaultTenantMode string `yaml:"default_tenant_mode" json:"default_tenant_mode"`
|
||||
}
|
||||
|
||||
// PromptTemplateI18n holds localized name and description for a prompt template.
|
||||
@@ -607,6 +627,11 @@ func ValidateConfig(cfg *Config) error {
|
||||
(strings.TrimSpace(cfg.OIDCAuth.AuthorizationEndpoint) == "" || strings.TrimSpace(cfg.OIDCAuth.TokenEndpoint) == "") {
|
||||
errs = append(errs, "oidc_auth.discovery_url or both oidc_auth.authorization_endpoint and oidc_auth.token_endpoint are required when OIDC is enabled")
|
||||
}
|
||||
tenantMode := strings.TrimSpace(cfg.OIDCAuth.DefaultTenantMode)
|
||||
if tenantMode != "" && tenantMode != AuthDefaultTenantModeCreatePersonal && tenantMode != AuthDefaultTenantModeTenantless {
|
||||
errs = append(errs, fmt.Sprintf("oidc_auth.default_tenant_mode must be %q or %q, got %q",
|
||||
AuthDefaultTenantModeCreatePersonal, AuthDefaultTenantModeTenantless, tenantMode))
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Auth != nil {
|
||||
@@ -615,6 +640,11 @@ func ValidateConfig(cfg *Config) error {
|
||||
errs = append(errs, fmt.Sprintf("auth.registration_mode must be %q or %q, got %q",
|
||||
AuthRegistrationModeSelfServe, AuthRegistrationModeInviteOnly, mode))
|
||||
}
|
||||
tenantMode := strings.TrimSpace(cfg.Auth.DefaultTenantMode)
|
||||
if tenantMode != "" && tenantMode != AuthDefaultTenantModeCreatePersonal && tenantMode != AuthDefaultTenantModeTenantless {
|
||||
errs = append(errs, fmt.Sprintf("auth.default_tenant_mode must be %q or %q, got %q",
|
||||
AuthDefaultTenantModeCreatePersonal, AuthDefaultTenantModeTenantless, tenantMode))
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Audit != nil && cfg.Audit.RetentionDays < 0 {
|
||||
@@ -699,6 +729,9 @@ func applyOIDCEnvOverrides(cfg *Config) {
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_SCOPES")); value != "" {
|
||||
cfg.OIDCAuth.Scopes = strings.Fields(strings.ReplaceAll(value, ",", " "))
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_AUTH_DEFAULT_TENANT_MODE")); value != "" {
|
||||
cfg.OIDCAuth.DefaultTenantMode = value
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("OIDC_USER_INFO_MAPPING_USER_NAME")); value != "" {
|
||||
cfg.OIDCAuth.UserInfoMapping.Username = value
|
||||
}
|
||||
@@ -709,6 +742,9 @@ func applyOIDCEnvOverrides(cfg *Config) {
|
||||
if cfg.OIDCAuth.ProviderDisplayName == "" {
|
||||
cfg.OIDCAuth.ProviderDisplayName = "OIDC"
|
||||
}
|
||||
if strings.TrimSpace(cfg.OIDCAuth.DefaultTenantMode) == "" {
|
||||
cfg.OIDCAuth.DefaultTenantMode = AuthDefaultTenantModeCreatePersonal
|
||||
}
|
||||
if len(cfg.OIDCAuth.Scopes) == 0 {
|
||||
cfg.OIDCAuth.Scopes = []string{"openid", "profile", "email"}
|
||||
}
|
||||
@@ -774,11 +810,17 @@ func applyAgentEnvOverrides(cfg *Config) {
|
||||
//
|
||||
// Defaults:
|
||||
// - auth.registration_mode -> "self_serve" (preserves pre-RBAC behaviour)
|
||||
// - auth.default_tenant_mode -> "create_personal" (preserves the
|
||||
// historical registration behaviour)
|
||||
// - tenant.enable_rbac -> true (enforce role checks unless an
|
||||
// operator explicitly opts into the logging-only rollout window via
|
||||
// config.yaml `enable_rbac: false` or `WEKNORA_TENANT_ENABLE_RBAC=false`).
|
||||
// - tenant.self_service_creation_enabled -> true (preserves ordinary
|
||||
// authenticated users' ability to create workspaces).
|
||||
//
|
||||
// Env overrides (when set and non-empty):
|
||||
// - WEKNORA_AUTH_DEFAULT_TENANT_MODE ("create_personal"/"tenantless")
|
||||
// - WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED (boolean)
|
||||
// - WEKNORA_TENANT_ENABLE_RBAC ("true"/"false", case-insensitive)
|
||||
// - WEKNORA_TENANT_MAX_OWNED_PER_USER (integer; <0 disables the cap,
|
||||
// 0 falls back to the handler default, >0 enforces that exact cap).
|
||||
@@ -813,6 +855,12 @@ func applyAuthAndTenantDefaults(cfg *Config) {
|
||||
if strings.TrimSpace(cfg.Auth.RegistrationMode) == "" {
|
||||
cfg.Auth.RegistrationMode = AuthRegistrationModeSelfServe
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv("WEKNORA_AUTH_DEFAULT_TENANT_MODE")); value != "" {
|
||||
cfg.Auth.DefaultTenantMode = value
|
||||
}
|
||||
if strings.TrimSpace(cfg.Auth.DefaultTenantMode) == "" {
|
||||
cfg.Auth.DefaultTenantMode = AuthDefaultTenantModeCreatePersonal
|
||||
}
|
||||
|
||||
if value := strings.TrimSpace(os.Getenv("WEKNORA_TENANT_ENABLE_RBAC")); value != "" {
|
||||
v := strings.EqualFold(value, "true")
|
||||
@@ -825,6 +873,21 @@ func applyAuthAndTenantDefaults(cfg *Config) {
|
||||
cfg.Tenant.EnableRBAC = &on
|
||||
}
|
||||
|
||||
if value := strings.TrimSpace(os.Getenv("WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED")); value != "" {
|
||||
if enabled, err := strconv.ParseBool(value); err == nil {
|
||||
cfg.Tenant.SelfServiceCreationEnabled = &enabled
|
||||
} else {
|
||||
fmt.Printf(
|
||||
"[config] WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED=%q is not a boolean, ignoring\n",
|
||||
value,
|
||||
)
|
||||
}
|
||||
}
|
||||
if cfg.Tenant.SelfServiceCreationEnabled == nil {
|
||||
on := true
|
||||
cfg.Tenant.SelfServiceCreationEnabled = &on
|
||||
}
|
||||
|
||||
if value := strings.TrimSpace(os.Getenv("WEKNORA_TENANT_MAX_OWNED_PER_USER")); value != "" {
|
||||
if n, err := strconv.Atoi(value); err == nil {
|
||||
cfg.Tenant.MaxOwnedPerUser = n
|
||||
|
||||
@@ -24,11 +24,12 @@ const (
|
||||
ErrValidation ErrorCode = 1010
|
||||
|
||||
// Tenant related error codes (2000-2099)
|
||||
ErrTenantNotFound ErrorCode = 2000
|
||||
ErrTenantAlreadyExists ErrorCode = 2001
|
||||
ErrTenantInactive ErrorCode = 2002
|
||||
ErrTenantNameRequired ErrorCode = 2003
|
||||
ErrTenantInvalidStatus ErrorCode = 2004
|
||||
ErrTenantNotFound ErrorCode = 2000
|
||||
ErrTenantAlreadyExists ErrorCode = 2001
|
||||
ErrTenantInactive ErrorCode = 2002
|
||||
ErrTenantNameRequired ErrorCode = 2003
|
||||
ErrTenantInvalidStatus ErrorCode = 2004
|
||||
ErrTenantCreationDisabled ErrorCode = 2005
|
||||
|
||||
// Agent related error codes (2100-2199)
|
||||
ErrAgentMissingThinkingModel ErrorCode = 2100
|
||||
@@ -184,6 +185,16 @@ func NewTenantInactiveError() *AppError {
|
||||
}
|
||||
}
|
||||
|
||||
// NewTenantCreationDisabledError reports a deployment-policy denial for
|
||||
// ordinary self-service tenant creation.
|
||||
func NewTenantCreationDisabledError() *AppError {
|
||||
return &AppError{
|
||||
Code: ErrTenantCreationDisabled,
|
||||
Message: "self-service tenant creation is disabled; join a workspace by invitation",
|
||||
HTTPCode: http.StatusForbidden,
|
||||
}
|
||||
}
|
||||
|
||||
// Agent related errors
|
||||
func NewAgentMissingThinkingModelError() *AppError {
|
||||
return &AppError{
|
||||
|
||||
@@ -101,6 +101,31 @@ func (h *AuthHandler) resolveRegistrationMode(ctx context.Context) string {
|
||||
return h.systemSettingSvc.GetString(ctx, "auth.registration_mode", "", def)
|
||||
}
|
||||
|
||||
// resolveDefaultTenantMode returns the provisioning policy for ordinary
|
||||
// public password registrations. Invitation registration never uses this
|
||||
// value: the invitation itself supplies the target tenant.
|
||||
func (h *AuthHandler) resolveDefaultTenantMode(ctx context.Context) types.TenantProvisioningMode {
|
||||
def := config.AuthDefaultTenantModeCreatePersonal
|
||||
if h.configInfo != nil && h.configInfo.Auth != nil {
|
||||
if mode := strings.TrimSpace(h.configInfo.Auth.DefaultTenantMode); mode != "" {
|
||||
def = mode
|
||||
}
|
||||
}
|
||||
mode := def
|
||||
if h.systemSettingSvc != nil {
|
||||
mode = h.systemSettingSvc.GetString(
|
||||
ctx,
|
||||
"auth.default_tenant_mode",
|
||||
"WEKNORA_AUTH_DEFAULT_TENANT_MODE",
|
||||
def,
|
||||
)
|
||||
}
|
||||
if mode == config.AuthDefaultTenantModeTenantless {
|
||||
return types.TenantProvisioningTenantless
|
||||
}
|
||||
return types.TenantProvisioningCreatePersonal
|
||||
}
|
||||
|
||||
// Register godoc
|
||||
// @Summary 用户注册
|
||||
// @Description 注册新用户账号
|
||||
@@ -150,6 +175,7 @@ func (h *AuthHandler) Register(c *gin.Context) {
|
||||
}
|
||||
req.Username = secutils.SanitizeForLog(req.Username)
|
||||
req.Email = secutils.SanitizeForLog(req.Email)
|
||||
req.TenantProvisioning = h.resolveDefaultTenantMode(ctx)
|
||||
// Call service to register user
|
||||
user, err := h.userService.Register(ctx, &req)
|
||||
if err != nil {
|
||||
@@ -536,12 +562,18 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
|
||||
// 同步返回当前用户的 memberships,让前端在页面刷新(仅命中 /auth/me)
|
||||
// 后也能恢复 currentTenantRole,避免角色信息只在 login 那一刻可用。
|
||||
memberships := h.userService.BuildLoginMemberships(ctx, user, tenant)
|
||||
canCreateTenant := user.CanAccessAllTenants ||
|
||||
resolveTenantSelfServiceCreationEnabled(ctx, h.configInfo, h.systemSettingSvc)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"user": userInfo,
|
||||
"tenant": dto.NewTenantResponse(ctx, tenant),
|
||||
"memberships": memberships,
|
||||
"user": userInfo,
|
||||
"tenant": dto.NewTenantResponse(ctx, tenant),
|
||||
"memberships": memberships,
|
||||
"tenant_required": tenant == nil,
|
||||
"capabilities": gin.H{
|
||||
"can_create_tenant": canCreateTenant,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -170,9 +170,10 @@ func (h *AuthHandler) RegisterByInvite(c *gin.Context) {
|
||||
}
|
||||
|
||||
user, err := h.userService.Register(ctx, &types.RegisterRequest{
|
||||
Username: req.Username,
|
||||
Email: req.Email,
|
||||
Password: req.Password,
|
||||
Username: req.Username,
|
||||
Email: req.Email,
|
||||
Password: req.Password,
|
||||
TenantProvisioning: types.TenantProvisioningTenantless,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "register-by-invite: user create failed for %s: %v",
|
||||
@@ -181,10 +182,26 @@ func (h *AuthHandler) RegisterByInvite(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// The invited tenant becomes the user's initial/default tenant. No
|
||||
user.TenantID = inv.TenantID
|
||||
if err := h.userService.UpdateUser(ctx, user); err != nil {
|
||||
logger.Errorf(ctx, "register-by-invite: failed to set home tenant for user %s: %v", user.ID, err)
|
||||
_ = h.userService.DeleteUser(ctx, user.ID)
|
||||
c.Error(apperrors.NewInternalServerError("failed to finalise invited account").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.invitationSvc.AcceptByToken(ctx, req.Token, user.ID); err != nil {
|
||||
// Race: link was revoked between Lookup and Accept. The user
|
||||
// account is created either way — they can still log in.
|
||||
// Race: link was revoked between Lookup and Accept. Keep the new
|
||||
// account, but restore it to tenantless so it does not point at a
|
||||
// tenant for which no membership was created. If even that repair
|
||||
// fails, remove the half-provisioned identity.
|
||||
logger.Errorf(ctx, "register-by-invite: accept failed for user %s: %v", user.ID, err)
|
||||
user.TenantID = 0
|
||||
if rollbackErr := h.userService.UpdateUser(ctx, user); rollbackErr != nil {
|
||||
logger.Errorf(ctx, "register-by-invite: failed to restore tenantless user %s: %v", user.ID, rollbackErr)
|
||||
_ = h.userService.DeleteUser(ctx, user.ID)
|
||||
}
|
||||
c.Error(&apperrors.AppError{
|
||||
Code: apperrors.ErrNotFound,
|
||||
Message: "invitation link is no longer valid; please log in to your new account",
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type invitedRegistrationUserService struct {
|
||||
interfaces.UserService
|
||||
registeredMode types.TenantProvisioningMode
|
||||
updatedTenant uint64
|
||||
updateCalls []uint64
|
||||
}
|
||||
|
||||
func (s *invitedRegistrationUserService) GetUserByEmail(context.Context, string) (*types.User, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *invitedRegistrationUserService) Register(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
|
||||
s.registeredMode = req.TenantProvisioning
|
||||
return &types.User{ID: "new-user", Username: req.Username, Email: req.Email, IsActive: true}, nil
|
||||
}
|
||||
|
||||
func (s *invitedRegistrationUserService) UpdateUser(_ context.Context, user *types.User) error {
|
||||
s.updatedTenant = user.TenantID
|
||||
s.updateCalls = append(s.updateCalls, user.TenantID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *invitedRegistrationUserService) GenerateTokens(context.Context, *types.User) (string, string, error) {
|
||||
return "access", "refresh", nil
|
||||
}
|
||||
|
||||
type invitedRegistrationInvitationService struct {
|
||||
interfaces.TenantInvitationService
|
||||
acceptErr error
|
||||
}
|
||||
|
||||
func (s *invitedRegistrationInvitationService) LookupByToken(context.Context, string) (*types.TenantInvitation, error) {
|
||||
return &types.TenantInvitation{TenantID: 42, Role: types.TenantRoleViewer}, nil
|
||||
}
|
||||
|
||||
func (s *invitedRegistrationInvitationService) AcceptByToken(context.Context, string, string) (*types.TenantMember, error) {
|
||||
if s.acceptErr != nil {
|
||||
return nil, s.acceptErr
|
||||
}
|
||||
return &types.TenantMember{TenantID: 42, Role: types.TenantRoleViewer}, nil
|
||||
}
|
||||
|
||||
type invitedRegistrationTenantService struct {
|
||||
interfaces.TenantService
|
||||
}
|
||||
|
||||
func TestRegisterByInviteRestoresTenantlessAccountWhenInviteExpiresDuringRegistration(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
users := &invitedRegistrationUserService{}
|
||||
h := &AuthHandler{
|
||||
userService: users,
|
||||
tenantService: &invitedRegistrationTenantService{},
|
||||
invitationSvc: &invitedRegistrationInvitationService{acceptErr: errors.New("expired")},
|
||||
}
|
||||
r := gin.New()
|
||||
r.Use(errorCapture())
|
||||
r.POST("/auth/register-by-invite", h.RegisterByInvite)
|
||||
|
||||
body := []byte(`{"token":"invite-token","email":"alice@example.com","username":"alice","password":"supersecret"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusGone {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if users.updatedTenant != 0 {
|
||||
t.Fatalf("updated tenant=%d, want tenantless rollback", users.updatedTenant)
|
||||
}
|
||||
if len(users.updateCalls) != 2 || users.updateCalls[0] != 42 || users.updateCalls[1] != 0 {
|
||||
t.Fatalf("update calls=%v, want [42 0]", users.updateCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *invitedRegistrationTenantService) GetTenantByID(context.Context, uint64) (*types.Tenant, error) {
|
||||
return &types.Tenant{ID: 42, Name: "Invited Workspace"}, nil
|
||||
}
|
||||
|
||||
func TestRegisterByInviteUsesInvitedTenantWithoutPersonalTenant(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
users := &invitedRegistrationUserService{}
|
||||
h := &AuthHandler{
|
||||
userService: users,
|
||||
tenantService: &invitedRegistrationTenantService{},
|
||||
invitationSvc: &invitedRegistrationInvitationService{},
|
||||
}
|
||||
r := gin.New()
|
||||
r.Use(errorCapture())
|
||||
r.POST("/auth/register-by-invite", h.RegisterByInvite)
|
||||
|
||||
body := []byte(`{"token":"invite-token","email":"alice@example.com","username":"alice","password":"supersecret"}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if users.registeredMode != types.TenantProvisioningTenantless {
|
||||
t.Fatalf("register mode=%q, want tenantless", users.registeredMode)
|
||||
}
|
||||
if users.updatedTenant != 42 {
|
||||
t.Fatalf("updated tenant=%d, want 42", users.updatedTenant)
|
||||
}
|
||||
}
|
||||
@@ -107,8 +107,11 @@ func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
|
||||
// through by observing the stub being invoked.
|
||||
called := false
|
||||
us := &stubRegisterUserService{
|
||||
register: func(_ context.Context, _ *types.RegisterRequest) (*types.User, error) {
|
||||
register: func(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
|
||||
called = true
|
||||
if req.TenantProvisioning != types.TenantProvisioningCreatePersonal {
|
||||
t.Fatalf("default provisioning = %q, want create_personal", req.TenantProvisioning)
|
||||
}
|
||||
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
|
||||
},
|
||||
}
|
||||
@@ -125,6 +128,28 @@ func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegister_TenantlessProvisioningFromConfig(t *testing.T) {
|
||||
us := &stubRegisterUserService{
|
||||
register: func(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
|
||||
if req.TenantProvisioning != types.TenantProvisioningTenantless {
|
||||
t.Fatalf("provisioning = %q, want tenantless", req.TenantProvisioning)
|
||||
}
|
||||
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
|
||||
},
|
||||
}
|
||||
h := NewAuthHandler(&config.Config{
|
||||
Auth: &config.AuthConfig{
|
||||
RegistrationMode: config.AuthRegistrationModeSelfServe,
|
||||
DefaultTenantMode: config.AuthDefaultTenantModeTenantless,
|
||||
},
|
||||
}, us, nil, nil, nil)
|
||||
|
||||
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("tenantless self-serve registration got %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegister_NilAuthConfigDoesNotPanic(t *testing.T) {
|
||||
// Defensive: a nil Auth section means the operator hasn't set the
|
||||
// registration mode at all, which must not crash and must keep the
|
||||
|
||||
@@ -31,8 +31,8 @@ type TenantHandler struct {
|
||||
memberService interfaces.TenantMemberService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
config *config.Config
|
||||
// systemSettingSvc resolves runtime tunables for tenant limits
|
||||
// (currently `tenant.max_owned_per_user`). Reading goes DB > ENV >
|
||||
// systemSettingSvc resolves runtime tenant policies and limits.
|
||||
// Reading goes DB > ENV >
|
||||
// in-code default, so a SystemAdmin's UI override applies on the
|
||||
// very next CreateTenant call.
|
||||
systemSettingSvc interfaces.SystemSettingService
|
||||
@@ -228,6 +228,17 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Deployment-level policy: ordinary users may be restricted to joining
|
||||
// existing workspaces by invitation. This check is authoritative; the
|
||||
// frontend capability only improves UX and cannot bypass it. Cross-tenant
|
||||
// superusers retain the catalog-management create path.
|
||||
if !caller.CanAccessAllTenants &&
|
||||
!resolveTenantSelfServiceCreationEnabled(ctx, h.config, h.systemSettingSvc) {
|
||||
logger.Warnf(ctx, "Self-service tenant creation denied by policy for user %s", caller.ID)
|
||||
c.Error(errors.NewTenantCreationDisabledError())
|
||||
return
|
||||
}
|
||||
|
||||
var tenantData types.Tenant
|
||||
|
||||
if caller.CanAccessAllTenants {
|
||||
@@ -402,6 +413,23 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// When a tenantless user creates their first workspace, make it their
|
||||
// default login tenant. Roll the just-created resources back if this
|
||||
// finalisation fails so the user is not left with an unreachable tenant.
|
||||
if caller.TenantID == 0 {
|
||||
caller.TenantID = createdTenant.ID
|
||||
if err := h.userService.UpdateUser(ctx, caller); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set first tenant %d as default for user %s: %v",
|
||||
createdTenant.ID, caller.ID, err)
|
||||
if h.memberService != nil {
|
||||
_ = h.memberService.RemoveMember(ctx, caller.ID, createdTenant.ID)
|
||||
}
|
||||
_ = h.service.DeleteTenant(ctx, createdTenant.ID)
|
||||
c.Error(errors.NewInternalServerError("Failed to finalise default tenant").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Tenant created successfully, ID: %d, name: %s",
|
||||
|
||||
@@ -490,6 +490,19 @@ func (h *TenantInvitationHandler) AcceptMyInvitation(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// A tenantless account adopts the first accepted invitation as its
|
||||
// default tenant. Membership remains the authorization source; TenantID
|
||||
// only supplies the login/navigation default.
|
||||
if user, userErr := h.userService.GetUserByID(ctx, caller); userErr == nil && user != nil && user.TenantID == 0 {
|
||||
user.TenantID = member.TenantID
|
||||
if updateErr := h.userService.UpdateUser(ctx, user); updateErr != nil {
|
||||
logger.Errorf(ctx, "AcceptMyInvitation failed to set default tenant: user=%s tenant=%d err=%v",
|
||||
caller, member.TenantID, updateErr)
|
||||
c.Error(apperrors.NewInternalServerError("invitation accepted but default tenant update failed").WithDetails(updateErr.Error()))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
const (
|
||||
tenantSelfServiceCreationSettingKey = "tenant.self_service_creation_enabled"
|
||||
tenantSelfServiceCreationEnvName = "WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED"
|
||||
)
|
||||
|
||||
// resolveTenantSelfServiceCreationEnabled is the shared policy resolver used
|
||||
// both by POST /tenants enforcement and /auth/me capability projection. Keeping
|
||||
// both on one function prevents the UI from advertising a capability that the
|
||||
// backend would reject.
|
||||
func resolveTenantSelfServiceCreationEnabled(
|
||||
ctx context.Context,
|
||||
cfg *config.Config,
|
||||
settings interfaces.SystemSettingService,
|
||||
) bool {
|
||||
enabled := true
|
||||
if cfg != nil && cfg.Tenant != nil {
|
||||
enabled = cfg.Tenant.IsSelfServiceCreationEnabled()
|
||||
}
|
||||
if settings == nil {
|
||||
return enabled
|
||||
}
|
||||
return settings.GetBool(
|
||||
ctx,
|
||||
tenantSelfServiceCreationSettingKey,
|
||||
tenantSelfServiceCreationEnvName,
|
||||
enabled,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func tenantPolicyErrorCapture() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Next()
|
||||
if len(c.Errors) == 0 {
|
||||
return
|
||||
}
|
||||
if appErr, ok := c.Errors.Last().Err.(*apperrors.AppError); ok {
|
||||
c.JSON(appErr.HTTPCode, gin.H{"error": appErr})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type tenantPolicySettingService struct {
|
||||
interfaces.SystemSettingService
|
||||
enabled bool
|
||||
}
|
||||
|
||||
func (s *tenantPolicySettingService) GetBool(context.Context, string, string, bool) bool {
|
||||
return s.enabled
|
||||
}
|
||||
|
||||
func (s *tenantPolicySettingService) GetInt(_ context.Context, _ string, _ string, def int64) int64 {
|
||||
return def
|
||||
}
|
||||
|
||||
type tenantPolicyUserService struct {
|
||||
interfaces.UserService
|
||||
user *types.User
|
||||
}
|
||||
|
||||
func (s *tenantPolicyUserService) GetCurrentUser(context.Context) (*types.User, error) {
|
||||
return s.user, nil
|
||||
}
|
||||
|
||||
func (s *tenantPolicyUserService) BuildLoginMemberships(context.Context, *types.User, *types.Tenant) []types.Membership {
|
||||
return []types.Membership{}
|
||||
}
|
||||
|
||||
type tenantPolicyTenantService struct {
|
||||
interfaces.TenantService
|
||||
createCalls int
|
||||
}
|
||||
|
||||
func (s *tenantPolicyTenantService) CreateTenant(_ context.Context, tenant *types.Tenant) (*types.Tenant, error) {
|
||||
s.createCalls++
|
||||
tenant.ID = 99
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
func TestCreateTenantRejectsRegularUserWhenSelfServiceDisabled(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
tenants := &tenantPolicyTenantService{}
|
||||
h := &TenantHandler{
|
||||
service: tenants,
|
||||
userService: &tenantPolicyUserService{user: &types.User{ID: "regular-user"}},
|
||||
config: &config.Config{Tenant: &config.TenantConfig{}},
|
||||
systemSettingSvc: &tenantPolicySettingService{enabled: false},
|
||||
}
|
||||
r := gin.New()
|
||||
r.Use(tenantPolicyErrorCapture())
|
||||
r.POST("/tenants", h.CreateTenant)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/tenants", bytes.NewBufferString(`{"name":"blocked"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if tenants.createCalls != 0 {
|
||||
t.Fatalf("CreateTenant called %d times, want 0", tenants.createCalls)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), `"code":2005`) {
|
||||
t.Fatalf("response missing typed disabled code: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTenantAllowsCrossTenantSuperuserWhenSelfServiceDisabled(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
tenants := &tenantPolicyTenantService{}
|
||||
h := &TenantHandler{
|
||||
service: tenants,
|
||||
userService: &tenantPolicyUserService{user: &types.User{
|
||||
ID: "super-user",
|
||||
TenantID: 1,
|
||||
CanAccessAllTenants: true,
|
||||
}},
|
||||
config: &config.Config{Tenant: &config.TenantConfig{}},
|
||||
systemSettingSvc: &tenantPolicySettingService{enabled: false},
|
||||
}
|
||||
r := gin.New()
|
||||
r.Use(errorCapture())
|
||||
r.POST("/tenants", h.CreateTenant)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/tenants", bytes.NewBufferString(`{"name":"admin-created"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if tenants.createCalls != 1 {
|
||||
t.Fatalf("CreateTenant called %d times, want 1", tenants.createCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthMeProjectsTenantCreationCapability(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
h := &AuthHandler{
|
||||
userService: &tenantPolicyUserService{user: &types.User{
|
||||
ID: "tenantless-user",
|
||||
Username: "tenantless",
|
||||
Email: "tenantless@example.com",
|
||||
}},
|
||||
configInfo: &config.Config{Tenant: &config.TenantConfig{}},
|
||||
systemSettingSvc: &tenantPolicySettingService{enabled: false},
|
||||
}
|
||||
r := gin.New()
|
||||
r.GET("/auth/me", h.GetCurrentUser)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/auth/me", nil))
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), `"can_create_tenant":false`) {
|
||||
t.Fatalf("response missing capability: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,45 @@ func isNoAuthAPI(path string, method string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// isTenantOptionalAPI lists authenticated identity-level operations that are
|
||||
// meaningful before a user belongs to any tenant. Every other authenticated
|
||||
// route remains tenant-scoped and returns TENANT_REQUIRED when the JWT and
|
||||
// request headers do not resolve a tenant.
|
||||
func isTenantOptionalAPI(path, method string) bool {
|
||||
switch {
|
||||
case path == "/api/v1/auth/me" && (method == http.MethodGet || method == http.MethodPut):
|
||||
return true
|
||||
case path == "/api/v1/auth/logout" && method == http.MethodPost:
|
||||
return true
|
||||
case path == "/api/v1/auth/change-password" && method == http.MethodPost:
|
||||
return true
|
||||
case path == "/api/v1/auth/validate" && method == http.MethodGet:
|
||||
return true
|
||||
case path == "/api/v1/auth/switch-tenant" && method == http.MethodPost:
|
||||
return true
|
||||
case path == "/api/v1/tenants" && method == http.MethodPost:
|
||||
return true
|
||||
case strings.HasPrefix(path, "/api/v1/me/invitations"):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func attachTenantlessUserContext(c *gin.Context, user *types.User) {
|
||||
principal := types.Principal{Type: types.PrincipalWebUser, ID: user.ID}
|
||||
c.Set(types.UserContextKey.String(), user)
|
||||
c.Set(types.UserIDContextKey.String(), user.ID)
|
||||
c.Set(types.SystemAdminContextKey.String(), user.IsSystemAdmin)
|
||||
c.Set(types.PrincipalContextKey.String(), principal)
|
||||
ctx := c.Request.Context()
|
||||
ctx = context.WithValue(ctx, types.UserContextKey, user)
|
||||
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
|
||||
ctx = context.WithValue(ctx, types.SystemAdminContextKey, user.IsSystemAdmin)
|
||||
ctx = types.WithPrincipal(ctx, principal)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
}
|
||||
|
||||
// Auth 认证中间件
|
||||
func Auth(
|
||||
tenantService interfaces.TenantService,
|
||||
@@ -157,6 +196,25 @@ func Auth(
|
||||
}
|
||||
}
|
||||
|
||||
if targetTenantID == 0 {
|
||||
targetTenantID = resolveFirstMembershipTarget(c.Request.Context(), user, memberService, tenantService)
|
||||
crossTenantSwitch = targetTenantID != user.TenantID
|
||||
}
|
||||
|
||||
if targetTenantID == 0 {
|
||||
if isTenantOptionalAPI(c.Request.URL.Path, c.Request.Method) {
|
||||
attachTenantlessUserContext(c, user)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusConflict, gin.H{
|
||||
"error": "Tenant required",
|
||||
"code": "TENANT_REQUIRED",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 获取租户信息(使用目标租户ID)
|
||||
tenant, err := tenantService.GetTenantByID(c.Request.Context(), targetTenantID)
|
||||
if err != nil {
|
||||
@@ -229,6 +287,37 @@ func Auth(
|
||||
}
|
||||
}
|
||||
|
||||
// resolveFirstMembershipTarget lets a tenantless session immediately become
|
||||
// usable once an active membership exists (for example after accepting its
|
||||
// first invitation or being added directly by an administrator). The user
|
||||
// service persists the same earliest-membership choice on the next token
|
||||
// issuance; middleware keeps the current JWT usable until then.
|
||||
func resolveFirstMembershipTarget(
|
||||
ctx context.Context,
|
||||
user *types.User,
|
||||
memberService interfaces.TenantMemberService,
|
||||
tenantService interfaces.TenantService,
|
||||
) uint64 {
|
||||
if user == nil || memberService == nil || tenantService == nil {
|
||||
return 0
|
||||
}
|
||||
members, err := memberService.ListByUser(ctx, user.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list memberships for tenantless user %s: %v", user.ID, err)
|
||||
return 0
|
||||
}
|
||||
for _, member := range members {
|
||||
if member == nil || member.TenantID == 0 || member.Status != types.TenantMemberStatusActive {
|
||||
continue
|
||||
}
|
||||
tenant, err := tenantService.GetTenantByID(ctx, member.TenantID)
|
||||
if err == nil && tenant != nil {
|
||||
return member.TenantID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func authenticateAPIKeyRequest(
|
||||
c *gin.Context,
|
||||
tenantService interfaces.TenantService,
|
||||
|
||||
@@ -24,9 +24,9 @@ type fakeMemberService struct {
|
||||
TenantID uint64
|
||||
Role types.TenantRole
|
||||
}
|
||||
failGet error
|
||||
failHasAny error
|
||||
failAdd error
|
||||
failGet error
|
||||
failHasAny error
|
||||
failAdd error
|
||||
// 阻止 auto-promote 把 hasAny 翻面:默认 AddMember 成功也会写入 members map。
|
||||
}
|
||||
|
||||
@@ -102,7 +102,14 @@ func (f *fakeMemberService) GetMembership(
|
||||
}
|
||||
|
||||
func (f *fakeMemberService) ListByUser(ctx context.Context, userID string) ([]*types.TenantMember, error) {
|
||||
return nil, nil
|
||||
var out []*types.TenantMember
|
||||
for _, member := range f.members {
|
||||
if member.UserID == userID && member.Status == types.TenantMemberStatusActive {
|
||||
copy := *member
|
||||
out = append(out, ©)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (f *fakeMemberService) ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error) {
|
||||
return nil, nil
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestTenantOptionalAPISurface(t *testing.T) {
|
||||
tests := []struct {
|
||||
method string
|
||||
path string
|
||||
want bool
|
||||
}{
|
||||
{http.MethodGet, "/api/v1/auth/me", true},
|
||||
{http.MethodPut, "/api/v1/auth/me", true},
|
||||
{http.MethodPost, "/api/v1/tenants", true},
|
||||
{http.MethodGet, "/api/v1/me/invitations", true},
|
||||
{http.MethodPost, "/api/v1/me/invitations/12/accept", true},
|
||||
{http.MethodGet, "/api/v1/knowledge-bases", false},
|
||||
{http.MethodGet, "/api/v1/tenants", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := isTenantOptionalAPI(tt.path, tt.method); got != tt.want {
|
||||
t.Errorf("isTenantOptionalAPI(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveFirstMembershipTarget(t *testing.T) {
|
||||
members := newFakeMemberService()
|
||||
members.seedActive("tenantless-user", 42, types.TenantRoleViewer)
|
||||
tenants := &fakeTenantService{tenant: &types.Tenant{ID: 42}}
|
||||
|
||||
got := resolveFirstMembershipTarget(
|
||||
context.Background(),
|
||||
&types.User{ID: "tenantless-user"},
|
||||
members,
|
||||
tenants,
|
||||
)
|
||||
if got != 42 {
|
||||
t.Fatalf("resolved tenant = %d, want 42", got)
|
||||
}
|
||||
}
|
||||
@@ -185,6 +185,27 @@ type RegisterRequest struct {
|
||||
Username string `json:"username" binding:"required,min=2,max=50"`
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
|
||||
// TenantProvisioning is server-controlled registration context. It is
|
||||
// deliberately excluded from JSON so a public caller cannot choose its
|
||||
// own tenancy semantics. Empty preserves the historical behaviour and is
|
||||
// treated as create_personal by UserService.Register.
|
||||
TenantProvisioning TenantProvisioningMode `json:"-"`
|
||||
}
|
||||
|
||||
// TenantProvisioningMode controls what UserService.Register does after it
|
||||
// has validated the identity fields. Joining an existing tenant is
|
||||
// orchestrated by the invitation handler because the invitation token is the
|
||||
// authority for the target tenant and role.
|
||||
type TenantProvisioningMode string
|
||||
|
||||
const (
|
||||
TenantProvisioningCreatePersonal TenantProvisioningMode = "create_personal"
|
||||
TenantProvisioningTenantless TenantProvisioningMode = "tenantless"
|
||||
)
|
||||
|
||||
func (m TenantProvisioningMode) IsValid() bool {
|
||||
return m == TenantProvisioningCreatePersonal || m == TenantProvisioningTenantless
|
||||
}
|
||||
|
||||
// LoginResponse represents a login response
|
||||
|
||||
Reference in New Issue
Block a user