forked from StevenWeathers/thunderdome-planning-poker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
593 lines (491 loc) · 16.2 KB
/
handlers.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
package main
import (
"encoding/json"
"errors"
"html/template"
"io/ioutil"
"log"
"net/http"
"github.com/StevenWeathers/thunderdome-planning-poker/pkg/database"
"github.com/gorilla/mux"
"github.com/markbates/pkger"
"github.com/spf13/viper"
"gopkg.in/go-playground/validator.v9"
)
type warriorAccount struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
Password1 string `json:"password1" validate:"required,min=6,max=72"`
Password2 string `json:"password2" validate:"required,min=6,max=72,eqfield=Password1"`
}
type warriorPassword struct {
Password1 string `json:"password1" validate:"required,min=6,max=72"`
Password2 string `json:"password2" validate:"required,min=6,max=72,eqfield=Password1"`
}
// ValidateWarriorAccount makes sure warrior name, email, and password are valid before creating the account
func ValidateWarriorAccount(name string, email string, pwd1 string, pwd2 string) (WarriorName string, WarriorEmail string, WarriorPassword string, validateErr error) {
v := validator.New()
a := warriorAccount{
Name: name,
Email: email,
Password1: pwd1,
Password2: pwd2,
}
err := v.Struct(a)
return name, email, pwd1, err
}
// ValidateWarriorPassword makes sure warrior password is valid before updating the password
func ValidateWarriorPassword(pwd1 string, pwd2 string) (WarriorPassword string, validateErr error) {
v := validator.New()
a := warriorPassword{
Password1: pwd1,
Password2: pwd2,
}
err := v.Struct(a)
return pwd1, err
}
// RespondWithJSON takes a payload and writes the response
func RespondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
// createWarriorCookie creates the warriors cookie
func (s *server) createWarriorCookie(w http.ResponseWriter, isRegistered bool, WarriorID string) {
var cookiedays = 365 // 356 days
if isRegistered == true {
cookiedays = 30 // 30 days
}
encoded, err := s.cookie.Encode(s.config.SecureCookieName, WarriorID)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
cookie := &http.Cookie{
Name: s.config.SecureCookieName,
Value: encoded,
Path: "/",
HttpOnly: true,
Domain: s.config.AppDomain,
MaxAge: 86400 * cookiedays,
Secure: s.config.SecureCookieFlag,
SameSite: http.SameSiteStrictMode,
}
http.SetCookie(w, cookie)
}
// clearWarriorCookies wipes the frontend and backend cookies
// used in the event of bad cookie reads
func (s *server) clearWarriorCookies(w http.ResponseWriter) {
feCookie := &http.Cookie{
Name: s.config.FrontendCookieName,
Value: "",
Path: "/",
MaxAge: -1,
}
beCookie := &http.Cookie{
Name: s.config.SecureCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
}
http.SetCookie(w, feCookie)
http.SetCookie(w, beCookie)
}
// validateWarriorCookie returns the warriorID from secure cookies or errors if failures getting it
func (s *server) validateWarriorCookie(w http.ResponseWriter, r *http.Request) (string, error) {
var warriorID string
if cookie, err := r.Cookie(s.config.SecureCookieName); err == nil {
var value string
if err = s.cookie.Decode(s.config.SecureCookieName, cookie.Value, &value); err == nil {
warriorID = value
} else {
log.Println("error in reading warrior cookie : " + err.Error() + "\n")
s.clearWarriorCookies(w)
return "", errors.New("invalid warrior cookies")
}
} else {
log.Println("error in reading warrior cookie : " + err.Error() + "\n")
s.clearWarriorCookies(w)
return "", errors.New("invalid warrior cookies")
}
return warriorID, nil
}
/*
Middlewares
*/
// adminOnly middleware checks if the user is an admin, otherwise reject their request
func (s *server) adminOnly(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
warriorID, cookieErr := s.validateWarriorCookie(w, r)
if cookieErr != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
adminErr := s.database.ConfirmAdmin(warriorID)
if adminErr != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
h(w, r)
}
}
/*
Handlers
*/
// handleIndex parses the index html file, injecting any relevant data
func (s *server) handleIndex() http.HandlerFunc {
type AppConfig struct {
AllowedPointValues []string
DefaultPointValues []string
}
type UIConfig struct {
AnalyticsEnabled bool
AnalyticsID string
AppConfig AppConfig
}
// get the html template from dist, have it ready for requests
indexFile, ioErr := pkger.Open("/dist/index.html")
if ioErr != nil {
log.Println("Error opening index template")
log.Fatal(ioErr)
}
tmplContent, ioReadErr := ioutil.ReadAll(indexFile)
if ioReadErr != nil {
// this will hopefully only possibly panic during development as the file is already in memory otherwise
log.Println("Error reading index template")
log.Fatal(ioReadErr)
}
tmplString := string(tmplContent)
tmpl, tmplErr := template.New("index").Parse(tmplString)
if tmplErr != nil {
log.Println("Error parsing index template")
log.Fatal(tmplErr)
}
appConfig := AppConfig{
AllowedPointValues: viper.GetStringSlice("config.allowedPointValues"),
DefaultPointValues: viper.GetStringSlice("config.defaultPointValues"),
}
data := UIConfig{
AnalyticsEnabled: s.config.AnalyticsEnabled,
AnalyticsID: s.config.AnalyticsID,
AppConfig: appConfig,
}
return func(w http.ResponseWriter, r *http.Request) {
tmpl.Execute(w, data)
}
}
// handleLogin attempts to login the warrior by comparing email/password to whats in DB
func (s *server) handleLogin() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal) // check for errors
WarriorEmail := keyVal["warriorEmail"]
WarriorPassword := keyVal["warriorPassword"]
authedWarrior, err := s.database.AuthWarrior(WarriorEmail, WarriorPassword)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
encoded, err := s.cookie.Encode(s.config.SecureCookieName, authedWarrior.WarriorID)
if err == nil {
cookie := &http.Cookie{
Name: s.config.SecureCookieName,
Value: encoded,
Path: "/",
HttpOnly: true,
Domain: s.config.AppDomain,
MaxAge: 86400 * 30, // 30 days
Secure: s.config.SecureCookieFlag,
SameSite: http.SameSiteStrictMode,
}
http.SetCookie(w, cookie)
} else {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
RespondWithJSON(w, http.StatusOK, authedWarrior)
}
}
// handleLogout clears the warrior cookie(s) ending session
func (s *server) handleLogout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.clearWarriorCookies(w)
return
}
}
// handleBattleCreate handles creating a battle (arena)
func (s *server) handleBattleCreate() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
warriorID, cookieErr := s.validateWarriorCookie(w, r)
if cookieErr != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
_, warErr := s.database.GetWarrior(warriorID)
if warErr != nil {
log.Println("error finding warrior : " + warErr.Error() + "\n")
s.clearWarriorCookies(w)
w.WriteHeader(http.StatusUnauthorized)
return
}
body, bodyErr := ioutil.ReadAll(r.Body) // check for errors
if bodyErr != nil {
log.Println("error in reading warrior cookie : " + bodyErr.Error() + "\n")
w.WriteHeader(http.StatusInternalServerError)
return
}
var keyVal struct {
BattleName string `json:"battleName"`
PointValuesAllowed []string `json:"pointValuesAllowed"`
Plans []*database.Plan `json:"plans"`
}
json.Unmarshal(body, &keyVal) // check for errors
newBattle, err := s.database.CreateBattle(warriorID, keyVal.BattleName, keyVal.PointValuesAllowed, keyVal.Plans)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
RespondWithJSON(w, http.StatusOK, newBattle)
}
}
// handleWarriorRecruit registers a user as a private warrior (guest)
func (s *server) handleWarriorRecruit() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
jsonErr := json.Unmarshal(body, &keyVal) // check for errors
if jsonErr != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
WarriorName := keyVal["warriorName"]
newWarrior, err := s.database.CreateWarriorPrivate(WarriorName)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
s.createWarriorCookie(w, false, newWarrior.WarriorID)
RespondWithJSON(w, http.StatusOK, newWarrior)
}
}
// handleWarriorEnlist registers a user as a corporal warrior (authenticated)
func (s *server) handleWarriorEnlist() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
jsonErr := json.Unmarshal(body, &keyVal) // check for errors
if jsonErr != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
ActiveWarriorID, _ := s.validateWarriorCookie(w, r)
WarriorName, WarriorEmail, WarriorPassword, accountErr := ValidateWarriorAccount(
keyVal["warriorName"],
keyVal["warriorEmail"],
keyVal["warriorPassword1"],
keyVal["warriorPassword2"],
)
if accountErr != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
newWarrior, VerifyID, err := s.database.CreateWarriorCorporal(WarriorName, WarriorEmail, WarriorPassword, ActiveWarriorID)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
s.createWarriorCookie(w, true, newWarrior.WarriorID)
s.email.SendWelcome(WarriorName, WarriorEmail, VerifyID)
RespondWithJSON(w, http.StatusOK, newWarrior)
}
}
// handleBattleGet looks up battle or returns notfound status
func (s *server) handleBattleGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
BattleID := vars["id"]
battle, err := s.database.GetBattle(BattleID)
if err != nil {
http.NotFound(w, r)
return
}
RespondWithJSON(w, http.StatusOK, battle)
}
}
// handleBattlesGet looks up battles associated with warriorID
func (s *server) handleBattlesGet() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
warriorID, cookieErr := s.validateWarriorCookie(w, r)
if cookieErr != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
_, warErr := s.database.GetWarrior(warriorID)
if warErr != nil {
log.Println("error finding warrior : " + warErr.Error() + "\n")
s.clearWarriorCookies(w)
w.WriteHeader(http.StatusUnauthorized)
return
}
battles, err := s.database.GetBattlesByWarrior(warriorID)
if err != nil {
http.NotFound(w, r)
return
}
RespondWithJSON(w, http.StatusOK, battles)
}
}
// handleForgotPassword attempts to send a password reset email
func (s *server) handleForgotPassword() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal) // check for errors
WarriorEmail := keyVal["warriorEmail"]
ResetID, WarriorName, resetErr := s.database.WarriorResetRequest(WarriorEmail)
if resetErr != nil {
log.Println("error attempting to send warrior reset : " + resetErr.Error() + "\n")
w.WriteHeader(http.StatusInternalServerError)
return
}
s.email.SendForgotPassword(WarriorName, WarriorEmail, ResetID)
w.WriteHeader(http.StatusOK)
return
}
}
// handleResetPassword attempts to reset a warriors password
func (s *server) handleResetPassword() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal) // check for errors
ResetID := keyVal["resetId"]
WarriorPassword, passwordErr := ValidateWarriorPassword(
keyVal["warriorPassword1"],
keyVal["warriorPassword2"],
)
if passwordErr != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
WarriorName, WarriorEmail, resetErr := s.database.WarriorResetPassword(ResetID, WarriorPassword)
if resetErr != nil {
log.Println("error attempting to reset warrior password : " + resetErr.Error() + "\n")
w.WriteHeader(http.StatusInternalServerError)
return
}
s.email.SendPasswordReset(WarriorName, WarriorEmail)
return
}
}
// handleUpdatePassword attempts to update a warriors password
func (s *server) handleUpdatePassword() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal) // check for errors
warriorID, cookieErr := s.validateWarriorCookie(w, r)
if cookieErr != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
WarriorPassword, passwordErr := ValidateWarriorPassword(
keyVal["warriorPassword1"],
keyVal["warriorPassword2"],
)
if passwordErr != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
WarriorName, WarriorEmail, updateErr := s.database.WarriorUpdatePassword(warriorID, WarriorPassword)
if updateErr != nil {
log.Println("error attempting to update warrior password : " + updateErr.Error() + "\n")
w.WriteHeader(http.StatusInternalServerError)
return
}
s.email.SendPasswordUpdate(WarriorName, WarriorEmail)
return
}
}
// handleWarriorProfile returns the warriors profile if it matches their session
func (s *server) handleWarriorProfile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
WarriorID := vars["id"]
warriorCookieID, cookieErr := s.validateWarriorCookie(w, r)
if cookieErr != nil || WarriorID != warriorCookieID {
w.WriteHeader(http.StatusUnauthorized)
return
}
warrior, warErr := s.database.GetWarrior(WarriorID)
if warErr != nil {
log.Println("error finding warrior : " + warErr.Error() + "\n")
w.WriteHeader(http.StatusInternalServerError)
return
}
RespondWithJSON(w, http.StatusOK, warrior)
}
}
// handleWarriorProfileUpdate attempts to update warriors profile (currently limited to name)
func (s *server) handleWarriorProfileUpdate() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal) // check for errors
WarriorName := keyVal["warriorName"]
WarriorID := vars["id"]
warriorCookieID, cookieErr := s.validateWarriorCookie(w, r)
if cookieErr != nil || WarriorID != warriorCookieID {
w.WriteHeader(http.StatusUnauthorized)
return
}
updateErr := s.database.UpdateWarriorProfile(WarriorID, WarriorName)
if updateErr != nil {
log.Println("error attempting to update warrior profile : " + updateErr.Error() + "\n")
w.WriteHeader(http.StatusInternalServerError)
return
}
warrior, warErr := s.database.GetWarrior(WarriorID)
if warErr != nil {
log.Println("error reloading warrior after update : " + warErr.Error() + "\n")
w.WriteHeader(http.StatusInternalServerError)
return
}
RespondWithJSON(w, http.StatusOK, warrior)
}
}
// handleAccountVerification attempts to verify a warriors account
func (s *server) handleAccountVerification() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal) // check for errors
VerifyID := keyVal["verifyId"]
verifyErr := s.database.VerifyWarriorAccount(VerifyID)
if verifyErr != nil {
log.Println("error attempting to verify warrior account : " + verifyErr.Error() + "\n")
w.WriteHeader(http.StatusInternalServerError)
return
}
return
}
}
/*
Admin Handlers
*/
// handleAppStats gets the applications stats
func (s *server) handleAppStats() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
AppStats, err := s.database.GetAppStats()
if err != nil {
http.NotFound(w, r)
return
}
RespondWithJSON(w, http.StatusOK, AppStats)
}
}