36 lines
732 B
Go
36 lines
732 B
Go
package middleware
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/timetracker/backend/internal/api/responses"
|
|
"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 == "" {
|
|
responses.UnauthorizedResponse(c, "API key is required")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// Validate API key
|
|
if apiKey != cfg.APIKey {
|
|
responses.UnauthorizedResponse(c, "Invalid API key")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|