refactor: Improve Elasticsearch query construction and JWT secret retrieval

- Enhanced Elasticsearch query construction by safely building the query body using JSON marshaling, improving error handling for query parsing and marshaling.
- Updated JWT secret retrieval to securely generate a random secret if the environment variable is not set, ensuring better security practices.
This commit is contained in:
wizardchen
2025-11-25 23:58:14 +08:00
parent 016df3a4db
commit a0ada8bcdc
2 changed files with 42 additions and 14 deletions
@@ -885,18 +885,30 @@ func (e *elasticsearchRepository) querySourceBatch(ctx context.Context,
) ([]interface{}, error) {
log := logger.GetLogger(ctx)
// Build query request
filter := e.getBaseConds(retrieveParams)
query := fmt.Sprintf(`{
"query": %s,
"from": %d,
"size": %d
}`, filter, from, batchSize)
// Build query request safely
filterJSON := e.getBaseConds(retrieveParams)
var filter map[string]interface{}
if err := json.Unmarshal([]byte(filterJSON), &filter); err != nil {
log.Errorf("[ElasticsearchV7] Failed to parse base conditions: %v", err)
filter = map[string]interface{}{}
}
queryBody := map[string]interface{}{
"query": filter,
"from": from,
"size": batchSize,
}
queryBytes, err := json.Marshal(queryBody)
if err != nil {
log.Errorf("[ElasticsearchV7] Failed to marshal query body: %v", err)
return nil, err
}
// Execute query
response, err := e.client.Search(
e.client.Search.WithIndex(e.index),
e.client.Search.WithBody(strings.NewReader(query)),
e.client.Search.WithBody(strings.NewReader(string(queryBytes))),
e.client.Search.WithContext(ctx),
)
if err != nil {
+22 -6
View File
@@ -2,10 +2,13 @@ package service
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
@@ -17,14 +20,27 @@ import (
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// JWT secret key - in production this should be from environment variable
var (
jwtSecretOnce sync.Once
jwtSecret string
)
// getJwtSecret retrieves the JWT secret from the environment, falling back to a securely generated random secret.
func getJwtSecret() string {
jwtSecret := os.Getenv("JWT_SECRET")
if jwtSecret != "" {
return jwtSecret
}
return "your-secret-key"
jwtSecretOnce.Do(func() {
if envSecret := strings.TrimSpace(os.Getenv("JWT_SECRET")); envSecret != "" {
jwtSecret = envSecret
return
}
randomBytes := make([]byte, 32)
if _, err := rand.Read(randomBytes); err != nil {
panic(fmt.Sprintf("failed to generate JWT secret: %v", err))
}
jwtSecret = base64.StdEncoding.EncodeToString(randomBytes)
})
return jwtSecret
}
// userService implements the UserService interface