forked from revel/revel
/
session.go
58 lines (48 loc) · 1.35 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
package revel
import (
"net/http"
"net/url"
"strings"
)
// A signed cookie (and thus limited to 4kb in size).
// Restriction: Keys may not have a colon in them.
type Session map[string]string
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 {
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)
}