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:
wizardchen
2026-05-16 04:42:21 +08:00
committed by lyingbug
parent 79d397297d
commit 29dc99ae79
10 changed files with 466 additions and 29 deletions
+91 -16
View File
@@ -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",
+8 -5
View File
@@ -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