woj-server/internal/web/jwt/middleware.go

47 lines
974 B
Go
Raw Normal View History

2022-09-17 10:10:53 +08:00
package jwt
import (
2023-07-14 21:47:11 +08:00
"git.0x7f.app/WOJ/woj-server/internal/e"
2023-07-15 16:19:49 +08:00
"git.0x7f.app/WOJ/woj-server/internal/model"
2022-09-17 10:10:53 +08:00
"github.com/gin-gonic/gin"
"strings"
)
func (s *service) Handler(forced bool) gin.HandlerFunc {
2022-09-17 10:10:53 +08:00
return func(c *gin.Context) {
2023-07-15 16:19:49 +08:00
claim, status := func() (*model.Claim, e.Status) {
tokenHeader := c.GetHeader("Authorization")
if tokenHeader == "" {
return nil, e.TokenEmpty
}
2022-09-17 10:10:53 +08:00
token := tokenHeader
const tokenPrefix = "bearer "
if strings.HasPrefix(strings.ToLower(tokenHeader), tokenPrefix) {
// don't force "bearer" prefix
token = tokenHeader[len(tokenPrefix):]
}
claim, status := s.ParseToken(token)
if status != e.Success {
return nil, status
}
2022-09-17 10:10:53 +08:00
if !s.Validate(claim) {
return nil, e.TokenRevoked
}
return claim, e.Success
}()
if status == e.Success {
c.Set("claim", claim)
}
if forced && status != e.Success {
e.Pong[any](c, status, nil)
c.Abort()
} else {
c.Next()
}
2022-09-17 10:10:53 +08:00
}
}