refactor: refactor API key middleware based on code review feedback

This commit is contained in:
Harold
2025-04-01 22:47:39 +02:00
parent ceaa90a7c7
commit cd74a96be2
4 changed files with 17 additions and 7 deletions

View File

@@ -1,18 +1,24 @@
package restapi
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func ApiKeyMiddleware(apiKey string) gin.HandlerFunc {
const APIKeyHeader = "X-API-Key"
func APIKeyMiddleware(apiKey string) gin.HandlerFunc {
return func(c *gin.Context) {
headerApiKey := c.GetHeader("X-API-Key")
headerApiKey := c.GetHeader(APIKeyHeader)
if headerApiKey == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing API Key"})
return
}
if headerApiKey != apiKey {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": fmt.Sprintf("Wrong or missing API Key")})
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Wrong API Key"})
return
}

View File

@@ -1,6 +1,8 @@
package restapi
import (
"log/slog"
"github.com/danielmiessler/fabric/core"
"github.com/gin-gonic/gin"
)
@@ -13,7 +15,9 @@ func Serve(registry *core.PluginRegistry, address string, apiKey string) (err er
r.Use(gin.Recovery())
if apiKey != "" {
r.Use(ApiKeyMiddleware(apiKey))
r.Use(APIKeyMiddleware(apiKey))
} else {
slog.Warn("Starting REST API server without API key authentication. This may pose security risks.")
}
// Register routes