pcgamedb/server/middleware/auth.go

44 lines
837 B
Go
Raw Permalink Normal View History

2024-09-24 06:17:11 -04:00
package middleware
import (
"net/http"
"strings"
2024-11-20 06:09:04 -05:00
"pcgamedb/config"
2024-11-15 02:02:45 -05:00
2024-09-24 06:17:11 -04:00
"github.com/gin-gonic/gin"
)
func Auth() gin.HandlerFunc {
apiKey := config.Config.Server.SecretKey
if apiKey == "" {
return func(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{
"status": "error",
"message": "API key is not configured properly.",
})
c.Abort()
}
}
return func(c *gin.Context) {
auth := c.GetHeader("Authorization")
if auth == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"status": "error",
"message": "Unauthorized. No API key provided.",
})
c.Abort()
return
}
if strings.TrimPrefix(auth, "Bearer ") != apiKey {
c.JSON(http.StatusUnauthorized, gin.H{
"status": "error",
"message": "Unauthorized. Invalid API key.",
})
c.Abort()
return
}
c.Next()
}
}