-
Notifications
You must be signed in to change notification settings - Fork 32
/
middleware.go
65 lines (57 loc) · 1.38 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
55
56
57
58
59
60
61
62
63
64
65
package ginserver
import (
"github.com/gin-gonic/gin"
)
type (
// ErrorHandleFunc error handling function
ErrorHandleFunc func(*gin.Context, error)
// Config defines the config for Session middleware
Config struct {
// error handling when starting the session
ErrorHandleFunc ErrorHandleFunc
// keys stored in the context
TokenKey string
// defines a function to skip middleware.Returning true skips processing
// the middleware.
Skipper func(*gin.Context) bool
}
)
var (
// DefaultConfig is the default middleware config.
DefaultConfig = Config{
ErrorHandleFunc: func(ctx *gin.Context, err error) {
ctx.AbortWithError(500, err)
},
TokenKey: "github.com/go-oauth2/gin-server/access-token",
Skipper: func(_ *gin.Context) bool {
return false
},
}
)
// HandleTokenVerify Verify the access token of the middleware
func HandleTokenVerify(config ...Config) gin.HandlerFunc {
cfg := DefaultConfig
if len(config) > 0 {
cfg = config[0]
}
if cfg.ErrorHandleFunc == nil {
cfg.ErrorHandleFunc = DefaultConfig.ErrorHandleFunc
}
tokenKey := cfg.TokenKey
if tokenKey == "" {
tokenKey = DefaultConfig.TokenKey
}
return func(c *gin.Context) {
if cfg.Skipper != nil && cfg.Skipper(c) {
c.Next()
return
}
ti, err := gServer.ValidationBearerToken(c.Request)
if err != nil {
cfg.ErrorHandleFunc(c, err)
return
}
c.Set(tokenKey, ti)
c.Next()
}
}