From 29dc99ae79a8d8e066b1be484e79648c7b7e32ad Mon Sep 17 00:00:00 2001 From: wizardchen Date: Sat, 16 May 2026 04:42:21 +0800 Subject: [PATCH] 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 --- frontend/src/api/tenant/index.ts | 20 +++ .../src/components/CreateTenantDialog.vue | 120 ++++++++++++++++++ frontend/src/components/TenantSelector.vue | 70 +++++++++- frontend/src/components/UserMenu.vue | 87 ++++++++++++- frontend/src/i18n/locales/en-US.ts | 13 ++ frontend/src/i18n/locales/ko-KR.ts | 26 ++++ frontend/src/i18n/locales/ru-RU.ts | 26 ++++ frontend/src/i18n/locales/zh-CN.ts | 13 ++ internal/handler/tenant.go | 107 +++++++++++++--- internal/router/router.go | 13 +- 10 files changed, 466 insertions(+), 29 deletions(-) create mode 100644 frontend/src/components/CreateTenantDialog.vue diff --git a/frontend/src/api/tenant/index.ts b/frontend/src/api/tenant/index.ts index 2b728fab..f3f1a9c2 100644 --- a/frontend/src/api/tenant/index.ts +++ b/frontend/src/api/tenant/index.ts @@ -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过滤) */ diff --git a/frontend/src/components/CreateTenantDialog.vue b/frontend/src/components/CreateTenantDialog.vue new file mode 100644 index 00000000..5eac5428 --- /dev/null +++ b/frontend/src/components/CreateTenantDialog.vue @@ -0,0 +1,120 @@ + + + diff --git a/frontend/src/components/TenantSelector.vue b/frontend/src/components/TenantSelector.vue index 512bf961..cb3d3774 100644 --- a/frontend/src/components/TenantSelector.vue +++ b/frontend/src/components/TenantSelector.vue @@ -68,11 +68,21 @@ + + +
+ + {{ $t('tenant.create.action') }} +
- +
+ + + @@ -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 { diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue index 05f4ea0d..51a2ffa9 100644 --- a/frontend/src/components/UserMenu.vue +++ b/frontend/src/components/UserMenu.vue @@ -208,8 +208,19 @@ {{ $t('tenant.switcher.empty') }} + +
+ + {{ $t('tenant.create.action') }} +
+ + + @@ -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(() => { 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; + } + } } diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index a63f714e..d751219a 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -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', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index a782f750..aa157c38 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -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: "소속 테넌트의 고유 식별자", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 14c20650..12f11d48 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -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: 'Уникальный идентификатор вашего арендатора', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 9fbf9639..519752c7 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -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: "您所属租户的唯一标识", diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go index 0b8e353c..0cfd62da 100644 --- a/internal/handler/tenant.go +++ b/internal/handler/tenant.go @@ -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", diff --git a/internal/router/router.go b/internal/router/router.go index c193c6d9..d448ce5f 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -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