-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauthcopy.go
87 lines (72 loc) · 1.69 KB
/
authcopy.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package authcopy
import (
"github.com/devopsfaith/krakend/config"
"github.com/devopsfaith/krakend/logging"
"github.com/gin-gonic/gin"
)
const authHeader = "Authorization"
const Namespace = "github.com/zean00/authcopy"
//CopyConfig authcopy config
type CopyConfig struct {
CookieKey string
QueryKey string
Overwrite bool
}
//New create middleware
func New(logger logging.Logger, config config.ExtraConfig) gin.HandlerFunc {
cfg := configGetter(logger, config)
if cfg == nil {
logger.Info("[authcopy] Empty config")
return func(c *gin.Context) {
c.Next()
}
}
return func(c *gin.Context) {
if token := c.Request.Header.Get(authHeader); token != "" && !cfg.Overwrite {
c.Next()
return
}
cookie, err := c.Request.Cookie(cfg.CookieKey)
if err == nil {
logger.Debug("[authcopy] Copying from cookie")
c.Request.Header.Set(authHeader, "Bearer "+cookie.Value)
}
query := c.Request.URL.Query().Get(cfg.QueryKey)
if query != "" {
logger.Debug("[authcopy] Copying from query")
c.Request.Header.Set(authHeader, "Bearer "+query)
val := c.Request.URL.Query()
val.Del(cfg.QueryKey)
c.Request.URL.RawQuery = val.Encode()
}
c.Next()
}
}
func configGetter(logger logging.Logger, config config.ExtraConfig) *CopyConfig {
v, ok := config[Namespace]
if !ok {
return nil
}
tmp, ok := v.(map[string]interface{})
if !ok {
return nil
}
cfg := new(CopyConfig)
cfg.Overwrite = false
ck, ok := tmp["cookie_key"].(string)
if ok {
cfg.CookieKey = ck
}
qk, ok := tmp["query_key"].(string)
if ok {
cfg.QueryKey = qk
}
ow, ok := tmp["overwrite"].(bool)
if ok {
cfg.Overwrite = ow
}
if cfg.CookieKey == "" && cfg.QueryKey == "" {
return nil
}
return cfg
}