-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsession.go
469 lines (384 loc) · 10.2 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package main
import (
"fmt"
"net"
"net/http"
"sync"
"github.com/gorilla/websocket"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"golang.org/x/crypto/bcrypt"
)
var (
// Hold signed in users sessions
sessions *Sessions
// Common error to use across the source code
// when user is not signed in
errSessionNotExists = fmt.Errorf("No sessions were deleted")
)
/*
* Structure to store signed in users sessions and its data.
*
* Use a separate structure as "mongostore.go" is a fork
* and potentially can be removed
*/
type Sessions struct {
*MongoStore
}
/*
* Structure of a single user's session.
* In-memory only, will not be stored in a database
*/
type Session struct {
// Client's IP address
IP string
// Websocket connection for client-server-client communication
Websocket *websocket.Conn
// Mutex, as WS connection supports one concurrent reader and one concurrent writer
WebsocketMutex sync.Mutex
// Client's initial HTTP request
Request *http.Request
// Client's initial HTTP response writer
ResponseWriter http.ResponseWriter
// A channel to use accross the code
// to indicate about a closed websocket connection
Done chan bool
}
/*
* Create a sessions store when service is started
*/
func setupSessions() error {
// Drop old TTL index
ctx, cancel := db.newContext()
defer cancel()
_, err := db.Sessions.Indexes().DropAll(ctx)
if err != nil {
// Ignore namespace not found errors
commandErr, ok := err.(mongo.CommandError)
if !ok {
log.Error().Msg("Can't check MongoDB sessions indexes drop error: " + err.Error())
}
if commandErr.Name != "NamespaceNotFound" {
log.Error().Msg("Failed to drop session coll's indexes: " + err.Error())
}
} else {
log.Debug().Msg("Session coll's old indexes are dropped")
}
// Create a new store with new index
store, err := NewMongoStore(
db.Sessions,
http.Cookie{
Path: "/",
Domain: "",
MaxAge: config.Sessions.TTL,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
},
[]byte(config.Sessions.AuthenticationKey),
[]byte(config.Sessions.EncryptionKey),
)
if err != nil {
return fmt.Errorf("Can't create a MongoDB session store: " + err.Error())
}
sessions = &Sessions{store}
log.Debug().Msg("MongoDB session store created")
return nil
}
/*
* Check whether user is signed in
*/
func (s *Sessions) exists(w http.ResponseWriter, r *http.Request) (string, error) {
// Get client's IP
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", fmt.Errorf("Can't get IP to check existing session: " + err.Error())
}
session, err := s.Get(r, config.Sessions.CookieName)
if err != nil {
return "", fmt.Errorf("Can't check existing session: " + err.Error())
}
//fmt.Printf("session: %#v\n", session)
if len(session.Values) == 0 {
// Check a database connection.
// 's.Get' doesn't return an error if connection was lost
ctx, cancel := db.newContext()
defer cancel()
err = s.Collection.Database().Client().Ping(ctx, nil)
if err != nil {
return "", fmt.Errorf("Can't ping a database: " + err.Error())
}
}
if username, ok := session.Values["username"].(string); ok {
// Update session
err = session.Save(r, w)
if err != nil {
return "", fmt.Errorf("Can't update session " + err.Error())
}
log.Debug().
Str("ip", ip).
Str("username", username).
Msg("Session updated")
return username, nil
}
return "", fmt.Errorf("Requested by unsigned user: " + r.Host + r.URL.RequestURI())
}
/*
* Process '/signup' request to register a new account
*/
func signupHandler(w http.ResponseWriter, r *http.Request) {
// Get client's IP
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Error().
Str("ip", ip).
Msg("Can't get IP to signup: " + err.Error())
return
}
username := r.FormValue("username")
password := r.FormValue("password")
// Validate user input
err = credentialsAreValid(username, password)
if err != nil {
log.Error().
Str("ip", ip).
Msg("Invalid credentials: " + err.Error())
templateData := &TemplateData{
Error: err.Error(),
}
renderTemplate(w, "signin", templateData, nil)
return
}
account := &Account{}
ctx, cancel := db.newContext()
defer cancel()
err = db.Users.FindOne(ctx, bson.M{"username": username}).Decode(account)
if err != nil {
/*
* Create a new account
*/
if err == mongo.ErrNoDocuments {
err = newAccount(w, r)
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Can't create new account: " + err.Error())
templateData := &TemplateData{
Error: "Server internal error, try again later!",
}
renderTemplate(w, "signin", templateData, nil)
} else {
log.Info().
Str("ip", ip).
Str("username", username).
Msg("Registration successful")
http.Redirect(w, r, "/", 302)
}
} else {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Can't find username in a database: " + err.Error())
templateData := &TemplateData{
Error: "Server internal error, try again later!",
}
renderTemplate(w, "signin", templateData, nil)
}
/*
* Set by admin previously removed password.
* Allows to reset forgotten password
*/
} else if account.Password == "" {
err = account.setPassword(r.FormValue("password"))
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Can't setPassword: " + err.Error())
templateData := &TemplateData{
Error: "Server internal error, try again later!",
}
renderTemplate(w, "signin", templateData, nil)
return
}
session, err := sessions.Get(r, config.Sessions.CookieName)
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Can't get session to set new password: " + err.Error())
templateData := &TemplateData{
Error: "Server internal error, try again later!",
}
renderTemplate(w, "signin", templateData, nil)
return
}
// Add username to the session.
// Without this user can't sign up immediately after password reset
session.Values["username"] = username
// Save session
err = session.Save(r, w)
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Can't save session with new password: " + err.Error())
templateData := &TemplateData{
Error: "Server internal error, try again later!",
}
renderTemplate(w, "signin", templateData, nil)
return
}
log.Info().
Str("ip", ip).
Str("username", username).
Msg("Password updated")
http.Redirect(w, r, "/", 302)
/*
* Account already exists and is complete
*/
} else {
log.Error().
Str("ip", ip).
Msg("Username already taken: " + username)
templateData := &TemplateData{
Error: "Username already taken!",
}
renderTemplate(w, "signin", templateData, nil)
}
}
/*
* Process '/signin' request for the existing account
*/
func signinHandler(w http.ResponseWriter, r *http.Request) {
// Accept GET requests only
if r.Method == "GET" {
templateData := &TemplateData{}
renderTemplate(w, "signin", templateData, nil)
return
}
// Get client's IP
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Error().
Str("ip", ip).
Msg("Can't get IP to signin: " + err.Error())
return
}
username := r.FormValue("username")
password := r.FormValue("password")
// Skip trying empty data
if username == "" || password == "" {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Input fields can't be empty")
templateData := &TemplateData{
Error: "Input fields can't be empty",
}
renderTemplate(w, "signin", templateData, nil)
return
}
account := &Account{}
ctx, cancel := db.newContext()
defer cancel()
err = db.Users.FindOne(ctx, bson.M{"username": username}).Decode(account)
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msgf("Invalid username '%s': %s", username, err.Error())
templateData := &TemplateData{
Error: "Invalid username",
}
renderTemplate(w, "signin", templateData, nil)
return
}
// Validate user's password
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(password))
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Invalid password: " + err.Error())
templateData := &TemplateData{
Error: "Invalid password",
}
renderTemplate(w, "signin", templateData, nil)
return
}
// User is authenticated, create a new session
session, err := sessions.Get(r, config.Sessions.CookieName)
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Can't get session: " + err.Error())
}
if session == nil {
templateData := &TemplateData{
Error: "Server internal error, try again later!",
}
renderTemplate(w, "signin", templateData, nil)
return
}
// Add values to the session
session.Values["username"] = username
// Save session
err = session.Save(r, w)
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Can't save session: " + err.Error())
templateData := &TemplateData{
Error: "Server internal error, try again later!",
}
renderTemplate(w, "signin", templateData, nil)
return
}
log.Info().
Str("ip", ip).
Str("username", username).
Msg("User signed in")
http.Redirect(w, r, "/", 302)
}
/*
* Sign out existing user
*/
func signoutHandler(w http.ResponseWriter, r *http.Request) {
// Get client's IP
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Error().
Str("ip", ip).
Msg("Can't get IP to signout: " + err.Error())
http.Redirect(w, r, "/signin", 302)
return
}
// Check existing session
username, err := sessions.exists(w, r)
if err != nil {
log.Error().
Str("ip", ip).
Msg("Can't validate session to sign out: " + err.Error())
fmt.Fprint(w, "Can't validate user session: "+err.Error())
return
}
// Delete session
err = db.deleteSession(username, w, r)
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Msg("Can't close user session: " + err.Error())
http.Redirect(w, r, "/signin", 302)
return
}
log.Info().
Str("ip", ip).
Str("username", username).
Msg("User signed out")
http.Redirect(w, r, "/signin", 302)
}