-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
288 lines (244 loc) · 7.01 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// A simple website in Go.
// Copyright (c) 2020. Tamás Demeter-Haludka
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package session
import (
"bytes"
"encoding/json"
"io"
"net/http"
"sync"
"time"
uuid "github.com/satori/go.uuid"
"github.com/sirupsen/logrus"
"github.com/tamasd/simplesite/keyvalue"
"github.com/tamasd/simplesite/respond"
"github.com/tamasd/simplesite/server"
"github.com/tamasd/simplesite/util"
"github.com/urfave/negroni"
)
const (
// SessionCookieName is the name of the session cookie.
SessionCookieName = "session"
)
const (
sidLength = 32
csrfLength = 64
sessionKey = "session"
sidKey = "sid"
)
var (
sessionBufferPool = sync.Pool{New: func() interface{} {
return bytes.NewBuffer(nil)
}}
)
// Get returns the session from the current request context.
func Get(r *http.Request) *Session {
return r.Context().Value(sessionKey).(*Session)
}
// GetSid returns the session id from the current request context.
func GetSid(r *http.Request) *string {
return r.Context().Value(sidKey).(*string)
}
// Session represents the session that is saved to the key-value storage.
type Session struct {
ID uuid.UUID
CSRFToken string
}
func (s *Session) GetCSRFToken() string {
return s.CSRFToken
}
func (s *Session) LoggedIn() bool {
return !uuid.Equal(s.ID, uuid.Nil)
}
func (s *Session) Read(p []byte) (int, error) {
return len(p), json.Unmarshal(p, s)
}
func (s *Session) WriteTo(w io.Writer) (int64, error) {
b, err := json.Marshal(s)
if err != nil {
return 0, err
}
n, err := w.Write(b)
return int64(n), err
}
// Middleware is the session middleware.
type Middleware struct {
logger logrus.FieldLogger
store keyvalue.Store
SecureCookie bool
CookieName string
}
func NewMiddleware(logger logrus.FieldLogger, store keyvalue.Store) *Middleware {
return &Middleware{
logger: logger,
store: store,
CookieName: SessionCookieName,
}
}
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
sess := &Session{}
sid := m.load(r, sess)
if sid == "" {
respond.Error(w, r, http.StatusInternalServerError, "session error", nil, nil)
return
}
if sess.CSRFToken == "" {
sess.CSRFToken = GenerateCSRFToken()
}
r = util.SetContext(r, sessionKey, sess)
r = util.SetContext(r, sidKey, &sid)
m.setSessionCookie(w, sid)
next.ServeHTTP(w, r)
buf := sessionBufferPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
sessionBufferPool.Put(buf)
}()
logger := server.GetLoggerOrDefault(r, m.logger)
if _, err := sess.WriteTo(buf); err != nil {
logger.WithError(err).Errorln("failed to encode session data")
return
}
if sid != "" {
if err := m.store.Set(sid, string(buf.Bytes())); err != nil {
logger.WithError(err).Errorln("failed to save session")
return
}
}
}
// RegenerateSession invalidates the previous session and creates a new one.
func (m *Middleware) RegenerateSession(w http.ResponseWriter, r *http.Request, id uuid.UUID) error {
sid := GetSid(r)
if err := m.store.Delete(*sid); err != nil {
return err
}
*sid = GenerateSid(id)
w.Header().Del("Set-Cookie")
m.setSessionCookie(w, *sid)
sess := Get(r)
sess.ID = id
sess.CSRFToken = GenerateCSRFToken()
return nil
}
// DeleteSession removes the current session.
func (m *Middleware) DeleteSession(w http.ResponseWriter, r *http.Request) {
logger := server.GetLogger(r)
sid := GetSid(r)
if err := m.store.Delete(*sid); err != nil {
logger.WithError(err).Errorln("cannot delete session")
}
w.Header().Del("Set-Cookie")
http.SetCookie(w, &http.Cookie{
Name: m.CookieName,
Value: "",
Path: "/",
Expires: time.Unix(0, 0),
HttpOnly: true,
Secure: m.SecureCookie,
})
*sid = ""
}
func (m *Middleware) setSessionCookie(w http.ResponseWriter, sid string) {
http.SetCookie(w, &http.Cookie{
Name: m.CookieName,
Value: sid,
Path: "/",
Expires: time.Now().AddDate(1, 0, 0),
Secure: m.SecureCookie,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
}
func (m *Middleware) load(r *http.Request, sess *Session) string {
start := time.Now()
l := server.GetLoggerOrDefault(r, m.logger)
c, err := r.Cookie(m.CookieName)
if err != nil {
if err == http.ErrNoCookie {
c = &http.Cookie{}
} else {
l.WithError(err).Warnln("failed to get cookie for session")
return ""
}
}
sid := c.Value
if sid == "" {
return GenerateSid(uuid.Nil)
}
sessdata, err := m.store.Get(sid)
if err != nil {
l.WithError(err).Warnln("failed to load session from store")
return ""
}
if sessdata != "" {
if _, err = sess.Read([]byte(sessdata)); err != nil {
l.WithError(err).Warnln("failed to decode session data")
return ""
}
}
l.WithFields(logrus.Fields{
"duration": time.Since(start),
}).Traceln("successfully loaded session")
return sid
}
// GenerateSid generates a new session id.
//
// The session id gets prefixed with the user id, so sessions can be invalidated
// for an user in case an account gets blocked or deleted.
func GenerateSid(id uuid.UUID) string {
return id.String() + ":" + util.RandomHexString(sidLength)
}
// GenerateCSRFToken generates a new csrf token.
func GenerateCSRFToken() string {
return util.RandomHexString(csrfLength)
}
// MustBeLoggedInMiddleware only lets the request proceed if an account is
// logged in.
func MustBeLoggedInMiddleware() negroni.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if sess := Get(r); sess.LoggedIn() {
next.ServeHTTP(w, r)
} else {
respond.Error(w, r, http.StatusForbidden, "must be logged in", nil, nil)
}
}
}
// MustBeAnonymousMiddleware only lets the request proceed if the account is
// not logged in.
func MustBeAnonymousMiddleware() negroni.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if sess := Get(r); !sess.LoggedIn() {
next.ServeHTTP(w, r)
} else {
respond.Error(w, r, http.StatusForbidden, "must not be logged in", nil, nil)
}
}
}
// CSRFTokenMiddleware enforces a CSRF token in the ?token= part of the URL.
func CSRFTokenMiddleware() negroni.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
token := r.URL.Query().Get("token")
if token == "" {
respond.Error(w, r, http.StatusBadRequest, "missing csrf token", nil, nil)
return
}
if sess := Get(r); token != sess.CSRFToken {
respond.Error(w, r, http.StatusForbidden, "invalid csrf token", nil, nil)
return
}
next.ServeHTTP(w, r)
}
}