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"
|
|
|
|
)
|
|
|
|
|
2022-10-22 17:38:39 +08:00
|
|
|
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) {
|
2022-10-22 17:38:39 +08:00
|
|
|
tokenHeader := c.GetHeader("Authorization")
|
2023-07-15 18:28:55 +08:00
|
|
|
if tokenHeader == "" {
|
2022-10-22 17:38:39 +08:00
|
|
|
return nil, e.TokenEmpty
|
|
|
|
}
|
2022-09-17 10:10:53 +08:00
|
|
|
|
2023-07-15 18:28:55 +08:00
|
|
|
token := tokenHeader
|
|
|
|
const tokenPrefix = "bearer "
|
|
|
|
if strings.HasPrefix(strings.ToLower(tokenHeader), tokenPrefix) {
|
|
|
|
// don't force "bearer" prefix
|
|
|
|
token = tokenHeader[len(tokenPrefix):]
|
|
|
|
}
|
|
|
|
|
2022-10-22 17:38:39 +08:00
|
|
|
claim, status := s.ParseToken(token)
|
|
|
|
if status != e.Success {
|
|
|
|
return nil, status
|
|
|
|
}
|
2022-09-17 10:10:53 +08:00
|
|
|
|
2022-10-22 17:38:39 +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 {
|
2023-12-22 15:19:13 +08:00
|
|
|
e.Pong[any](c, status, nil)
|
2022-09-17 18:10:06 +08:00
|
|
|
c.Abort()
|
2022-10-22 17:38:39 +08:00
|
|
|
} else {
|
|
|
|
c.Next()
|
2022-09-17 18:10:06 +08:00
|
|
|
}
|
2022-09-17 10:10:53 +08:00
|
|
|
}
|
|
|
|
}
|