50 lines
1.0 KiB
Go
50 lines
1.0 KiB
Go
package auth_middleware
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
|
|
"autolibrary.top/webserver/config"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func APIKeyAuth() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
cfg := config.GetConfig()
|
|
if !cfg.Backend.Auth.Required {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
apiKey := c.GetHeader("X-API-Key")
|
|
if apiKey == "" {
|
|
apiKey = c.Query("api_key")
|
|
}
|
|
|
|
// Check if API key is configured
|
|
expectedKey := cfg.Backend.Auth.Key
|
|
if expectedKey == "" || expectedKey == "null" {
|
|
log.Printf("[E] AUTH > API key not configured")
|
|
c.JSON(http.StatusInternalServerError, gin.H{
|
|
"code": http.StatusInternalServerError,
|
|
"msg": "AUTH > API key has not been configured on this server",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// Check if API key is valid
|
|
if apiKey == "" || apiKey != expectedKey {
|
|
log.Printf("[W] AUTH > invalid API key or key is missing")
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"msg": "AUTH > invalid API key or key is missing",
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|