feat: Add API key middleware and update configuration to support API key validation

This commit is contained in:
2025-03-11 17:20:39 +00:00
parent 165432208c
commit c08da6fc92
5 changed files with 46 additions and 3 deletions
@@ -0,0 +1,35 @@
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/timetracker/backend/internal/api/utils"
"github.com/timetracker/backend/internal/config"
)
// APIKeyMiddleware checks for a valid API key if configured
func APIKeyMiddleware(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
// Skip if no API key is configured
if cfg.APIKey == "" {
c.Next()
return
}
// Get API key from header
apiKey := c.GetHeader("X-API-Key")
if apiKey == "" {
utils.UnauthorizedResponse(c, "API key is required")
c.Abort()
return
}
// Validate API key
if apiKey != cfg.APIKey {
utils.UnauthorizedResponse(c, "Invalid API key")
c.Abort()
return
}
c.Next()
}
}