feat: Add API key middleware and update configuration to support API key validation
This commit is contained in:
@@ -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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user