pcgamedb/server/middleware/auth.go
nite07 304517e241
Some checks failed
release / goreleaser (push) Failing after 2m23s
docker / prepare-and-build (push) Failing after 2m55s
trans to private
2024-11-20 19:09:04 +08:00

44 lines
837 B
Go

package middleware
import (
"net/http"
"strings"
"pcgamedb/config"
"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()
}
}