forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
69 lines (54 loc) · 1.4 KB
/
session.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"
"github.com/openshift/origin/pkg/auth/server/session"
)
const CSRFKey = "csrf"
type sessionCsrf struct {
store session.Store
name string
}
// NewSessionCSRF stores CSRF tokens in a session with the given name.
// Empty CSRF tokens or tokens that do not match the value in the session are rejected.
func NewSessionCSRF(store session.Store, name string) CSRF {
return &sessionCsrf{
store: store,
name: name,
}
}
// Generate implements the CSRF interface
func (c *sessionCsrf) Generate(w http.ResponseWriter, req *http.Request) (string, error) {
session, err := c.store.Get(req, c.name)
if err != nil {
return "", err
}
values := session.Values()
csrfString, ok := values[CSRFKey].(string)
if ok && csrfString != "" {
return csrfString, nil
}
csrfString = uuid.NewUUID().String()
values[CSRFKey] = csrfString
// TODO: defer save until response is written?
if err = c.store.Save(w, req); err != nil {
return "", err
}
return csrfString, nil
}
// Check implements the CSRF interface
func (c *sessionCsrf) Check(req *http.Request, value string) (bool, error) {
if len(value) == 0 {
return false, nil
}
session, err := c.store.Get(req, c.name)
if err != nil {
return false, err
}
values := session.Values()
csrfString, ok := values[CSRFKey].(string)
if ok && csrfString == value {
return true, nil
}
return false, nil
}