forked from tommy351/gin-csrf
-
Notifications
You must be signed in to change notification settings - Fork 38
/
csrf.go
135 lines (106 loc) · 2.43 KB
/
csrf.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package csrf
import (
"crypto/sha1"
"encoding/base64"
"errors"
"io"
"github.com/dchest/uniuri"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
const (
csrfSecret = "csrfSecret"
csrfSalt = "csrfSalt"
csrfToken = "csrfToken"
)
var defaultIgnoreMethods = []string{"GET", "HEAD", "OPTIONS"}
var defaultErrorFunc = func(c *gin.Context) {
panic(errors.New("CSRF token mismatch"))
}
var defaultTokenGetter = func(c *gin.Context) string {
r := c.Request
if t := r.FormValue("_csrf"); len(t) > 0 {
return t
} else if t := r.URL.Query().Get("_csrf"); len(t) > 0 {
return t
} else if t := r.Header.Get("X-CSRF-TOKEN"); len(t) > 0 {
return t
} else if t := r.Header.Get("X-XSRF-TOKEN"); len(t) > 0 {
return t
}
return ""
}
// Options stores configurations for a CSRF middleware.
type Options struct {
Secret string
IgnoreMethods []string
ErrorFunc gin.HandlerFunc
TokenGetter func(c *gin.Context) string
}
func tokenize(secret, salt string) string {
h := sha1.New()
io.WriteString(h, salt+"-"+secret)
hash := base64.URLEncoding.EncodeToString(h.Sum(nil))
return hash
}
func inArray(arr []string, value string) bool {
inarr := false
for _, v := range arr {
if v == value {
inarr = true
break
}
}
return inarr
}
// Middleware validates CSRF token.
func Middleware(options Options) gin.HandlerFunc {
ignoreMethods := options.IgnoreMethods
errorFunc := options.ErrorFunc
tokenGetter := options.TokenGetter
if ignoreMethods == nil {
ignoreMethods = defaultIgnoreMethods
}
if errorFunc == nil {
errorFunc = defaultErrorFunc
}
if tokenGetter == nil {
tokenGetter = defaultTokenGetter
}
return func(c *gin.Context) {
session := sessions.Default(c)
c.Set(csrfSecret, options.Secret)
if inArray(ignoreMethods, c.Request.Method) {
c.Next()
return
}
salt, ok := session.Get(csrfSalt).(string)
if !ok || len(salt) == 0 {
errorFunc(c)
return
}
token := tokenGetter(c)
if tokenize(options.Secret, salt) != token {
errorFunc(c)
return
}
c.Next()
}
}
// GetToken returns a CSRF token.
func GetToken(c *gin.Context) string {
session := sessions.Default(c)
secret := c.MustGet(csrfSecret).(string)
if t, ok := c.Get(csrfToken); ok {
return t.(string)
}
salt, ok := session.Get(csrfSalt).(string)
if !ok {
salt = uniuri.New()
session.Set(csrfSalt, salt)
session.Save()
}
token := tokenize(secret, salt)
c.Set(csrfToken, token)
return token
}