forked from ubccr/mokey
/
handlers.go
757 lines (642 loc) · 20.5 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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// Copyright 2015 mokey Authors. All rights reserved.
// Use of this source code is governed by a BSD style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"errors"
"fmt"
"html/template"
"net/http"
"strconv"
"unicode/utf8"
"github.com/Sirupsen/logrus"
"github.com/gorilla/context"
"github.com/gorilla/mux"
"github.com/justinas/nosurf"
"github.com/spf13/viper"
"github.com/ubccr/goipa"
"github.com/ubccr/mokey/model"
"golang.org/x/crypto/bcrypt"
)
func renderTemplate(w http.ResponseWriter, t *template.Template, data interface{}) {
var buf bytes.Buffer
err := t.ExecuteTemplate(&buf, "layout", data)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("failed to render template")
http.Error(w, "Fatal error rendering template", http.StatusInternalServerError)
return
}
buf.WriteTo(w)
}
func errorHandler(app *Application, w http.ResponseWriter, status int) {
w.WriteHeader(status)
renderTemplate(w, app.templates["error.html"], nil)
}
func setupAccount(app *Application, questions []*model.SecurityQuestion, token *model.Token, r *http.Request) error {
qid := r.FormValue("qid")
answer := r.FormValue("answer")
pass := r.FormValue("password")
pass2 := r.FormValue("password2")
if len(pass) < viper.GetInt("min_passwd_len") || len(pass2) < viper.GetInt("min_passwd_len") {
return errors.New(fmt.Sprintf("Please set a password at least %d characters in length.", viper.GetInt("min_passwd_len")))
}
if pass != pass2 {
return errors.New("Password do not match. Please confirm your password.")
}
if len(qid) == 0 || len(answer) == 0 {
return errors.New("Please choose a security question and answer.")
}
if utf8.RuneCountInString(answer) < 2 || utf8.RuneCountInString(answer) > 100 {
return errors.New("Invalid answer. Must be between 2 and 100 characters long.")
}
q, err := strconv.Atoi(qid)
if err != nil {
return errors.New("Invalid security question")
}
found := false
for _, sq := range questions {
if sq.Id == q {
found = true
break
}
}
if found == false {
return errors.New("Invalid security question")
}
hash, err := bcrypt.GenerateFromPassword([]byte(answer), bcrypt.DefaultCost)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to generate bcrypt hash of answer")
return errors.New("Fatal system error")
}
// Setup password in FreeIPA
err = setPassword(token.UserName, "", pass)
if err != nil {
if ierr, ok := err.(*ipa.ErrPasswordPolicy); ok {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": ierr.Error(),
}).Error("password does not conform to policy")
return errors.New("Your password is too weak. Please ensure your password includes a number and lower/upper case character")
}
if ierr, ok := err.(*ipa.ErrInvalidPassword); ok {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": ierr.Error(),
}).Error("invalid password from FreeIPA")
return errors.New("Invalid password.")
}
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to set user password in FreeIPA")
return errors.New("Fatal system error")
}
// Save security answer
a := &model.SecurityAnswer{
UserName: token.UserName,
QuestionId: q,
Answer: string(hash)}
err = model.StoreAnswer(app.db, a)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to save answer to the database")
return errors.New("Fatal system error")
}
// Destroy token
err = model.DestroyToken(app.db, token.Token)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to remove token from database")
return errors.New("Fatal system error")
}
return nil
}
func SetupAccountHandler(app *Application) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tk, ok := model.VerifyToken(ACCOUNT_SETUP_SALT, mux.Vars(r)["token"])
if !ok {
w.WriteHeader(http.StatusNotFound)
renderTemplate(w, app.templates["404.html"], nil)
return
}
token, err := model.FetchToken(app.db, tk, viper.GetInt("setup_max_age"))
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("Failed to fetch token from database")
w.WriteHeader(http.StatusNotFound)
renderTemplate(w, app.templates["404.html"], nil)
return
}
if token.Attempts > viper.GetInt("max_attempts") {
logrus.WithFields(logrus.Fields{
"token": token.Token,
"uid": token.UserName,
}).Error("Too many attempts for token.")
w.WriteHeader(http.StatusNotFound)
renderTemplate(w, app.templates["404.html"], nil)
return
}
questions, err := model.FetchQuestions(app.db)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("Failed to fetch questions from database")
errorHandler(app, w, http.StatusInternalServerError)
return
}
message := ""
completed := false
if r.Method == "POST" {
err := setupAccount(app, questions, token, r)
if err != nil {
message = err.Error()
completed = false
err := model.IncrementToken(app.db, token.Token)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("Failed to increment token attempts")
}
} else {
completed = true
err = app.SendEmail(token.Email, fmt.Sprintf("[%s] Your account confirmation", viper.GetString("email_prefix")), "setup-account-confirm.txt", nil)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err,
}).Error("failed to send setup confirmation email to user")
}
}
}
vars := map[string]interface{}{
"token": nosurf.Token(r),
"uid": token.UserName,
"completed": completed,
"questions": questions,
"message": message}
renderTemplate(w, app.templates["setup-account.html"], vars)
})
}
func resetPassword(app *Application, answer *model.SecurityAnswer, token *model.Token, r *http.Request) error {
ans := r.FormValue("answer")
pass := r.FormValue("password")
pass2 := r.FormValue("password2")
if len(pass) < viper.GetInt("min_passwd_len") || len(pass2) < viper.GetInt("min_passwd_len") {
return errors.New(fmt.Sprintf("Please set a password at least %d characters in length.", viper.GetInt("min_passwd_len")))
}
if pass != pass2 {
return errors.New("Password do not match. Please confirm your password.")
}
if utf8.RuneCountInString(ans) < 2 || utf8.RuneCountInString(ans) > 100 {
return errors.New("Invalid answer. Must be between 2 and 100 characters long.")
}
err := bcrypt.CompareHashAndPassword([]byte(answer.Answer), []byte(ans))
if err != nil {
return errors.New("The security answer you provided does not match. Please check that you are entering the correct answer.")
}
// Setup password in FreeIPA
err = setPassword(token.UserName, "", pass)
if err != nil {
if ierr, ok := err.(*ipa.ErrPasswordPolicy); ok {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": ierr.Error(),
}).Error("password does not conform to policy")
return errors.New("Your password is too weak. Please ensure your password includes a number and lower/upper case character")
}
if ierr, ok := err.(*ipa.ErrInvalidPassword); ok {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": ierr.Error(),
}).Error("invalid password from FreeIPA")
return errors.New("Invalid password.")
}
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to set user password in FreeIPA")
return errors.New("Fatal system error")
}
// Destroy token
err = model.DestroyToken(app.db, token.Token)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err.Error(),
}).Error("failed to remove token from database")
return errors.New("Fatal system error")
}
return nil
}
func ResetPasswordHandler(app *Application) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tk, ok := model.VerifyToken(RESET_SALT, mux.Vars(r)["token"])
if !ok {
w.WriteHeader(http.StatusNotFound)
renderTemplate(w, app.templates["404.html"], nil)
return
}
token, err := model.FetchToken(app.db, tk, viper.GetInt("reset_max_age"))
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("Failed to fetch token from database")
w.WriteHeader(http.StatusNotFound)
renderTemplate(w, app.templates["404.html"], nil)
return
}
if token.Attempts > viper.GetInt("max_attempts") {
logrus.WithFields(logrus.Fields{
"token": token.Token,
"uid": token.UserName,
}).Error("Too many attempts for token.")
w.WriteHeader(http.StatusNotFound)
renderTemplate(w, app.templates["404.html"], nil)
return
}
answer, err := model.FetchAnswer(app.db, token.UserName)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err,
}).Error("Failed to fetch security answer")
w.WriteHeader(http.StatusNotFound)
renderTemplate(w, app.templates["404.html"], nil)
return
}
message := ""
completed := false
if r.Method == "POST" {
err := resetPassword(app, answer, token, r)
if err != nil {
message = err.Error()
completed = false
err := model.IncrementToken(app.db, token.Token)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("Failed to increment token attempts")
}
} else {
completed = true
err = app.SendEmail(token.Email, fmt.Sprintf("[%s] Your password change confirmation", viper.GetString("email_prefix")), "reset-password-confirm.txt", nil)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": token.UserName,
"error": err,
}).Error("failed to send reset confirmation email to user")
}
}
}
vars := map[string]interface{}{
"token": nosurf.Token(r),
"uid": token.UserName,
"completed": completed,
"question": answer.Question,
"message": message}
renderTemplate(w, app.templates["reset-password.html"], vars)
})
}
func forgotPassword(app *Application, r *http.Request) error {
uid := r.FormValue("uid")
if len(uid) == 0 {
return errors.New("Please provide a user name.")
}
_, err := model.FetchTokenByUser(app.db, uid, viper.GetInt("setup_max_age"))
if err == nil {
logrus.WithFields(logrus.Fields{
"uid": uid,
}).Error("Forgotpw: user already has active token")
return nil
}
client := NewIpaClient(true)
userRec, err := client.UserShow(uid)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": uid,
"error": err,
}).Error("Forgotpw: invalid uid")
return nil
}
if len(userRec.Email) == 0 {
logrus.WithFields(logrus.Fields{
"uid": uid,
}).Error("Forgotpw: missing email address")
return nil
}
_, err = model.FetchAnswer(app.db, uid)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": uid,
"error": err,
}).Error("Forgotpw: Failed to fetch security answer")
return nil
}
token, err := model.NewToken(app.db, uid, string(userRec.Email))
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": uid,
"error": err,
}).Error("Forgotpw: Failed to create token")
return nil
}
vars := map[string]interface{}{
"link": fmt.Sprintf("%s/auth/resetpw/%s", viper.GetString("email_link_base"), model.SignToken(RESET_SALT, token.Token))}
err = app.SendEmail(token.Email, fmt.Sprintf("[%s] Please reset your password", viper.GetString("email_prefix")), "reset-password.txt", vars)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": uid,
"error": err,
}).Error("Forgotpw: failed send email to user")
}
return nil
}
func ForgotPasswordHandler(app *Application) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
message := ""
completed := false
if r.Method == "POST" {
err := forgotPassword(app, r)
if err != nil {
message = err.Error()
completed = false
} else {
completed = true
}
}
vars := map[string]interface{}{
"token": nosurf.Token(r),
"completed": completed,
"message": message}
renderTemplate(w, app.templates["forgot-password.html"], vars)
})
}
func setPassword(uid, oldPass, newPass string) error {
c := NewIpaClient(true)
if len(oldPass) == 0 {
rand, err := c.ResetPassword(uid)
if err != nil {
return err
}
oldPass = rand
}
err := c.ChangePassword(uid, oldPass, newPass)
if err != nil {
return err
}
return nil
}
func tryAuth(uid, pass string) (string, *ipa.UserRecord, error) {
if len(uid) == 0 || len(pass) == 0 {
return "", nil, errors.New("Please provide a uid/password")
}
c := NewIpaClient(true)
sess, err := c.Login(uid, pass)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": uid,
"ipa_client_error": err,
}).Error("tryauth: failed login attempt")
return "", nil, errors.New("Invalid login")
}
userRec, err := c.UserShow(uid)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": uid,
"ipa_client_error": err,
}).Error("tryauth: failed to fetch user info")
return "", nil, errors.New("Invalid login")
}
return sess, userRec, nil
}
func LoginHandler(app *Application) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
message := ""
if r.Method == "POST" {
uid := r.FormValue("uid")
pass := r.FormValue("password")
sid, userRec, err := tryAuth(uid, pass)
if err != nil {
message = err.Error()
} else {
session, _ := app.cookieStore.Get(r, MOKEY_COOKIE_SESSION)
session.Values[MOKEY_COOKIE_SID] = sid
session.Values[MOKEY_COOKIE_USER] = userRec
err = session.Save(r, w)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("loginhandler: failed to save session")
errorHandler(app, w, http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", 302)
return
}
}
vars := map[string]interface{}{
"token": nosurf.Token(r),
"message": message}
renderTemplate(w, app.templates["login.html"], vars)
})
}
func LogoutHandler(app *Application) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := app.cookieStore.Get(r, MOKEY_COOKIE_SESSION)
delete(session.Values, MOKEY_COOKIE_SID)
delete(session.Values, MOKEY_COOKIE_USER)
session.Options.MaxAge = -1
err := session.Save(r, w)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("logouthandler: failed to save session")
errorHandler(app, w, http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/auth/login", 302)
})
}
func IndexHandler(app *Application) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := context.Get(r, "user").(*ipa.UserRecord)
if user == nil {
logrus.Error("index handler: user not found in request context")
errorHandler(app, w, http.StatusInternalServerError)
return
}
vars := map[string]interface{}{
"user": user}
renderTemplate(w, app.templates["index.html"], vars)
})
}
func changePassword(app *Application, user *ipa.UserRecord, r *http.Request) error {
current := r.FormValue("password")
pass := r.FormValue("new_password")
pass2 := r.FormValue("new_password2")
if len(current) < viper.GetInt("min_passwd_len") || len(pass) < viper.GetInt("min_passwd_len") || len(pass2) < viper.GetInt("min_passwd_len") {
return errors.New(fmt.Sprintf("Please set a password at least %d characters in length.", viper.GetInt("min_passwd_len")))
}
if pass != pass2 {
return errors.New("Password do not match. Please confirm your password.")
}
if current == pass {
return errors.New("Current password is the same as new password. Please set a different password.")
}
// Setup password in FreeIPA
err := setPassword(string(user.Uid), current, pass)
if err != nil {
if ierr, ok := err.(*ipa.ErrPasswordPolicy); ok {
logrus.WithFields(logrus.Fields{
"uid": user.Uid,
"error": ierr.Error(),
}).Error("password does not conform to policy")
return errors.New("Password policy error. Your password is either too weak or you just changed your password within the last hour. Please ensure your password includes a number and lower/upper case character. You can only update your password once an hour.")
}
if ierr, ok := err.(*ipa.ErrInvalidPassword); ok {
logrus.WithFields(logrus.Fields{
"uid": user.Uid,
"error": ierr.Error(),
}).Error("invalid password from FreeIPA")
return errors.New("Invalid password.")
}
logrus.WithFields(logrus.Fields{
"uid": user.Uid,
"error": err.Error(),
}).Error("failed to set user password in FreeIPA")
return errors.New("Fatal system error")
}
return nil
}
func ChangePasswordHandler(app *Application) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := context.Get(r, "user").(*ipa.UserRecord)
if user == nil {
logrus.Error("changepw handler: user not found in request context")
errorHandler(app, w, http.StatusInternalServerError)
return
}
message := ""
completed := false
if r.Method == "POST" {
err := changePassword(app, user, r)
if err != nil {
message = err.Error()
completed = false
} else {
completed = true
if len(user.Email) > 0 {
err = app.SendEmail(string(user.Email), fmt.Sprintf("[%s] Your password change confirmation", viper.GetString("email_prefix")), "reset-password-confirm.txt", nil)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": user.Uid,
"error": err,
}).Error("failed to send reset confirmation email to user")
}
} else {
logrus.WithFields(logrus.Fields{
"uid": user.Uid,
}).Error("changepw: user missing email address")
}
}
}
vars := map[string]interface{}{
"token": nosurf.Token(r),
"completed": completed,
"user": user,
"message": message}
renderTemplate(w, app.templates["change-password.html"], vars)
})
}
func updateSecurityQuestion(app *Application, questions []*model.SecurityQuestion, user *ipa.UserRecord, r *http.Request) error {
qid := r.FormValue("qid")
answer := r.FormValue("answer")
if len(qid) == 0 || len(answer) == 0 {
return errors.New("Please choose a security question and answer.")
}
if utf8.RuneCountInString(answer) < 2 || utf8.RuneCountInString(answer) > 100 {
return errors.New("Invalid answer. Must be between 2 and 100 characters long.")
}
q, err := strconv.Atoi(qid)
if err != nil {
return errors.New("Invalid security question")
}
found := false
for _, sq := range questions {
if sq.Id == q {
found = true
break
}
}
if found == false {
return errors.New("Invalid security question")
}
hash, err := bcrypt.GenerateFromPassword([]byte(answer), bcrypt.DefaultCost)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": user.Uid,
"error": err.Error(),
}).Error("failed to generate bcrypt hash of answer")
return errors.New("Fatal system error")
}
a := &model.SecurityAnswer{
UserName: string(user.Uid),
QuestionId: q,
Answer: string(hash)}
err = model.StoreAnswer(app.db, a)
if err != nil {
logrus.WithFields(logrus.Fields{
"uid": user.Uid,
"error": err.Error(),
}).Error("failed to save answer to the database")
return errors.New("Fatal system error")
}
return nil
}
func UpdateSecurityQuestionHandler(app *Application) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := context.Get(r, "user").(*ipa.UserRecord)
if user == nil {
logrus.Error("securityquestion handler: user not found in request context")
errorHandler(app, w, http.StatusInternalServerError)
return
}
questions, err := model.FetchQuestions(app.db)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("Failed to fetch questions from database")
errorHandler(app, w, http.StatusInternalServerError)
return
}
message := ""
completed := false
if r.Method == "POST" {
err := updateSecurityQuestion(app, questions, user, r)
if err != nil {
message = err.Error()
completed = false
} else {
completed = true
}
}
vars := map[string]interface{}{
"token": nosurf.Token(r),
"completed": completed,
"user": user,
"questions": questions,
"message": message}
renderTemplate(w, app.templates["update-security-question.html"], vars)
})
}