forked from bearded-web/bearded
/
session.go
154 lines (134 loc) · 3.68 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package filters
import (
"fmt"
"net/http"
"time"
"sync"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni"
"github.com/emicklei/go-restful"
"github.com/gorilla/securecookie"
)
// name for key in restful attributes
var AttrSessionKey = "__session"
type Session struct {
store map[string]string
modified bool
m sync.RWMutex
}
func NewSession() *Session {
return &Session{
store: map[string]string{},
}
}
func (s *Session) Set(key, val string) {
s.m.Lock()
s.modified = true
s.store[key] = val
s.m.Unlock()
}
func (s *Session) Get(key string) (string, bool) {
s.m.RLock()
val, ok := s.store[key]
s.m.RUnlock()
return val, ok
}
func (s *Session) Del(key string) {
if _, ok := s.Get(key); ok {
s.m.Lock()
s.modified = true
delete(s.store, key)
s.m.Unlock()
}
}
func (s *Session) IsModified() bool {
return s.modified
}
// Options stores configuration for a session or session store.
//
// Fields are a subset of http.Cookie fields.
type CookieOpts struct {
Path string
Domain string
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'.
// MaxAge>0 means Max-Age attribute present and given in seconds.
MaxAge int
Secure bool
HttpOnly bool
}
func SessionCookieFilter(cookieName string, opts *CookieOpts, keyPairs ...string) restful.FilterFunction {
keyPairsBytes := [][]byte{}
for _, key := range keyPairs {
keyPairsBytes = append(keyPairsBytes, []byte(key))
}
codecs := securecookie.CodecsFromPairs(keyPairsBytes...)
return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
session := NewSession()
if cookie, err := req.Request.Cookie(cookieName); err == nil {
if err = securecookie.DecodeMulti(cookieName, cookie.Value, &session.store, codecs...); err == nil {
} else {
logrus.Warn(err)
}
} else {
if err != http.ErrNoCookie {
logrus.Warn(err)
}
}
req.SetAttribute(AttrSessionKey, session)
// I don't know how to write cookie in restful, so I use underneath negroni before hook
resp.ResponseWriter.(negroni.ResponseWriter).Before(func(rw negroni.ResponseWriter) {
if !session.IsModified() {
return
}
if encoded, err := securecookie.EncodeMulti(cookieName, session.store, codecs...); err == nil {
cookie := NewCookie(cookieName, encoded, opts)
http.SetCookie(rw, cookie)
}
})
chain.ProcessFilter(req, resp)
}
}
func SessionFilterMock(session *Session) restful.FilterFunction {
return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
req.SetAttribute(AttrSessionKey, session)
chain.ProcessFilter(req, resp)
}
}
// Get session from restful.Request attribute or panic
func GetSession(req *restful.Request) *Session {
m := req.Attribute(AttrSessionKey)
if m == nil {
panic("GetSession attribute is nil")
}
session, ok := m.(*Session)
if !ok {
panic(fmt.Sprintf("GetSession attribute isn't a session type, but %#v", m))
}
return session
}
// NewCookie returns an http.Cookie with the options set. It also sets
// the Expires field calculated based on the MaxAge value, for Internet
// Explorer compatibility.
func NewCookie(name, value string, options *CookieOpts) *http.Cookie {
if options == nil {
options = &CookieOpts{}
}
cookie := &http.Cookie{
Name: name,
Value: value,
Path: options.Path,
Domain: options.Domain,
MaxAge: options.MaxAge,
Secure: options.Secure,
HttpOnly: options.HttpOnly,
}
if options.MaxAge > 0 {
d := time.Duration(options.MaxAge) * time.Second
cookie.Expires = time.Now().Add(d)
} else if options.MaxAge < 0 {
// Set it to the past to expire now.
cookie.Expires = time.Unix(1, 0)
}
return cookie
}