gocommon/ginutils/auth.go
Matthieu 'JP' DERASSE 959f245c01
All checks were successful
continuous-integration/drone/push Build is passing
feat(ginutils): Add ginutils that is a toolbox for gin gonic
2023-08-11 18:39:40 +00:00

35 lines
733 B
Go

package ginutils
import (
"github.com/gin-gonic/gin"
)
// SimpleTokens is a middleware that will just check if a token match X-TOKEN header.
func SimpleTokens(tokens []string, forbiddenHandler gin.HandlerFunc) gin.HandlerFunc {
if forbiddenHandler == nil {
forbiddenHandler = func(c *gin.Context) {
c.AbortWithStatusJSON(403, map[string]string{
"message": "Forbidden",
"debugId": c.GetString(string(ContextKey_RequestID)),
})
}
}
return func(c *gin.Context) {
requestToken := c.GetHeader(string(HeaderKey_Token))
isAuthorized := false
for _, key := range tokens {
if key == requestToken {
isAuthorized = true
}
}
if isAuthorized {
c.Next()
} else {
forbiddenHandler(c)
}
}
}