forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cookie.go
69 lines (58 loc) · 1.37 KB
/
cookie.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
package csrf
import (
"net/http"
"github.com/pborman/uuid"
)
type cookieCsrf struct {
name string
path string
domain string
secure bool
httponly bool
}
// NewCookieCSRF stores random CSRF tokens in a cookie created with the given options.
// Empty CSRF tokens or tokens that do not match the value of the cookie on the request
// are rejected.
func NewCookieCSRF(name, path, domain string, secure, httponly bool) CSRF {
return &cookieCsrf{
name: name,
path: path,
domain: domain,
secure: secure,
httponly: httponly,
}
}
// Generate implements the CSRF interface
func (c *cookieCsrf) Generate(w http.ResponseWriter, req *http.Request) (string, error) {
cookie, err := req.Cookie(c.name)
if err == nil && len(cookie.Value) > 0 {
return cookie.Value, nil
}
cookie = &http.Cookie{
Name: c.name,
Value: uuid.NewUUID().String(),
Path: c.path,
Domain: c.domain,
Secure: c.secure,
HttpOnly: c.httponly,
}
http.SetCookie(w, cookie)
return cookie.Value, nil
}
// Check implements the CSRF interface
func (c *cookieCsrf) Check(req *http.Request, value string) (bool, error) {
if len(value) == 0 {
return false, nil
}
cookie, err := req.Cookie(c.name)
if err == http.ErrNoCookie {
return false, nil
}
if err != nil {
return false, err
}
if cookie.Value != value {
return false, nil
}
return true, nil
}