|
|
package main |
|
|
|
|
|
import ( |
|
|
"log" |
|
|
"net/http" |
|
|
|
|
|
"github.com/gin-gonic/gin" |
|
|
) |
|
|
|
|
|
const APIKeyHeaderName = "X-API-Key" |
|
|
|
|
|
|
|
|
func APIKeyAuthMiddleware(validKeys map[string]bool) gin.HandlerFunc { |
|
|
return func(c *gin.Context) { |
|
|
apiKey := c.GetHeader(APIKeyHeaderName) |
|
|
|
|
|
if apiKey == "" { |
|
|
|
|
|
log.Printf("WARN: [%s] API Key missing in header '%s'", c.ClientIP(), APIKeyHeaderName) |
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ |
|
|
"type": "error", |
|
|
"error": gin.H{ |
|
|
"type": "authentication_error", |
|
|
"message": "API Key required in header '" + APIKeyHeaderName + "'", |
|
|
}, |
|
|
}) |
|
|
return |
|
|
} |
|
|
|
|
|
if _, isValid := validKeys[apiKey]; !isValid { |
|
|
|
|
|
log.Printf("WARN: [%s] Invalid API Key received (length: %d)", c.ClientIP(), len(apiKey)) |
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ |
|
|
"type": "error", |
|
|
"error": gin.H{ |
|
|
"type": "authentication_error", |
|
|
"message": "Invalid or expired API Key", |
|
|
}, |
|
|
}) |
|
|
return |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
c.Next() |
|
|
} |
|
|
} |
|
|
|