Skip to content

Commit c0d33dc

Browse files
committed
feat: use env variable replace hardcoded hmacSecret
1 parent a0d3bcf commit c0d33dc

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

backend/domain/user/service/user_impl.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"encoding/base64"
2626
"encoding/json"
2727
"fmt"
28+
"os"
2829
"strconv"
2930
"strings"
3031
"time"
@@ -575,8 +576,19 @@ type Session struct {
575576
ExpiresAt time.Time `json:"expires_at"` // 过期时间
576577
}
577578

578-
// 用于签名的密钥(在实际应用中应从配置中读取或使用环境变量)
579-
var hmacSecret = []byte("opencoze-session-hmac-key")
579+
// 用于签名的密钥
580+
var hmacSecret []byte
581+
582+
func getHmacSecret() []byte {
583+
if hmacSecret == nil {
584+
secret := os.Getenv("secret")
585+
if secret == "" {
586+
secret = "opencoze-session-hmac-key" // 默认的会话密钥
587+
}
588+
hmacSecret = []byte(secret)
589+
}
590+
return hmacSecret
591+
}
580592

581593
// 生成安全的会话密钥
582594
func generateSessionKey(sessionID int64) (string, error) {
@@ -594,7 +606,7 @@ func generateSessionKey(sessionID int64) (string, error) {
594606
}
595607

596608
// 计算HMAC签名以确保完整性
597-
h := hmac.New(sha256.New, hmacSecret)
609+
h := hmac.New(sha256.New, getHmacSecret())
598610
h.Write(sessionData)
599611
signature := h.Sum(nil)
600612

@@ -623,7 +635,7 @@ func verifySessionKey(sessionKey string) (*Session, error) {
623635
signature := data[len(data)-32:]
624636

625637
// 验证签名
626-
h := hmac.New(sha256.New, hmacSecret)
638+
h := hmac.New(sha256.New, getHmacSecret())
627639
h.Write(sessionData)
628640
expectedSignature := h.Sum(nil)
629641

docker/.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ export LOG_LEVEL="debug"
44
export MAX_REQUEST_BODY_SIZE=1073741824
55
export SERVER_HOST="localhost${LISTEN_ADDR}"
66
export MINIO_PROXY_ENDPOINT=":8889"
7+
export SESSION_SECRET="opencoze-session-hmac-key"
78

89
# MySQL
910
export MYSQL_ROOT_PASSWORD=root

0 commit comments

Comments
 (0)