-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsessionstore.go
274 lines (238 loc) · 6.48 KB
/
sessionstore.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package sessionstore
import (
"crypto/rand"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"sync"
"time"
)
type SessionManager struct {
SessionName string
Sessions []*Session
mut sync.RWMutex
}
type MessageType string
type Message struct {
MessageType MessageType
Content string
}
type Session struct {
Id string
Lifetime time.Time
Vars map[string]string
Message Message
mut sync.RWMutex
}
// NewManager creates and returns a new *SessionManager
func NewManager(sn string) *SessionManager {
return &SessionManager{
SessionName: sn,
Sessions: make([]*Session, 0),
}
}
func NewManagerFromFile(file string) (*SessionManager, error) {
m := SessionManager{}
fh, err := os.OpenFile(file, os.O_RDONLY, 0600)
if err != nil {
return nil, err
}
defer fh.Close()
if err = gob.NewDecoder(fh).Decode(&m); err != nil {
return nil, err
}
return &m, nil
}
func (m *SessionManager) ToFile(file string) error {
fh, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer fh.Close()
if err = gob.NewEncoder(fh).Encode(m); err != nil {
return err
}
return nil
}
// CreateSession creates a new Session under the *SessionManager
func (m *SessionManager) CreateSession(lt time.Time) (*Session, error) {
id, err := generateSessionId(m.Sessions, 30)
if err != nil {
return nil, err
}
s := Session{
Id: id,
Lifetime: lt,
Vars: make(map[string]string),
}
m.Sessions = append(m.Sessions, &s)
return &s, nil
}
// GetSession retrieves the Session with the supplied session ID
func (m *SessionManager) GetSession(id string) (*Session, error) {
m.mut.RLock()
defer m.mut.RUnlock()
for k, v := range m.Sessions {
if v.Id == id {
if !v.Lifetime.After(time.Now()) {
m.Sessions = removeSessionIndex(m.Sessions, k)
} else {
return v, nil
}
}
}
return nil, errors.New("could not find Session for given ID")
}
// GetSessionFromUrl is a convenience method to find an existing session by taking the session ID
// from a *url.URL query parameter.
func (m *SessionManager) GetSessionFromUrl(u *url.URL) (*Session, error) {
return m.GetSession(u.Query().Get(m.SessionName))
}
// GetSessionFromCookie is a convenience method to find an existing session by taking the session ID
// from the cookie with the name initially set when creating the *SessionManager.
func (m *SessionManager) GetSessionFromCookie(r *http.Request) (*Session, error) {
c, err := r.Cookie(m.SessionName)
if err != nil {
return nil, fmt.Errorf("could not read session cookie: %s", err.Error())
}
return m.GetSession(c.Value)
}
// RemoveSession removes the Session with the supplied session ID
func (m *SessionManager) RemoveSession(id string) error {
m.mut.Lock()
defer m.mut.Unlock()
for i, v := range m.Sessions {
if v.Id == id {
m.Sessions = removeSessionIndex(m.Sessions, i)
return nil
}
}
return errors.New("could not find Session for the given ID")
}
// RemoveAllSessions removes all Sessions from a *SessionManager
func (m *SessionManager) RemoveAllSessions() {
m.mut.Lock()
m.Sessions = []*Session{}
m.mut.Unlock()
}
// SetMessage sets a flash message to the *Session
//
// Deprecated
func (s *Session) SetMessage(t MessageType, content string) {
s.Message = Message{
MessageType: t,
Content: content,
}
}
// GetMessage returns a previously set message
func (s *Session) GetMessage() Message {
return s.Message
}
// GetVar returns whether the variable with the given name and the actual value, if it exists
func (s *Session) GetVar(key string) (string, bool) {
s.mut.RLock()
defer s.mut.RUnlock()
val, ok := s.Vars[key]
return val, ok
}
// SetVar sets a attaches a variable with the given name and value
func (s *Session) SetVar(key string, value string) {
s.mut.Lock()
defer s.mut.Unlock()
s.Vars[key] = value
}
// SetCookie is a convenience method to set a session cookie with the initially chosen name.
func (m *SessionManager) SetCookie(w http.ResponseWriter, value string, expires time.Time) {
http.SetCookie(w, &http.Cookie{
Name: m.SessionName,
Value: value,
Path: "/",
Expires: expires,
HttpOnly: true,
})
}
// RemoveCookie is a convenience method to remove the session cookie (s
func (m *SessionManager) RemoveCookie(w http.ResponseWriter, name string) {
http.SetCookie(w, &http.Cookie{
Name: m.SessionName,
Value: "",
Path: "/",
MaxAge: -10,
HttpOnly: true,
})
}
// GetCookieValue fetches the session ID from the session cookie of a given request
func (m *SessionManager) GetCookieValue(r *http.Request) (string, error) {
c, err := r.Cookie(m.SessionName)
if err != nil {
return "", err
}
return c.Value, nil
}
func (m *SessionManager) AddMessage(w http.ResponseWriter, t MessageType, msg string) {
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("%s_MSG_TYPE", m.SessionName),
Value: string(t),
Path: "/",
Expires: time.Now().Add(time.Hour),
HttpOnly: true,
})
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("%s_MSG", m.SessionName),
Value: url.QueryEscape(msg),
Path: "/",
Expires: time.Now().Add(time.Hour),
HttpOnly: true,
})
}
func (m *SessionManager) GetMessage(w http.ResponseWriter, r *http.Request) (MessageType, string, error) {
tc, err := r.Cookie(fmt.Sprintf("%s_MSG_TYPE", m.SessionName))
if err != nil {
return "", "", err
}
mc, err := r.Cookie(fmt.Sprintf("%s_MSG", m.SessionName))
if err != nil {
return "", "", err
}
// remove the cookies
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("%s_MSG_TYPE", m.SessionName),
Value: "",
Path: "/",
Expires: time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC),
MaxAge: -10,
HttpOnly: true,
})
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("%s_MSG", m.SessionName),
Value: "",
Path: "/",
Expires: time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC),
MaxAge: -10,
HttpOnly: true,
})
v, _ := url.QueryUnescape(mc.Value)
return MessageType(tc.Value), v, nil
}
// removeSessionIndex removes a session from a session slice with the given index
func removeSessionIndex(s []*Session, index int) []*Session {
return append(s[:index], s[index+1:]...)
}
// generateSessionId generates a new session ID
func generateSessionId(ss []*Session, length int) (string, error) {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
return "", err
}
id := hex.EncodeToString(b)
for _, v := range ss {
if v.Id == id {
return generateSessionId(ss, length)
}
}
return id, nil
}