gocommon/ginutils/auth.go

35 lines
733 B
Go
Raw Normal View History

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)
}
}
}