gocommon/ginutils/auth.go

34 lines
737 B
Go
Raw Permalink Normal View History

package ginutils
import (
2023-08-21 07:08:54 +00:00
"git.dev.m-and-m.ovh/mderasse/gocommon/aerr"
"git.dev.m-and-m.ovh/mderasse/gocommon/constant"
"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) {
2023-08-21 07:08:54 +00:00
errorHandler(c, aerr.NewForbidden())
}
}
return func(c *gin.Context) {
2023-08-21 07:08:54 +00:00
requestToken := c.GetHeader(string(constant.HeaderKey_Token))
isAuthorized := false
for _, key := range tokens {
if key == requestToken {
isAuthorized = true
}
}
if isAuthorized {
c.Next()
} else {
forbiddenHandler(c)
}
}
}