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
|
|
|
|
|
|
|
|
func ValidateAPIKey(r *http.Request) bool {
|
2026-09-21 10:50:03 +08:00
|
|
|
keys := setting.GetAuthAPIKeys()
|
|
|
|
|
if len(keys) == 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-09-21 10:50:03 +08:00
|
|
|
for _, validKey := range keys {
|
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,
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
}
|