forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
84 lines (71 loc) · 1.93 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package revel
import (
"github.com/streadway/simpleuuid"
"net/http"
"net/url"
"strings"
"time"
)
// A signed cookie (and thus limited to 4kb in size).
// Restriction: Keys may not have a colon in them.
type Session map[string]string
const (
SESSION_ID_KEY = "_ID"
)
// Return a UUID identifying this session.
func (s Session) Id() string {
if uuidStr, ok := s[SESSION_ID_KEY]; ok {
return uuidStr
}
uuid, err := simpleuuid.NewTime(time.Now())
if err != nil {
panic(err) // I don't think this can actually happen.
}
s[SESSION_ID_KEY] = uuid.String()
return s[SESSION_ID_KEY]
}
type SessionPlugin struct{ EmptyPlugin }
func (p SessionPlugin) BeforeRequest(c *Controller) {
c.Session = restoreSession(c.Request.Request)
}
func (p SessionPlugin) AfterRequest(c *Controller) {
// Store the session (and sign it).
var sessionValue string
for key, value := range c.Session {
if strings.ContainsAny(key, ":\x00") {
panic("Session keys may not have colons or null bytes")
}
if strings.Contains(value, "\x00") {
panic("Session values may not have null bytes")
}
sessionValue += "\x00" + key + ":" + value + "\x00"
}
sessionData := url.QueryEscape(sessionValue)
c.SetCookie(&http.Cookie{
Name: CookiePrefix + "_SESSION",
Value: Sign(sessionData) + "-" + sessionData,
Path: "/",
})
}
func restoreSession(req *http.Request) Session {
session := make(map[string]string)
cookie, err := req.Cookie(CookiePrefix + "_SESSION")
if err != nil {
return Session(session)
}
// Separate the data from the signature.
hyphen := strings.Index(cookie.Value, "-")
if hyphen == -1 || hyphen >= len(cookie.Value)-1 {
return Session(session)
}
sig, data := cookie.Value[:hyphen], cookie.Value[hyphen+1:]
// Verify the signature.
if Sign(data) != sig {
INFO.Println("Session cookie signature failed")
return Session(session)
}
ParseKeyValueCookie(data, func(key, val string) {
session[key] = val
})
return Session(session)
}