feat(tenant): implement self-service tenant creation functionality
Added a new API endpoint for creating tenants, allowing any logged-in user to create their own workspace. The backend automatically assigns the creator as the Owner of the new tenant. A new CreateTenantDialog component was introduced in the frontend, enabling users to input the workspace name and an optional description. Internationalization files were updated to include relevant messages for this feature across multiple languages. Refs: #1303
This commit is contained in:
@@ -91,6 +91,26 @@ export async function updateTenant(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建新工作区(任意已登录用户均可调用)。
|
||||
* 后端会自动把调用者写成新租户的 Owner,并生成 api_key、默认 storage_quota
|
||||
* 等服务端字段,所以这里只暴露 name + description。
|
||||
* 路由:POST /api/v1/tenants(router 上不挂 g.CrossTenant(),自助场景使用)。
|
||||
*/
|
||||
export async function createTenant(
|
||||
payload: { name: string; description?: string },
|
||||
): Promise<{ success: boolean; data?: TenantInfo; message?: string }> {
|
||||
try {
|
||||
const response = await post('/api/v1/tenants', payload)
|
||||
return response as unknown as { success: boolean; data?: TenantInfo; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.tenant.createFailed'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索租户(支持分页、关键词搜索和租户ID过滤)
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
<template>
|
||||
<!-- 自助创建新工作区弹窗。任意已登录用户均可调用 POST /api/v1/tenants
|
||||
(后端 router 已去掉 g.CrossTenant() 守卫),handler 会自动把当前
|
||||
用户 EnsureOwner 成新租户的 Owner。提交成功后通知父组件,由父组件
|
||||
决定下一步导航(一般是切到新租户)。 -->
|
||||
<t-dialog
|
||||
:visible="visible"
|
||||
:header="$t('tenant.create.dialogTitle')"
|
||||
width="480px"
|
||||
:on-confirm="handleSubmit"
|
||||
:on-close="handleClose"
|
||||
:confirm-btn="{ content: $t('tenant.create.submit'), loading: submitting, theme: 'primary' }"
|
||||
:cancel-btn="{ content: $t('tenant.create.cancel') }"
|
||||
:close-on-overlay-click="!submitting"
|
||||
:close-on-esc-keydown="!submitting"
|
||||
@update:visible="onVisibleUpdate"
|
||||
>
|
||||
<t-form ref="formRef" :data="form" :rules="formRules" @submit.prevent>
|
||||
<t-form-item :label="$t('tenant.create.nameLabel')" name="name">
|
||||
<t-input
|
||||
v-model="form.name"
|
||||
:placeholder="$t('tenant.create.namePlaceholder')"
|
||||
:maxlength="128"
|
||||
autofocus
|
||||
/>
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('tenant.create.descriptionLabel')" name="description">
|
||||
<t-textarea
|
||||
v-model="form.description"
|
||||
:placeholder="$t('tenant.create.descriptionPlaceholder')"
|
||||
:maxlength="512"
|
||||
:autosize="{ minRows: 2, maxRows: 4 }"
|
||||
/>
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
</t-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin, type FormInstanceFunctions, type FormRule } from 'tdesign-vue-next'
|
||||
import { createTenant, type TenantInfo } from '@/api/tenant'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:visible', value: boolean): void
|
||||
// 创建成功后由父组件决定如何导航(切换到新租户、刷新本地列表等)。
|
||||
(e: 'created', tenant: TenantInfo): void
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const formRef = ref<FormInstanceFunctions | null>(null)
|
||||
const submitting = ref(false)
|
||||
|
||||
const form = reactive({
|
||||
name: '',
|
||||
description: '',
|
||||
})
|
||||
|
||||
const formRules: Record<string, FormRule[]> = {
|
||||
name: [
|
||||
{ required: true, message: t('tenant.create.nameRequired'), trigger: 'blur' },
|
||||
{ max: 128, message: t('tenant.create.nameRequired'), trigger: 'blur' },
|
||||
],
|
||||
}
|
||||
|
||||
// 每次打开时重置表单;关闭时不动状态,让动画结束。
|
||||
watch(
|
||||
() => props.visible,
|
||||
(open) => {
|
||||
if (open) {
|
||||
form.name = ''
|
||||
form.description = ''
|
||||
// 等 dialog 渲染完成再清掉之前的校验态。
|
||||
requestAnimationFrame(() => formRef.value?.clearValidate?.())
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const onVisibleUpdate = (next: boolean) => {
|
||||
if (!next && submitting.value) return
|
||||
emit('update:visible', next)
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
if (submitting.value) return
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (submitting.value) return
|
||||
const validateResult = await formRef.value?.validate?.()
|
||||
if (validateResult !== true) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const response = await createTenant({
|
||||
name: form.name.trim(),
|
||||
description: form.description.trim() || undefined,
|
||||
})
|
||||
if (!response.success || !response.data) {
|
||||
MessagePlugin.error(response.message || t('tenant.create.failed'))
|
||||
return
|
||||
}
|
||||
MessagePlugin.success(t('tenant.create.success'))
|
||||
emit('created', response.data)
|
||||
emit('update:visible', false)
|
||||
} catch (error: any) {
|
||||
console.error('Failed to create tenant:', error)
|
||||
MessagePlugin.error(error?.message || t('tenant.create.failed'))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -68,11 +68,21 @@
|
||||
<t-loading size="small" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 自助创建新工作区入口:任意已登录用户可点击,后端会把当前用户
|
||||
写成新租户的 Owner(见 internal/handler/tenant.go CreateTenant)。 -->
|
||||
<div 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>
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
|
||||
<!-- 遮罩层 -->
|
||||
<div v-if="showDropdown" class="tenant-overlay" @click="closeDropdown"></div>
|
||||
|
||||
<!-- 创建工作区弹窗:复用共享组件,TenantSelector 与 UserMenu 都用它 -->
|
||||
<CreateTenantDialog v-model:visible="createDialogVisible" @created="onTenantCreated" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -83,6 +93,7 @@ import { searchTenants, type TenantInfo } from '@/api/tenant'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { navigateAfterTenantSwitch } from '@/utils/tenantSwitch'
|
||||
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const authStore = useAuthStore()
|
||||
@@ -231,16 +242,38 @@ const handleSearchInput = () => {
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!tenantListRef.value) return
|
||||
|
||||
|
||||
const { scrollTop, scrollHeight, clientHeight } = tenantListRef.value
|
||||
const isNearBottom = scrollHeight - scrollTop - clientHeight < 50
|
||||
|
||||
|
||||
if (isNearBottom && hasMore.value && !loading.value) {
|
||||
currentPage.value++
|
||||
loadTenants(true)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 创建新工作区 ----
|
||||
// dialog 由共享组件 CreateTenantDialog 渲染,这里只负责打开 / 接收创建结果。
|
||||
const createDialogVisible = ref(false)
|
||||
|
||||
const openCreateDialog = () => {
|
||||
closeDropdown()
|
||||
createDialogVisible.value = true
|
||||
}
|
||||
|
||||
const onTenantCreated = (newTenant: TenantInfo) => {
|
||||
// 把新租户合并进当前列表并切过去。和 selectTenant 走同一条链路:
|
||||
// setSelectedTenant + navigateAfterTenantSwitch。后端 X-Tenant-ID 中
|
||||
// 间件会查 tenant_members 校验,EnsureOwner 已经在后端写好 owner 行。
|
||||
tenants.value = [newTenant, ...tenants.value.filter(t => t.id !== newTenant.id)]
|
||||
total.value = total.value + 1
|
||||
authStore.setAllTenants(tenants.value)
|
||||
authStore.setSelectedTenant(newTenant.id, newTenant.name)
|
||||
setTimeout(() => {
|
||||
navigateAfterTenantSwitch()
|
||||
}, 300)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 预加载租户列表
|
||||
loadTenants()
|
||||
@@ -517,6 +550,37 @@ onUnmounted(() => {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.tenant-create-action {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
margin: 4px 6px 6px;
|
||||
border-top: .5px solid var(--td-component-stroke);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
color: var(--td-brand-color);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: rgba(7, 192, 95, 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
.tenant-create-icon {
|
||||
font-size: 14px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.tenant-create-label {
|
||||
flex: 1;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
// 下拉动画
|
||||
.dropdown-enter-active,
|
||||
.dropdown-leave-active {
|
||||
|
||||
@@ -208,8 +208,19 @@
|
||||
{{ $t('tenant.switcher.empty') }}
|
||||
</div>
|
||||
</div>
|
||||
<!-- 自助创建新工作区入口:放在租户列表底部,所有能 hover 出这个
|
||||
子菜单的用户都能看到(包括单租户用户)。后端 router 已对
|
||||
POST /api/v1/tenants 去掉跨租户超管守卫,handler 内部会把
|
||||
当前用户 EnsureOwner 成新租户的 Owner。 -->
|
||||
<div 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>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<!-- 创建工作区弹窗 -->
|
||||
<CreateTenantDialog v-model:visible="createTenantDialogVisible" @created="onTenantCreated" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -222,8 +233,10 @@ import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { getCurrentUser, logout as logoutApi } from '@/api/auth'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import IMChannelsOverviewPanel from '@/components/IMChannelsOverviewPanel.vue'
|
||||
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
|
||||
import { listAllIMChannels, type IMChannelOverview } from '@/api/agent'
|
||||
import { navigateAfterTenantSwitch } from '@/utils/tenantSwitch'
|
||||
import type { TenantInfo } from '@/api/tenant'
|
||||
import { useRoleLabel, useHomeTenant } from '@/composables/useRoleLabel'
|
||||
|
||||
const { t } = useI18n()
|
||||
@@ -350,6 +363,37 @@ const closeAll = () => {
|
||||
menuVisible.value = false
|
||||
}
|
||||
|
||||
// ---------- Create new tenant ----------
|
||||
// 普通用户在租户子菜单底部点 "+ 创建新工作区" → 弹 CreateTenantDialog →
|
||||
// 后端写一行 owner 的 tenant_members → 直接切到新租户。复用 switchToTenant
|
||||
// 同款的 setSelectedTenant + navigateAfterTenantSwitch 链路,避免 token
|
||||
// 依然指向旧租户带来的 SSE / store 不一致。
|
||||
const createTenantDialogVisible = ref(false)
|
||||
|
||||
const openCreateTenantDialog = () => {
|
||||
closeAll()
|
||||
createTenantDialogVisible.value = true
|
||||
}
|
||||
|
||||
const onTenantCreated = (newTenant: TenantInfo) => {
|
||||
// memberships 由 /auth/login 落库 + localStorage 缓存。这里追加一条
|
||||
// owner 进去让 hover 子菜单立即看到新租户;hard reload 后会被
|
||||
// /auth/me 的真实数据覆盖,状态不会长期失真。
|
||||
const next = [
|
||||
...(authStore.memberships ?? []),
|
||||
{
|
||||
tenant_id: newTenant.id,
|
||||
tenant_name: newTenant.name,
|
||||
role: 'owner',
|
||||
},
|
||||
]
|
||||
authStore.setMemberships(next)
|
||||
authStore.setSelectedTenant(newTenant.id, newTenant.name)
|
||||
setTimeout(() => {
|
||||
navigateAfterTenantSwitch()
|
||||
}, 300)
|
||||
}
|
||||
|
||||
// ---------- Tenant switcher submenu ----------
|
||||
//
|
||||
// Same hover-driven submenu pattern as the IM panel above; data comes from
|
||||
@@ -372,12 +416,14 @@ const switchableMemberships = computed<Membership[]>(() => {
|
||||
return authStore.memberships ?? []
|
||||
})
|
||||
|
||||
// Rendered only when there's something to switch *to*. Multi-tenant members
|
||||
// (memberships.length > 1) need it for tenant switching; superusers keep
|
||||
// using the sidebar TenantSelector for the "any tenant in the system" case,
|
||||
// so we don't double-show the entry there.
|
||||
// Rendered whenever the user has at least one membership — even single-
|
||||
// tenant users need this submenu to discover the "create new workspace"
|
||||
// entry at the bottom. Multi-tenant users additionally use it to switch
|
||||
// between memberships. Cross-tenant superusers keep using the sidebar
|
||||
// TenantSelector for the "any tenant in the system" case, so we don't
|
||||
// double-show that here.
|
||||
const showTenantSwitcher = computed(() => {
|
||||
return switchableMemberships.value.length > 1
|
||||
return switchableMemberships.value.length >= 1
|
||||
})
|
||||
|
||||
const isCurrentTenant = (id: number) => {
|
||||
@@ -1234,5 +1280,36 @@ onUnmounted(() => {
|
||||
font-size: 12px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.tenant-submenu-create {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
margin: 4px 6px 6px;
|
||||
border-top: .5px solid var(--td-component-stroke);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
color: var(--td-brand-color);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: rgba(7, 192, 95, 0.08);
|
||||
}
|
||||
|
||||
.tenant-submenu-create-icon {
|
||||
font-size: 14px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.tenant-submenu-create-label {
|
||||
flex: 1;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -2342,6 +2342,19 @@ export default {
|
||||
loadTenantsFailed: 'Failed to load tenant list',
|
||||
loading: 'Loading...',
|
||||
loadMore: 'Load more',
|
||||
create: {
|
||||
action: 'Create new workspace',
|
||||
dialogTitle: 'Create new workspace',
|
||||
nameLabel: 'Workspace name',
|
||||
namePlaceholder: 'e.g. My new project',
|
||||
nameRequired: 'Please enter a workspace name',
|
||||
descriptionLabel: 'Description (optional)',
|
||||
descriptionPlaceholder: 'Briefly describe what this workspace is for',
|
||||
submit: 'Create',
|
||||
cancel: 'Cancel',
|
||||
success: 'Workspace created successfully',
|
||||
failed: 'Failed to create workspace',
|
||||
},
|
||||
details: {
|
||||
idLabel: 'Tenant ID',
|
||||
idDescription: 'Unique identifier of your tenant',
|
||||
|
||||
@@ -1599,6 +1599,32 @@ export default {
|
||||
loadTenantsFailed: "테넌트 목록 로드 실패",
|
||||
loading: "로딩 중...",
|
||||
loadMore: "더 보기",
|
||||
create: {
|
||||
action: "새 워크스페이스 만들기",
|
||||
dialogTitle: "새 워크스페이스 만들기",
|
||||
nameLabel: "워크스페이스 이름",
|
||||
namePlaceholder: "예: 새 프로젝트",
|
||||
nameRequired: "워크스페이스 이름을 입력하세요",
|
||||
descriptionLabel: "설명(선택)",
|
||||
descriptionPlaceholder: "이 워크스페이스의 용도를 간단히 설명하세요",
|
||||
submit: "만들기",
|
||||
cancel: "취소",
|
||||
success: "워크스페이스가 생성되었습니다",
|
||||
failed: "워크스페이스 생성 실패",
|
||||
},
|
||||
create: {
|
||||
action: "새 워크스페이스 만들기",
|
||||
dialogTitle: "새 워크스페이스 만들기",
|
||||
nameLabel: "워크스페이스 이름",
|
||||
namePlaceholder: "예: 새 프로젝트",
|
||||
nameRequired: "워크스페이스 이름을 입력하세요",
|
||||
descriptionLabel: "설명(선택)",
|
||||
descriptionPlaceholder: "이 워크스페이스의 용도를 간단히 설명하세요",
|
||||
submit: "만들기",
|
||||
cancel: "취소",
|
||||
success: "워크스페이스가 생성되었습니다",
|
||||
failed: "워크스페이스 생성 실패",
|
||||
},
|
||||
details: {
|
||||
idLabel: "테넌트 ID",
|
||||
idDescription: "소속 테넌트의 고유 식별자",
|
||||
|
||||
@@ -1417,6 +1417,32 @@ export default {
|
||||
loadTenantsFailed: 'Не удалось загрузить список арендаторов',
|
||||
loading: 'Загрузка...',
|
||||
loadMore: 'Загрузить еще',
|
||||
create: {
|
||||
action: 'Создать новое рабочее пространство',
|
||||
dialogTitle: 'Создать новое рабочее пространство',
|
||||
nameLabel: 'Название',
|
||||
namePlaceholder: 'Например: Мой новый проект',
|
||||
nameRequired: 'Введите название рабочего пространства',
|
||||
descriptionLabel: 'Описание (необязательно)',
|
||||
descriptionPlaceholder: 'Кратко опишите назначение рабочего пространства',
|
||||
submit: 'Создать',
|
||||
cancel: 'Отмена',
|
||||
success: 'Рабочее пространство создано',
|
||||
failed: 'Не удалось создать рабочее пространство',
|
||||
},
|
||||
create: {
|
||||
action: 'Создать новое рабочее пространство',
|
||||
dialogTitle: 'Создать новое рабочее пространство',
|
||||
nameLabel: 'Название',
|
||||
namePlaceholder: 'Например: Мой новый проект',
|
||||
nameRequired: 'Введите название рабочего пространства',
|
||||
descriptionLabel: 'Описание (необязательно)',
|
||||
descriptionPlaceholder: 'Кратко опишите назначение рабочего пространства',
|
||||
submit: 'Создать',
|
||||
cancel: 'Отмена',
|
||||
success: 'Рабочее пространство создано',
|
||||
failed: 'Не удалось создать рабочее пространство',
|
||||
},
|
||||
details: {
|
||||
idLabel: 'ID арендатора',
|
||||
idDescription: 'Уникальный идентификатор вашего арендатора',
|
||||
|
||||
@@ -1579,6 +1579,19 @@ export default {
|
||||
loadTenantsFailed: "加载租户列表失败",
|
||||
loading: "加载中...",
|
||||
loadMore: "加载更多",
|
||||
create: {
|
||||
action: "创建新工作区",
|
||||
dialogTitle: "创建新工作区",
|
||||
nameLabel: "工作区名称",
|
||||
namePlaceholder: "例如:我的新项目",
|
||||
nameRequired: "请输入工作区名称",
|
||||
descriptionLabel: "描述(可选)",
|
||||
descriptionPlaceholder: "简单描述一下这个工作区的用途",
|
||||
submit: "创建",
|
||||
cancel: "取消",
|
||||
success: "工作区创建成功",
|
||||
failed: "工作区创建失败",
|
||||
},
|
||||
details: {
|
||||
idLabel: "租户 ID",
|
||||
idDescription: "您所属租户的唯一标识",
|
||||
|
||||
+91
-16
@@ -21,16 +21,19 @@ import (
|
||||
// Provides functionality for creating, retrieving, updating, and deleting tenants
|
||||
// through the REST API endpoints
|
||||
type TenantHandler struct {
|
||||
service interfaces.TenantService
|
||||
userService interfaces.UserService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
config *config.Config
|
||||
service interfaces.TenantService
|
||||
userService interfaces.UserService
|
||||
memberService interfaces.TenantMemberService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
config *config.Config
|
||||
}
|
||||
|
||||
// NewTenantHandler creates a new tenant handler instance with the provided service
|
||||
// Parameters:
|
||||
// - service: An implementation of the TenantService interface for business logic
|
||||
// - userService: An implementation of the UserService interface for user operations
|
||||
// - memberService: An implementation of TenantMemberService used to bootstrap
|
||||
// the creator as Owner of the tenant they just created (self-service create).
|
||||
// - config: Application configuration
|
||||
//
|
||||
// Returns a pointer to the newly created TenantHandler
|
||||
@@ -42,22 +45,46 @@ type TenantHandler struct {
|
||||
// `middleware/access.go` (RequireCrossTenantAccess /
|
||||
// RequirePathTenantMatch) and are wired in `router.go` so the handler
|
||||
// stays focused on business logic.
|
||||
func NewTenantHandler(service interfaces.TenantService, userService interfaces.UserService, kbService interfaces.KnowledgeBaseService, config *config.Config) *TenantHandler {
|
||||
func NewTenantHandler(
|
||||
service interfaces.TenantService,
|
||||
userService interfaces.UserService,
|
||||
memberService interfaces.TenantMemberService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
config *config.Config,
|
||||
) *TenantHandler {
|
||||
return &TenantHandler{
|
||||
service: service,
|
||||
userService: userService,
|
||||
kbService: kbService,
|
||||
config: config,
|
||||
service: service,
|
||||
userService: userService,
|
||||
memberService: memberService,
|
||||
kbService: kbService,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// createTenantRequest is the JSON body for POST /tenants. Only fields a
|
||||
// regular authenticated user is allowed to set are accepted; everything
|
||||
// else (api_key, status, storage_quota, retriever_engines, etc.) is
|
||||
// generated server-side by TenantService.CreateTenant so a normal user
|
||||
// can't bypass quotas or self-suspend a workspace at create time.
|
||||
//
|
||||
// Cross-tenant superusers historically posted the full Tenant struct to
|
||||
// this endpoint. We keep that path working by binding into the same
|
||||
// types.Tenant when CanAccessAllTenants is true (see CreateTenant
|
||||
// below), but the recommended shape going forward is name+description.
|
||||
type createTenantRequest struct {
|
||||
Name string `json:"name" binding:"required,min=1,max=128"`
|
||||
Description string `json:"description" binding:"max=512"`
|
||||
}
|
||||
|
||||
// CreateTenant godoc
|
||||
// @Summary 创建租户
|
||||
// @Description 创建新的租户
|
||||
// @Description 创建新的租户。任意已登录用户均可调用以建立自己的新工作区,
|
||||
// @Description 调用方会被自动设为该租户的 Owner。跨租户超管仍可像以前一样
|
||||
// @Description 通过本接口创建任意租户。
|
||||
// @Tags 租户管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body types.Tenant true "租户信息"
|
||||
// @Param request body handler.createTenantRequest true "租户信息"
|
||||
// @Success 201 {object} map[string]interface{} "创建的租户"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
@@ -67,14 +94,46 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Start creating tenant")
|
||||
|
||||
var tenantData types.Tenant
|
||||
if err := c.ShouldBindJSON(&tenantData); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
appErr := errors.NewValidationError("Invalid request parameters").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
// Resolve the caller; required so we can bootstrap the Owner
|
||||
// membership and so we can branch on cross-tenant superuser status
|
||||
// for the legacy full-payload path.
|
||||
caller, err := h.userService.GetCurrentUser(ctx)
|
||||
if err != nil || caller == nil {
|
||||
logger.Error(ctx, "Failed to resolve current user from context", err)
|
||||
c.Error(errors.NewUnauthorizedError("authentication required"))
|
||||
return
|
||||
}
|
||||
|
||||
var tenantData types.Tenant
|
||||
|
||||
if caller.CanAccessAllTenants {
|
||||
// Backward-compatible path for cross-tenant superusers: accept
|
||||
// the full Tenant payload (status, storage_quota, retriever
|
||||
// engines, configs...) so existing tooling keeps working.
|
||||
if err := c.ShouldBindJSON(&tenantData); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
appErr := errors.NewValidationError("Invalid request parameters").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// Self-service path: a regular user can only set name and
|
||||
// description. Everything else is server-generated by
|
||||
// TenantService.CreateTenant (api_key, status="active",
|
||||
// storage_quota default, retriever engines from RETRIEVE_DRIVER).
|
||||
var req createTenantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
appErr := errors.NewValidationError("Invalid request parameters").WithDetails(err.Error())
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
tenantData = types.Tenant{
|
||||
Name: strings.TrimSpace(req.Name),
|
||||
Description: strings.TrimSpace(req.Description),
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Creating tenant, name: %s", secutils.SanitizeForLog(tenantData.Name))
|
||||
|
||||
createdTenant, err := h.service.CreateTenant(ctx, &tenantData)
|
||||
@@ -90,6 +149,22 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Bootstrap an Owner membership so the caller immediately has full
|
||||
// control over the tenant they just created. This mirrors what
|
||||
// userService.Register does for the auto-created home tenant.
|
||||
// Idempotent: EnsureOwner is a no-op if the row already exists,
|
||||
// which lets cross-tenant superusers create-and-own without a
|
||||
// separate code path. Failure here only logs — the orphan-tenant
|
||||
// recovery path in middleware/auth.go will recreate the membership
|
||||
// on next login as a safety net.
|
||||
if h.memberService != nil {
|
||||
if _, err := h.memberService.EnsureOwner(ctx, caller.ID, createdTenant.ID); err != nil {
|
||||
logger.Errorf(ctx,
|
||||
"Failed to bootstrap owner membership for user %s tenant %d: %v",
|
||||
caller.ID, createdTenant.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Tenant created successfully, ID: %d, name: %s",
|
||||
|
||||
@@ -496,11 +496,14 @@ func RegisterTenantRoutes(
|
||||
// 租户路由组
|
||||
tenantRoutes := r.Group("/tenants")
|
||||
{
|
||||
// 创建租户是组织级管理动作(建一个新租户只有 cross-tenant
|
||||
// 超管可以做),所以挂 g.CrossTenant() — 与 /tenants/all、
|
||||
// /tenants/search 保持一致。普通用户的租户在登录/auto-setup
|
||||
// 链路里隐式创建,不走这个端点。
|
||||
tenantRoutes.POST("", g.CrossTenant(), handler.CreateTenant)
|
||||
// 创建租户对所有已登录用户开放:用户可以为自己再开一个工作区,
|
||||
// handler 内部会调 EnsureOwner 把调用者写成新租户的 Owner。
|
||||
// 跨租户超管走同一个端点,但能携带 storage_quota / status 等
|
||||
// 全字段(见 handler.CreateTenant 内部分支)。
|
||||
// 安全说明:这里不挂 g.CrossTenant(),因为 self-service 创建
|
||||
// 不需要跨租户特权;handler 也不读写 X-Tenant-ID 指向的现有
|
||||
// 租户,所以越过 PathTenantMatch 守卫不会扩大攻击面。
|
||||
tenantRoutes.POST("", handler.CreateTenant)
|
||||
tenantRoutes.GET("", handler.ListTenants)
|
||||
|
||||
// Generic KV configuration management (tenant-level). Tenant ID
|
||||
|
||||
Reference in New Issue
Block a user