Files
Horchposten/handlers/middleware.go
2026-03-08 14:44:50 +00:00

26 lines
707 B
Go

package handlers
import (
"crypto/subtle"
"net/http"
"github.com/labstack/echo/v4"
)
// APIKeyAuth returns middleware that validates the X-API-Key header
// against the provided key using constant-time comparison.
func APIKeyAuth(key string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
provided := c.Request().Header.Get("X-API-Key")
if provided == "" {
return c.JSON(http.StatusUnauthorized, echo.Map{"error": "missing API key"})
}
if subtle.ConstantTimeCompare([]byte(provided), []byte(key)) != 1 {
return c.JSON(http.StatusUnauthorized, echo.Map{"error": "invalid API key"})
}
return next(c)
}
}
}