feat: Implement cross-tenant access functionality

- Added configuration for enabling cross-tenant access in the application.
- Introduced new API endpoints for listing and searching tenants, accessible only to users with the appropriate permissions.
- Updated user and tenant models to include the `can_access_all_tenants` field.
- Enhanced the authentication middleware to handle cross-tenant requests and validate user permissions.
- Created a new TenantSelector component for selecting tenants in the frontend, improving user experience.
- Updated internationalization files to support new tenant-related strings and messages.
This commit is contained in:
wizardchen
2025-12-02 12:17:39 +08:00
parent e66ace9c14
commit cdf576eb18
22 changed files with 1079 additions and 29 deletions
+39
View File
@@ -52,6 +52,45 @@ func (r *tenantRepository) ListTenants(ctx context.Context) ([]*types.Tenant, er
return tenants, nil
}
// SearchTenants searches tenants with pagination and filters
func (r *tenantRepository) SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error) {
var tenants []*types.Tenant
var total int64
query := r.db.WithContext(ctx).Model(&types.Tenant{})
// Filter by tenant ID if provided
if tenantID > 0 {
query = query.Where("id = ?", tenantID)
}
// Filter by keyword if provided (search in name and description)
if keyword != "" {
query = query.Where("name LIKE ? OR description LIKE ?", "%"+keyword+"%", "%"+keyword+"%")
}
// Count total
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
}
// Apply pagination
if page > 0 && pageSize > 0 {
offset := (page - 1) * pageSize
query = query.Offset(offset).Limit(pageSize)
}
// Order by created_at DESC
query = query.Order("created_at DESC")
// Execute query
if err := query.Find(&tenants).Error; err != nil {
return nil, 0, err
}
return tenants, total, nil
}
// UpdateTenant updates tenant
func (r *tenantRepository) UpdateTenant(ctx context.Context, tenant *types.Tenant) error {
return r.db.WithContext(ctx).Model(&types.Tenant{}).Where("id = ?", tenant.ID).Updates(tenant).Error
+46
View File
@@ -280,3 +280,49 @@ func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error)
return tenantID, nil
}
// ListAllTenants lists all tenants (for users with cross-tenant access permission)
// This method returns all tenants without filtering, intended for admin users
func (s *tenantService) ListAllTenants(ctx context.Context) ([]*types.Tenant, error) {
tenants, err := s.repo.ListTenants(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return nil, err
}
logger.Infof(ctx, "All tenants list retrieved successfully, total: %d", len(tenants))
return tenants, nil
}
// SearchTenants searches tenants with pagination and filters
func (s *tenantService) SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error) {
tenants, total, err := s.repo.SearchTenants(ctx, keyword, tenantID, page, pageSize)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"keyword": keyword,
"tenantID": tenantID,
"page": page,
"pageSize": pageSize,
})
return nil, 0, err
}
logger.Infof(ctx, "Tenants search completed, keyword: %s, tenantID: %d, page: %d, pageSize: %d, total: %d, found: %d",
keyword, tenantID, page, pageSize, total, len(tenants))
return tenants, total, nil
}
// GetTenantByIDForUser gets a tenant by ID with permission check
// This method verifies that the user has permission to access the tenant
func (s *tenantService) GetTenantByIDForUser(ctx context.Context, tenantID uint64, userID string) (*types.Tenant, error) {
tenant, err := s.repo.GetTenantByID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
"user_id": userID,
})
return nil, err
}
return tenant, nil
}
+2
View File
@@ -102,6 +102,8 @@ type TenantConfig struct {
DefaultSessionName string `yaml:"default_session_name" json:"default_session_name"`
DefaultSessionTitle string `yaml:"default_session_title" json:"default_session_title"`
DefaultSessionDescription string `yaml:"default_session_description" json:"default_session_description"`
// EnableCrossTenantAccess enables cross-tenant access for users with permission
EnableCrossTenantAccess bool `yaml:"enable_cross_tenant_access" json:"enable_cross_tenant_access"`
}
// ModelConfig 模型配置
+141 -5
View File
@@ -20,20 +20,23 @@ import (
// Provides functionality for creating, retrieving, updating, and deleting tenants
// through the REST API endpoints
type TenantHandler struct {
service interfaces.TenantService
config *config.Config
service interfaces.TenantService
userService interfaces.UserService
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
// - config: Application configuration
//
// Returns a pointer to the newly created TenantHandler
func NewTenantHandler(service interfaces.TenantService, config *config.Config) *TenantHandler {
func NewTenantHandler(service interfaces.TenantService, userService interfaces.UserService, config *config.Config) *TenantHandler {
return &TenantHandler{
service: service,
config: config,
service: service,
userService: userService,
config: config,
}
}
@@ -234,6 +237,139 @@ func (h *TenantHandler) ListTenants(c *gin.Context) {
})
}
// ListAllTenants handles the HTTP request for retrieving a list of all tenants
// This endpoint requires cross-tenant access permission
// Parameters:
// - c: Gin context for the HTTP request
func (h *TenantHandler) ListAllTenants(c *gin.Context) {
ctx := c.Request.Context()
// Get current user from context
user, err := h.userService.GetCurrentUser(ctx)
if err != nil {
logger.Errorf(ctx, "Failed to get current user: %v", err)
c.Error(errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error()))
return
}
// Check if cross-tenant access is enabled
if h.config == nil || h.config.Tenant == nil || !h.config.Tenant.EnableCrossTenantAccess {
logger.Warnf(ctx, "Cross-tenant access is disabled, user: %s", user.ID)
c.Error(errors.NewForbiddenError("Cross-tenant access is disabled"))
return
}
// Check if user has permission
if !user.CanAccessAllTenants {
logger.Warnf(ctx, "User %s attempted to list all tenants without permission", user.ID)
c.Error(errors.NewForbiddenError("Insufficient permissions to access all tenants"))
return
}
tenants, err := h.service.ListAllTenants(ctx)
if err != nil {
// Check if this is an application-specific error
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to retrieve all tenants list: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to retrieve all tenants list").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"items": tenants,
},
})
}
// SearchTenants handles the HTTP request for searching tenants with pagination
// This endpoint requires cross-tenant access permission
// Query parameters:
// - keyword: search keyword (optional)
// - tenant_id: filter by tenant ID (optional)
// - page: page number (default: 1)
// - page_size: page size (default: 20)
func (h *TenantHandler) SearchTenants(c *gin.Context) {
ctx := c.Request.Context()
// Get current user from context
user, err := h.userService.GetCurrentUser(ctx)
if err != nil {
logger.Errorf(ctx, "Failed to get current user: %v", err)
c.Error(errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error()))
return
}
// Check if cross-tenant access is enabled
if h.config == nil || h.config.Tenant == nil || !h.config.Tenant.EnableCrossTenantAccess {
logger.Warnf(ctx, "Cross-tenant access is disabled, user: %s", user.ID)
c.Error(errors.NewForbiddenError("Cross-tenant access is disabled"))
return
}
// Check if user has permission
if !user.CanAccessAllTenants {
logger.Warnf(ctx, "User %s attempted to search tenants without permission", user.ID)
c.Error(errors.NewForbiddenError("Insufficient permissions to access all tenants"))
return
}
// Parse query parameters
keyword := c.Query("keyword")
tenantIDStr := c.Query("tenant_id")
pageStr := c.DefaultQuery("page", "1")
pageSizeStr := c.DefaultQuery("page_size", "20")
var tenantID uint64
if tenantIDStr != "" {
parsedID, err := strconv.ParseUint(tenantIDStr, 10, 64)
if err == nil {
tenantID = parsedID
}
}
page, err := strconv.Atoi(pageStr)
if err != nil || page < 1 {
page = 1
}
pageSize, err := strconv.Atoi(pageSizeStr)
if err != nil || pageSize < 1 {
pageSize = 20
}
if pageSize > 100 {
pageSize = 100 // Limit max page size
}
tenants, total, err := h.service.SearchTenants(ctx, keyword, tenantID, page, pageSize)
if err != nil {
// Check if this is an application-specific error
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to search tenants: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to search tenants").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"items": tenants,
"total": total,
"page": page,
"page_size": pageSize,
},
})
}
// AgentConfigRequest represents the request body for updating agent configuration
type AgentConfigRequest struct {
MaxIterations int `json:"max_iterations"`
+58 -5
View File
@@ -6,6 +6,7 @@ import (
"log"
"net/http"
"slices"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/config"
@@ -37,6 +38,24 @@ func isNoAuthAPI(path string, method string) bool {
return false
}
// canAccessTenant checks if a user can access a target tenant
func canAccessTenant(user *types.User, targetTenantID uint64, cfg *config.Config) bool {
// 1. 检查功能是否启用
if cfg == nil || cfg.Tenant == nil || !cfg.Tenant.EnableCrossTenantAccess {
return false
}
// 2. 检查用户权限
if !user.CanAccessAllTenants {
return false
}
// 3. 如果目标租户是用户自己的租户,允许访问
if user.TenantID == targetTenantID {
return true
}
// 4. 用户有跨租户权限,允许访问(具体验证在中间件中完成)
return true
}
// Auth 认证中间件
func Auth(
tenantService interfaces.TenantService,
@@ -63,10 +82,44 @@ func Auth(
user, err := userService.ValidateToken(c.Request.Context(), token)
if err == nil && user != nil {
// JWT Token认证成功
// 获取租户信息
tenant, err := tenantService.GetTenantByID(c.Request.Context(), user.TenantID)
// 检查是否有跨租户访问请求
targetTenantID := user.TenantID
tenantHeader := c.GetHeader("X-Tenant-ID")
if tenantHeader != "" {
// 解析目标租户ID
parsedTenantID, err := strconv.ParseUint(tenantHeader, 10, 64)
if err == nil {
// 检查用户是否有跨租户访问权限
if canAccessTenant(user, parsedTenantID, cfg) {
// 验证目标租户是否存在
targetTenant, err := tenantService.GetTenantByID(c.Request.Context(), parsedTenantID)
if err == nil && targetTenant != nil {
targetTenantID = parsedTenantID
log.Printf("User %s switching to tenant %d", user.ID, targetTenantID)
} else {
log.Printf("Error getting target tenant by ID: %v, tenantID: %d", err, parsedTenantID)
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid target tenant ID",
})
c.Abort()
return
}
} else {
// 用户没有权限访问目标租户
log.Printf("User %s attempted to access tenant %d without permission", user.ID, parsedTenantID)
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: insufficient permissions to access target tenant",
})
c.Abort()
return
}
}
}
// 获取租户信息(使用目标租户ID)
tenant, err := tenantService.GetTenantByID(c.Request.Context(), targetTenantID)
if err != nil {
log.Printf("Error getting tenant by ID: %v, tenantID: %d, userID: %s", err, user.TenantID, user.ID)
log.Printf("Error getting tenant by ID: %v, tenantID: %d, userID: %s", err, targetTenantID, user.ID)
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Unauthorized: invalid tenant",
})
@@ -75,13 +128,13 @@ func Auth(
}
// 存储用户和租户信息到上下文
c.Set(types.TenantIDContextKey.String(), user.TenantID)
c.Set(types.TenantIDContextKey.String(), targetTenantID)
c.Set(types.TenantInfoContextKey.String(), tenant)
c.Set("user", user)
c.Request = c.Request.WithContext(
context.WithValue(
context.WithValue(
context.WithValue(c.Request.Context(), types.TenantIDContextKey, user.TenantID),
context.WithValue(c.Request.Context(), types.TenantIDContextKey, targetTenantID),
types.TenantInfoContextKey, tenant,
),
"user", user,
+4
View File
@@ -256,6 +256,10 @@ func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler) {
// RegisterTenantRoutes 注册租户相关的路由
func RegisterTenantRoutes(r *gin.RouterGroup, handler *handler.TenantHandler) {
// 添加获取所有租户的路由(需要跨租户权限)
r.GET("/tenants/all", handler.ListAllTenants)
// 添加搜索租户的路由(需要跨租户权限,支持分页和搜索)
r.GET("/tenants/search", handler.SearchTenants)
// 租户路由组
tenantRoutes := r.Group("/tenants")
{
+8
View File
@@ -22,6 +22,12 @@ type TenantService interface {
UpdateAPIKey(ctx context.Context, id uint64) (string, error)
// ExtractTenantIDFromAPIKey extracts the tenant ID from the API key
ExtractTenantIDFromAPIKey(apiKey string) (uint64, error)
// ListAllTenants lists all tenants (for users with cross-tenant access permission)
ListAllTenants(ctx context.Context) ([]*types.Tenant, error)
// SearchTenants searches tenants with pagination and filters
SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error)
// GetTenantByIDForUser gets a tenant by ID with permission check
GetTenantByIDForUser(ctx context.Context, tenantID uint64, userID string) (*types.Tenant, error)
}
// TenantRepository defines the tenant repository interface
@@ -32,6 +38,8 @@ type TenantRepository interface {
GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error)
// ListTenants lists all tenants
ListTenants(ctx context.Context) ([]*types.Tenant, error)
// SearchTenants searches tenants with pagination and filters
SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error)
// UpdateTenant updates a tenant
UpdateTenant(ctx context.Context, tenant *types.Tenant) error
// DeleteTenant deletes a tenant
+20 -16
View File
@@ -22,6 +22,8 @@ type User struct {
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Whether the user is active
IsActive bool `json:"is_active" gorm:"default:true"`
// Whether the user can access all tenants (cross-tenant access)
CanAccessAllTenants bool `json:"can_access_all_tenants" gorm:"default:false"`
// Creation time of the user
CreatedAt time.Time `json:"created_at"`
// Last updated time of the user
@@ -89,26 +91,28 @@ type RegisterResponse struct {
// UserInfo represents user information for API responses
type UserInfo struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Avatar string `json:"avatar"`
TenantID uint64 `json:"tenant_id"`
IsActive bool `json:"is_active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Avatar string `json:"avatar"`
TenantID uint64 `json:"tenant_id"`
IsActive bool `json:"is_active"`
CanAccessAllTenants bool `json:"can_access_all_tenants"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// ToUserInfo converts User to UserInfo (without sensitive data)
func (u *User) ToUserInfo() *UserInfo {
return &UserInfo{
ID: u.ID,
Username: u.Username,
Email: u.Email,
Avatar: u.Avatar,
TenantID: u.TenantID,
IsActive: u.IsActive,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
ID: u.ID,
Username: u.Username,
Email: u.Email,
Avatar: u.Avatar,
TenantID: u.TenantID,
IsActive: u.IsActive,
CanAccessAllTenants: u.CanAccessAllTenants,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
}
}