2026-06-27 14:31:10 +08:00
|
|
|
package middleware
|
2026-05-23 20:32:12 +08:00
|
|
|
|
|
|
|
|
import (
|
2026-05-24 15:33:27 +08:00
|
|
|
"crypto/subtle"
|
2026-05-23 20:32:12 +08:00
|
|
|
"encoding/json"
|
|
|
|
|
"net/http"
|
|
|
|
|
"strings"
|
|
|
|
|
|
2026-06-30 20:55:56 +08:00
|
|
|
"github.com/volcano-tts/tts-api/setting"
|
|
|
|
|
)
|
2026-05-23 20:32:12 +08:00
|
|
|
|
2026-06-30 20:55:56 +08:00
|
|
|
// InitAPIKeys 已在 setting.InitAuthConfig 中完成,这里保留为 no-op 以维持现有调用顺序。
|
|
|
|
|
// 实际鉴权逻辑直接读 setting.Auth.APIKeys。
|
2026-05-23 20:32:12 +08:00
|
|
|
func InitAPIKeys() {
|
2026-06-30 20:55:56 +08:00
|
|
|
// 配置由 setting 包统一加载,日志也由 setting.LogStartupSummary 输出。
|
|
|
|
|
_ = setting.Auth
|
2026-05-23 20:32:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func ValidateAPIKey(r *http.Request) bool {
|
2026-06-30 20:55:56 +08:00
|
|
|
if len(setting.Auth.APIKeys) == 0 {
|
2026-05-23 20:32:12 +08:00
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
authHeader := r.Header.Get("Authorization")
|
|
|
|
|
if authHeader == "" {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if !strings.HasPrefix(authHeader, "Bearer ") {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
token := strings.TrimPrefix(authHeader, "Bearer ")
|
2026-06-30 20:55:56 +08:00
|
|
|
for _, validKey := range setting.Auth.APIKeys {
|
2026-05-24 15:33:27 +08:00
|
|
|
if subtle.ConstantTimeCompare([]byte(token), []byte(validKey)) == 1 {
|
2026-05-23 20:32:12 +08:00
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func SendJSONError(w http.ResponseWriter, statusCode int, message string, errType string, code string) {
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
|
w.WriteHeader(statusCode)
|
|
|
|
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
|
|
|
"error": map[string]interface{}{
|
|
|
|
|
"message": message,
|
|
|
|
|
"type": errType,
|
|
|
|
|
"code": code,
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
}
|