forked from hoisie/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxsrf.go
51 lines (44 loc) · 1.14 KB
/
xsrf.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
// XSRF support
// call web.SetXSRFOption to setup option
// call XSRFFormField to get a hidden form field, then add to the form
// before process POST request, use XSRFValidate to validate _xsrf form value
package web
import (
"net/http"
"time"
"code.google.com/p/xsrftoken"
)
func getXSRFToken(server *Server, ctx *Context) {
if token, ok := ctx.GetSecureCookie("_xsrf"); ok && token != "" {
ctx.XSRFToken = token
} else {
if ctx.Server.XSRFGetUid == nil {
return
}
uid := ctx.Server.XSRFGetUid(ctx)
if uid == "" {
return
}
ctx.XSRFToken = xsrftoken.Generate(ctx.Server.Config.XSRFSecret, uid, "POST")
ctx.SetSecureCookie("_xsrf", ctx.XSRFToken, int64(xsrftoken.Timeout/time.Second))
}
}
func XSRFValidate(ctx *Context) bool {
if ctx.XSRFToken == "" {
return false
}
if ctx.XSRFToken == XSRFGetFormToken(ctx.Request) {
return true
}
return false
}
func XSRFFormField(ctx *Context) string {
return "<input type=\"hidden\" name=\"_xsrf\" value=\"" +
ctx.XSRFToken + "\"/>"
}
func XSRFGetFormToken(r *http.Request) string {
if len(r.PostForm) == 0 {
r.ParseMultipartForm(32 << 20)
}
return r.Form.Get("_xsrf")
}