From c89fd5da98781031499d85a9b1bdab5726726d28 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 29 Apr 2026 19:43:25 +0800 Subject: [PATCH] fix(tenant): return plaintext API key after create/reset CreateTenant and UpdateAPIKey both overwrote tenant.APIKey with the AES-encrypted ciphertext before returning, causing the UI to display "enc:v1:..." right after generating or resetting an API key. Save the plaintext in a local variable, encrypt only the value handed to UpdateTenant, and return the plaintext to callers. Subsequent reads via GetTenantByID continue to rely on the AfterFind hook for transparent decryption, so this only affects the initial write-back path. --- internal/application/service/tenant.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/internal/application/service/tenant.go b/internal/application/service/tenant.go index 1da13d8f..1e115e30 100644 --- a/internal/application/service/tenant.go +++ b/internal/application/service/tenant.go @@ -75,7 +75,8 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant) } logger.Infof(ctx, "Tenant created successfully, ID: %d, generating official API Key", tenant.ID) - tenant.APIKey = s.generateApiKey(tenant.ID) + plaintextAPIKey := s.generateApiKey(tenant.ID) + tenant.APIKey = plaintextAPIKey // Manually encrypt APIKey before update, because db.Updates() does not trigger BeforeSave hook if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" { @@ -92,6 +93,9 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant) return nil, err } + // Restore plaintext for the response so callers don't see enc:v1: ciphertext. + tenant.APIKey = plaintextAPIKey + logger.Infof(ctx, "Tenant creation and update completed, ID: %d, name: %s", tenant.ID, tenant.Name) return tenant, nil } @@ -218,7 +222,8 @@ func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, er } logger.Infof(ctx, "Generating new API Key for tenant, ID: %d", id) - tenant.APIKey = s.generateApiKey(tenant.ID) + plaintextAPIKey := s.generateApiKey(tenant.ID) + tenant.APIKey = plaintextAPIKey // Manually encrypt APIKey before update, because db.Updates() does not trigger BeforeSave hook if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" { @@ -235,7 +240,7 @@ func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, er } logger.Infof(ctx, "Tenant API Key updated successfully, ID: %d", id) - return tenant.APIKey, nil + return plaintextAPIKey, nil } // generateApiKey generates a secure API key for tenant authentication