37 lines
630 B
Go
37 lines
630 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const (
|
|
APIKeyHeader = "X-API-Key"
|
|
)
|
|
|
|
// APIKeyAuth creates a middleware that validates the API key
|
|
func APIKeyAuth(validAPIKey string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
apiKey := c.GetHeader(APIKeyHeader)
|
|
if apiKey == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
"success": false,
|
|
"error": "API key is required",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if apiKey != validAPIKey {
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
"success": false,
|
|
"error": "Invalid API key",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|