feat: add simple optional api key management for protect routes in --serve mode

This commit is contained in:
Harold
2025-04-01 00:51:56 +02:00
committed by HaroldFinchIFT
parent 8d02f5b21d
commit 15a2eeadc9
4 changed files with 28 additions and 2 deletions

21
restapi/auth.go Normal file
View File

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

View File

@@ -5,13 +5,17 @@ import (
"github.com/gin-gonic/gin"
)
func Serve(registry *core.PluginRegistry, address string) (err error) {
func Serve(registry *core.PluginRegistry, address string, apiKey string) (err error) {
r := gin.New()
// Middleware
r.Use(gin.Logger())
r.Use(gin.Recovery())
if apiKey != "" {
r.Use(ApiKeyMiddleware(apiKey))
}
// Register routes
fabricDb := registry.Db
NewPatternsHandler(r, fabricDb.Patterns)