mirror of
https://github.com/danielmiessler/Fabric.git
synced 2026-02-12 23:15:05 -05:00
refactor: refactor API key middleware based on code review feedback
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user