feat: add scoped tenant api keys
This commit is contained in:
@@ -3,12 +3,10 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
@@ -116,27 +114,8 @@ func (r *tenantRepository) SearchTenants(ctx context.Context, keyword string, te
|
||||
}
|
||||
|
||||
// UpdateTenant updates tenant.
|
||||
// Handles api_key carefully because db.Updates() does not trigger the BeforeSave
|
||||
// GORM hook. Without this guard, AfterFind-decrypted plaintext would silently
|
||||
// overwrite the encrypted value in the database.
|
||||
//
|
||||
// Strategy:
|
||||
// - enc:v1:… (pre-encrypted by CreateTenant / UpdateAPIKey): write as-is.
|
||||
// - plaintext (decrypted by AfterFind): blank it so GORM skips the column.
|
||||
// - SYSTEM_AES_KEY not set: write as-is (encryption disabled).
|
||||
//
|
||||
// The caller's in-memory struct is always restored after the write.
|
||||
func (r *tenantRepository) UpdateTenant(ctx context.Context, tenant *types.Tenant) error {
|
||||
origAPIKey := tenant.APIKey
|
||||
if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" &&
|
||||
!strings.HasPrefix(tenant.APIKey, utils.EncPrefix) {
|
||||
// Plaintext from AfterFind — do not write back; let the DB keep its
|
||||
// existing encrypted value untouched.
|
||||
tenant.APIKey = ""
|
||||
}
|
||||
err := r.db.WithContext(ctx).Model(&types.Tenant{}).Where("id = ?", tenant.ID).Updates(tenant).Error
|
||||
tenant.APIKey = origAPIKey
|
||||
return err
|
||||
return r.db.WithContext(ctx).Model(&types.Tenant{}).Where("id = ?", tenant.ID).Updates(tenant).Error
|
||||
}
|
||||
|
||||
// DeleteTenant soft-deletes the tenant and every active membership row
|
||||
|
||||
Reference in New Issue
Block a user