-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
54 lines (48 loc) · 1.39 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package restful
import (
"github.com/gin-gonic/gin"
"github.com/justdomepaul/toolbox/config"
"github.com/justdomepaul/toolbox/definition"
"github.com/justdomepaul/toolbox/errorhandler"
"strings"
)
type GuarderValidator interface {
Verify(c *gin.Context, token string) error
}
func NewJWTGuarder(option config.JWT, validator GuarderValidator) *JWTGuarder {
return &JWTGuarder{
option: option,
validator: validator,
}
}
type JWTGuarder struct {
option config.JWT
validator GuarderValidator
}
// JWTGuarder method
func (j *JWTGuarder) JWTGuarder(whitelist ...string) gin.HandlerFunc {
return func(c *gin.Context) {
// skip if matching whitelist
for _, term := range whitelist {
if strings.HasPrefix(c.FullPath(), term) || strings.HasPrefix(c.Request.RequestURI, term) {
c.Next()
return
}
}
token := c.DefaultQuery(definition.QueryAuthKey, "")
if token == "" {
authorization := c.GetHeader(definition.AuthorizationKey)
if len(authorization) == 0 {
panic(errorhandler.NewErrInvalidArgument(errorhandler.ErrAuthorizationRequired))
}
if strings.HasPrefix(authorization, definition.AuthorizationType) {
token = strings.TrimPrefix(authorization, definition.AuthorizationType)
} else {
panic(errorhandler.NewErrInvalidArgument(errorhandler.ErrAuthorizationTypeBearer))
}
}
if err := j.validator.Verify(c, token); err != nil {
panic(err)
}
}
}