VOAIDF / auth.go
KaThaNg's picture
Upload 12 files
a0e64e6 verified
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
const APIKeyHeaderName = "X-API-Key"
// APIKeyAuthMiddleware creates a Gin middleware for API key authentication
func APIKeyAuthMiddleware(validKeys map[string]bool) gin.HandlerFunc {
return func(c *gin.Context) {
apiKey := c.GetHeader(APIKeyHeaderName)
if apiKey == "" {
// Giữ lại: Log cảnh báo quan trọng về thiếu API Key
log.Printf("WARN: [%s] API Key missing in header '%s'", c.ClientIP(), APIKeyHeaderName)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"type": "error",
"error": gin.H{
"type": "authentication_error",
"message": "API Key required in header '" + APIKeyHeaderName + "'",
},
})
return
}
if _, isValid := validKeys[apiKey]; !isValid {
// Giữ lại: Log cảnh báo quan trọng về API Key không hợp lệ
log.Printf("WARN: [%s] Invalid API Key received (length: %d)", c.ClientIP(), len(apiKey))
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"type": "error",
"error": gin.H{
"type": "authentication_error",
"message": "Invalid or expired API Key",
},
})
return
}
// Đã được comment từ trước, tốt cho việc giảm log không cần thiết
// log.Printf("INFO: [%s] Valid API key received (length: %d)", c.ClientIP(), len(apiKey))
c.Next() // Proceed to the next handler
}
}