-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
1943 lines (1720 loc) · 43.5 KB
/
app.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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"fmt"
"log"
"net/http"
"net/url"
"sort"
"time"
"github.com/go-playground/validator/v10"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"golang.org/x/crypto/bcrypt"
"github.com/gin-gonic/gin"
"github.com/go-co-op/gocron"
)
const (
javascriptISOString = "2006-01-02T15:04:05.000Z07:00"
passwordHashCost = bcrypt.DefaultCost
maxBodySize = 10240
cleanupDBTimeUTC = "04:00"
pendingTTL = 1 // days
sessionTTL = 30 // days
adminSessionTTL = 1 // days
emailTTL = 1 // days
)
var paths = map[string]string{
// public API
"joinCheck": "/api/join/check", // *
"join": "/api/join",
"joinActivate": "/api/join/activate",
"signin": "/api/signin",
"resetPassword": "/api/reset-password",
"newPassword": "/api/reset-password/new",
// private API
"auth": "",
"auth_session": "/api/auth/session",
"auth_account": "/api/auth/account",
"auth_account_remove": "/api/auth/account/remove",
"auth_data": "/api/auth/your-data",
"auth_data_profile": "/api/auth/your-data/profile",
"auth_data_tags": "/api/auth/your-data/tags",
"auth_data_tags_remove": "/api/auth/your-data/tags/remove",
"auth_password": "/api/auth/password",
"auth_tags": "/api/auth/tags/:id",
// admin API
"admin": "",
"admin_signin": "/api/admin/signin",
"admin_tags": "/api/admin/tags",
"admin_tags_reset": "/api/admin/tags/:id/reset",
// debug API
"debug_reset": "/debug/reset",
"debug_pending": "/debug/pending",
}
type emailValidator func(pool *pgxpool.Pool, email string) bool
// GoTags holds parts together
type GoTags struct {
pool *pgxpool.Pool
router *gin.Engine
authorized *gin.RouterGroup
emailer mailer
emailValidator emailValidator
inputValidator *validator.Validate
}
// Session is set to gin context once Token validates
type Session struct {
User int
Token string
}
// auth middleware. Token is http header variable with format "Token": "uuid-v4".
// Sessions are stored in database.
func (a *GoTags) auth() gin.HandlerFunc {
return func(c *gin.Context) {
tokens, ok := c.Request.Header["Token"]
if !ok {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// use the first value.
token := tokens[0]
// just in case; validate token before use for db query
err := a.inputValidator.Var(token, "required,uuid")
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
}
var user int
// var name, email string // excluding password_hash.
err = a.pool.QueryRow(
context.Background(),
`SELECT (user_id) FROM sessions WHERE id = $1;`,
token).Scan(&user)
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Set("session", Session{user, token})
c.Next()
}
}
// adminAuth middleware. Admin token is http header variable with
// format "Token": "uuid-v4". Admin sessions are stored in database.
func (a *GoTags) adminAuth() gin.HandlerFunc {
return func(c *gin.Context) {
tokens, ok := c.Request.Header["Token"]
if !ok {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// use the first value.
token := tokens[0]
// just in case; validate token before use for db query
err := a.inputValidator.Var(token, "required,uuid")
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
}
var user int
// var name, email string // excluding password_hash.
err = a.pool.QueryRow(
context.Background(),
`SELECT (user_id) FROM admin_sessions WHERE id = $1;`,
token).Scan(&user)
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Set("session", Session{user, token})
c.Next()
}
}
func bodySizeLimiter(n int64) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, n)
c.Next()
}
}
// session helper
func currentSession(c *gin.Context) Session {
s, ok := c.Get("session")
if !ok {
log.Fatalln("currentSession: no session")
}
return s.(Session)
}
// hooks
var extraInitializations = []func(a *GoTags){}
func addExtraInitialization(f func(a *GoTags)) {
extraInitializations = append(extraInitializations, f)
}
func furtherValidateEmail(pool *pgxpool.Pool, email string) bool {
return true // no anti-cycle-measures
}
/* initialize connects to database, sets up gin router and initializes (a *GoTags).
It also activates hooks and the scheduler. CALLED from main. */
func (a *GoTags) initialize(databaseURL string) {
config, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
log.Fatalf("Unable to parse database config: %v\n", err)
}
config.ConnConfig.RuntimeParams["timezone"] = "UTC" // important
pool, err := pgxpool.ConnectConfig(context.Background(), config)
if err != nil {
log.Fatalf("Unable to connect to database: %v\n", err)
}
router := gin.Default()
router.Use(bodySizeLimiter(maxBodySize))
router.POST(paths["joinCheck"], a.joinCheck)
router.POST(paths["join"], a.join)
router.POST(paths["joinActivate"], a.joinActivate)
router.POST(paths["signin"], a.signin)
router.POST(paths["resetPassword"], a.resetPassword)
router.POST(paths["newPassword"], a.newPassword)
authorized := router.Group(paths["auth"])
authorized.Use(a.auth())
{
authorized.PATCH(paths["auth_session"], a.renewSession)
authorized.DELETE(paths["auth_session"], a.deleteSession)
authorized.GET(paths["auth_account"], a.getAccount)
authorized.PUT(paths["auth_account"], a.updateAccount)
authorized.POST(paths["auth_account_remove"], a.removeAccount)
authorized.GET(paths["auth_data"], a.getData)
authorized.POST(paths["auth_data_profile"], a.updateProfile)
authorized.POST(paths["auth_data_tags"], a.addTags)
authorized.POST(paths["auth_data_tags_remove"], a.removeTags)
authorized.POST(paths["auth_password"], a.updatePassword)
authorized.GET(paths["auth_tags"], a.getTag)
authorized.POST(paths["auth_tags"], a.updateTag)
}
router.POST(paths["admin_signin"], a.adminSignin)
admin := router.Group(paths["admin"])
admin.Use(a.adminAuth())
{
admin.POST(paths["admin_tags"], a.adminAddTag)
admin.POST(paths["admin_tags_reset"], a.adminResetTag)
}
a.pool = pool
a.router = router
a.authorized = authorized
a.emailer = sasMailer
a.inputValidator = validator.New()
// hook run hooks
for _, f := range extraInitializations {
f(a)
}
// set default validator
a.emailValidator = furtherValidateEmail
// start scheduler; initially to run nightly database cleanup
s := gocron.NewScheduler(time.UTC)
s.Every(1).Day().At(cleanupDBTimeUTC).Do(a.cleanupDB)
s.StartAsync()
}
// cleanup runs database cleanup
func (a *GoTags) cleanupDB() {
log.Println("Running database cleanup")
b := &pgx.Batch{}
b.Queue(fmt.Sprintf(`DELETE FROM pending WHERE created_at < now() - interval '%d days';`, pendingTTL))
b.Queue(fmt.Sprintf(`DELETE FROM sessions WHERE modified_at < now() - interval '%d days';`, sessionTTL))
b.Queue(fmt.Sprintf(`DELETE FROM admin_sessions WHERE created_at < now() - interval '%d days';`, adminSessionTTL))
b.Queue(fmt.Sprintf(`DELETE FROM limiter WHERE created_at < now() - interval '%d days';`, emailTTL))
r := a.pool.SendBatch(context.Background(), b)
defer r.Close()
_, err := r.Exec()
if err != nil {
log.Println("Error in database cleanup (pending)", err)
}
_, err = r.Exec()
if err != nil {
log.Println("Error in database cleanup (sessions):", err)
}
_, err = r.Exec()
if err != nil {
log.Println("Error in database cleanup (limiter):", err)
}
}
// called from main, runs the server in a loop
func (a *GoTags) run(server string) {
a.router.Run(server)
}
// convert time.Time to JavaScript new Date compatible format
func jstime(t time.Time) string {
return t.UTC().Format(javascriptISOString)
}
// ******************************************************************
func queryEmailExists(pool *pgxpool.Pool, email string) (bool, error) {
var exists bool
row := pool.QueryRow(
context.Background(),
`SELECT EXISTS(SELECT 1 FROM users WHERE email = $1);`,
email)
err := row.Scan(&exists)
return exists, err
}
func queryEmailExistsTx(tx pgx.Tx, email string) (bool, error) {
var exists bool
row := tx.QueryRow(
context.Background(),
`SELECT EXISTS(SELECT 1 FROM users WHERE email = $1);`,
email)
err := row.Scan(&exists)
return exists, err
}
func queryProfileDataTx(tx pgx.Tx, user int) (data map[string]any, timestamp time.Time, err error) {
row := tx.QueryRow(
context.Background(),
`SELECT data, modified_at FROM profiles WHERE id = $1;`,
user)
err = row.Scan(&data, ×tamp)
return data, timestamp, err
}
type tagrow struct {
ID string `json:"id"`
Name string `json:"name"`
Category string `json:"category"`
Modified string `json:"modified"`
Added string `json:"added"`
Accessed string `json:"accessed"`
ActedOn string `json:"acted_on"`
}
type byAdded []tagrow
func (t byAdded) Len() int {
return len(t)
}
func (t byAdded) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func (t byAdded) Less(i, j int) bool {
ti := t[i]
tj := t[j]
if ti.Added == tj.Added {
return ti.Name < tj.Name
}
return ti.Added < tj.Added
}
func queryTagsTx(tx pgx.Tx, user int) ([]tagrow, error) {
rows, err := tx.Query(
context.Background(),
`SELECT t.id, t.name, t.category, t.modified_at, te.category, te.event_at
FROM tag_events te INNER JOIN tags t ON tag_id = id
WHERE user_id = $1;`,
user)
defer rows.Close()
tagmap := map[string]*tagrow{}
for rows.Next() {
var id, name, category, event string
var modifiedAt, eventAt time.Time
err = rows.Scan(&id, &name, &category, &modifiedAt, &event, &eventAt)
if err == nil {
if _, ok := tagmap[id]; !ok {
tagmap[id] = &tagrow{}
}
t := tagmap[id]
t.ID = id
t.Name = name
t.Modified = jstime(modifiedAt)
t.Category = category
switch event {
case "added":
t.Added = jstime(eventAt)
case "accessed":
t.Accessed = jstime(eventAt)
case "acted_on":
t.ActedOn = jstime(eventAt)
default:
log.Fatalln("unexpected tag event", event)
}
} else {
return nil, err
}
}
if rows.Err() != nil {
return nil, rows.Err()
}
rows.Close()
tagrows := make([]tagrow, 0, len(tagmap))
for k := range tagmap {
tagrows = append(tagrows, *tagmap[k])
}
// sort by added timestamp and by tag name
sort.Sort(byAdded(tagrows))
return tagrows, nil
}
func (a *GoTags) queryUserDataTx(tx pgx.Tx, user int) (map[string]any, error) {
profileData, timestamp, err := queryProfileDataTx(tx, user)
if err != nil {
return nil, err
}
tags, err := queryTagsTx(tx, user)
if err != nil {
return nil, err
}
return map[string]any{
"profile": map[string]any{
"data": profileData,
"timestamp": timestamp,
},
"tags": tags,
}, nil
}
// ******************************************************************
// paths
func (a *GoTags) joinCheck(c *gin.Context) {
var d struct {
Email string `json:"email" binding:"required,email,max=1024"`
// these validators can be customised
}
if err := c.BindJSON(&d); err != nil {
c.Status(http.StatusBadRequest)
return
}
email := d.Email
if !a.emailValidator(a.pool, email) { // further validate email
c.Status(http.StatusConflict)
return
}
// check if email is in use
exists, err := queryEmailExists(a.pool, email)
switch {
case err != nil:
c.Status(http.StatusInternalServerError)
return
case exists:
c.Status(http.StatusConflict)
return
}
c.JSON(http.StatusOK, gin.H{"email": email})
}
//
func (a *GoTags) join(c *gin.Context) {
var d struct {
Name string `json:"name" binding:"required,min=1,max=1024"`
Email string `json:"email" binding:"required,email,max=1024"`
Password string `json:"password" binding:"required,min=1,max=1024"`
Lang string `json:"lang" binding:"max=1024"`
Extra string `json:"extra" binding:"max=1024"`
}
if err := c.BindJSON(&d); err != nil {
c.Status(http.StatusBadRequest)
return
}
name := d.Name
email := d.Email
password := d.Password
lang := d.Lang
extra := d.Extra
if !a.emailValidator(a.pool, email) { // further validate email
c.Status(http.StatusConflict)
return
}
// begin transaction
tx, err := a.pool.Begin(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
defer tx.Rollback(context.Background())
// check if email in use
exists, err := queryEmailExistsTx(tx, email)
switch {
case err != nil:
c.Status(http.StatusInternalServerError)
return
case exists:
c.Status(http.StatusConflict)
return
}
// calculate hash from incoming password
passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), passwordHashCost)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
// add email to limiter
t, err := tx.Exec(
context.Background(),
`INSERT INTO limiter (email, counter)
SELECT $1, counter_nr
FROM (
SELECT counter_nr
FROM generate_series (1, get_emails_limit()) counter_nr
EXCEPT (SELECT counter FROM limiter WHERE email = $1)
ORDER BY 1
LIMIT 1
) sub;`, email)
switch {
case err != nil:
c.Status(http.StatusInternalServerError)
return
case t.RowsAffected() == 0:
c.Status(http.StatusTooManyRequests)
return
}
// add pending join request data
data := map[string]any{
"name": name,
"password_hash": string(passwordHash),
"extra": extra,
}
var uuid string
row := tx.QueryRow(
context.Background(),
`INSERT INTO pending (email, category, data)
VALUES ($1, 'join', $2)
RETURNING id;`,
email, data)
err = row.Scan(&uuid)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusTooManyRequests)
return
case err != nil:
switch e := err.(type) {
case *pgconn.PgError:
if e.Code == "P0001" /* && e.Message == "pending: no capacity" */ {
c.Status(http.StatusTooManyRequests)
return
}
default:
c.Status(http.StatusInternalServerError)
return
}
}
req, err := http.NewRequest("GET", paths["joinActivate"], nil)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
q := url.Values{}
q.Add("id", uuid)
req.URL.RawQuery = q.Encode()
// send message with a link
err = a.emailer(email, req.URL.String(), lang)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
// commit transaction
err = tx.Commit(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.Status(http.StatusCreated)
}
//
func (a *GoTags) joinActivate(c *gin.Context) {
var d struct {
ID string `json:"id" binding:"required,uuid"`
Email string `json:"email" binding:"required,email,max=1024"`
Password string `json:"password" binding:"required,min=1,max=1024"`
}
if err := c.BindJSON(&d); err != nil {
c.Status(http.StatusBadRequest)
return
}
id := d.ID
email := d.Email
password := d.Password
// begin transaction
tx, err := a.pool.Begin(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
defer tx.Rollback(context.Background())
// delete matching pending join, get email and data
var pendingEmail string
data := map[string]any{}
row := tx.QueryRow(
context.Background(),
`DELETE FROM pending WHERE id = $1 AND category = 'join' RETURNING email, data;`,
id)
err = row.Scan(&pendingEmail, &data)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusNotFound)
return
case err != nil:
c.Status(http.StatusInternalServerError)
return
}
// validate email and password
name := (data["name"]).(string)
passwordHash := (data["password_hash"]).(string)
err = bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password))
if pendingEmail != email || err != nil {
c.Status(http.StatusUnauthorized)
return
}
extra := data["extra"]
// add user
var user int
row = tx.QueryRow(
context.Background(),
`INSERT INTO users (name, email, password_hash)
VALUES ($1, $2, $3)
ON CONFLICT (email) DO UPDATE
SET name=EXCLUDED.name, password_hash=EXCLUDED.password_hash
RETURNING id;`,
name, email, passwordHash)
err = row.Scan(&user)
switch {
case err == pgx.ErrNoRows:
log.Print("unexpected error err == pgx.ErrNoRows", err) // should not happen
c.Status(http.StatusInternalServerError)
return
case err != nil:
c.Status(http.StatusInternalServerError)
return
}
var token string
row = tx.QueryRow(
context.Background(),
`INSERT INTO sessions (user_id) VALUES ($1) RETURNING id;`, user)
err = row.Scan(&token)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusTooManyRequests)
return
case err != nil:
switch e := err.(type) {
case *pgconn.PgError:
if e.Code == "P0001" /* && e.Message == "sessions: no capacity" */ {
c.Status(http.StatusTooManyRequests)
return
}
default:
c.Status(http.StatusInternalServerError)
return
}
}
userData, err := a.queryUserDataTx(tx, user)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusGone)
return
case err != nil:
c.Status(http.StatusInternalServerError)
return
}
// commit transaction
err = tx.Commit(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.JSON(http.StatusOK, gin.H{
"name": name,
"email": email,
"data": userData,
"token": token,
"extra": extra,
})
}
//
func (a *GoTags) signin(c *gin.Context) {
var d struct {
Email string `json:"email" binding:"required,email,max=1024"`
Password string `json:"password" binding:"required,min=1,max=1024"`
}
if err := c.BindJSON(&d); err != nil {
c.Status(http.StatusBadRequest)
return
}
email := d.Email
password := d.Password
// begin transaction
tx, err := a.pool.Begin(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
defer tx.Rollback(context.Background())
// get use data and profile
var user int
var data map[string]any
var name, passwordHash string
row := tx.QueryRow(
context.Background(),
`WITH xu AS (
SELECT id, name, password_hash FROM users WHERE email = $1
)
SELECT u.id, name, password_hash, data FROM profiles AS p JOIN xu AS u ON p.id = u.id;`,
email)
err = row.Scan(&user, &name, &passwordHash, &data)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusUnauthorized)
return
case err != nil:
c.Status(http.StatusInternalServerError)
return
}
// validate password
err = bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password))
if err != nil {
c.Status(http.StatusUnauthorized)
return
}
// create a session
var token string
row = tx.QueryRow(
context.Background(),
`INSERT INTO sessions (user_id)
VALUES ($1)
RETURNING id;`,
user)
err = row.Scan(&token)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusTooManyRequests)
return
case err != nil:
switch e := err.(type) {
case *pgconn.PgError:
if e.Code == "P0001" /* && e.Message == "sessions: no capacity" */ {
c.Status(http.StatusTooManyRequests)
return
}
default:
c.Status(http.StatusInternalServerError)
return
}
}
userData, err := a.queryUserDataTx(tx, user)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusGone)
return
case err != nil:
c.Status(http.StatusInternalServerError)
return
}
// commit transaction
err = tx.Commit(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.JSON(http.StatusOK, gin.H{
"name": name,
"email": email,
"data": userData,
"token": token,
})
}
//
func (a *GoTags) resetPassword(c *gin.Context) {
var d struct {
Email string `json:"email" binding:"required,email,max=1024"`
Lang string `json:"lang" binding:"max=1024"`
Extra string `json:"extra" binding:"max=1024"`
}
if err := c.BindJSON(&d); err != nil {
c.Status(http.StatusBadRequest)
return
}
email := d.Email
lang := d.Lang
extra := d.Extra
// beging transaction
tx, err := a.pool.Begin(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
defer tx.Rollback(context.Background())
// get user with matching email
var user int
row := tx.QueryRow(
context.Background(),
`SELECT id FROM users WHERE email = $1;`,
email)
err = row.Scan(&user)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusNotFound)
return
case err != nil:
c.Status(http.StatusInternalServerError)
return
}
// add email to limiter
t, err := tx.Exec(
context.Background(),
`INSERT INTO limiter (email, counter)
SELECT $1, counter_nr
FROM (
SELECT counter_nr
FROM generate_series (1, get_emails_limit()) counter_nr
EXCEPT (SELECT counter FROM limiter WHERE email = $1)
ORDER BY 1
LIMIT 1
) sub;`, email)
switch {
case err != nil:
c.Status(http.StatusInternalServerError)
return
case t.RowsAffected() == 0:
c.Status(http.StatusTooManyRequests)
return
}
// add pending reset password data
data := map[string]any{
"extra": extra,
}
var uuid string
row = tx.QueryRow(
context.Background(),
`INSERT INTO pending (email, category, data)
VALUES ($1, 'reset_password', $2)
RETURNING id;`,
email, data)
err = row.Scan(&uuid)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusTooManyRequests)
return
case err != nil:
switch e := err.(type) {
case *pgconn.PgError:
if e.Code == "P0001" /* && e.Message == "pending: no capacity" */ {
c.Status(http.StatusTooManyRequests)
return
}
default:
c.Status(http.StatusInternalServerError)
return
}
}
// create reset password url
req, err := http.NewRequest("GET", paths["resetPasswordVerify"], nil)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
q := url.Values{}
q.Add("id", uuid)
req.URL.RawQuery = q.Encode()
// send message with a link to complete password reset
err = a.emailer(email, req.URL.String(), lang)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
// commit transaction
err = tx.Commit(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.Status(http.StatusCreated)
}
//
func (a *GoTags) newPassword(c *gin.Context) {
var d struct {
ID string `json:"id" binding:"required,uuid"`
Email string `json:"email" binding:"required,email,max=1024"`
Password string `json:"password" binding:"required,min=1,max=1024"`
}
if err := c.BindJSON(&d); err != nil {
c.Status(http.StatusBadRequest)
return
}
id := d.ID
email := d.Email
password := d.Password
// start transaction
tx, err := a.pool.Begin(context.Background())
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
defer tx.Rollback(context.Background())
// delete matching pending password reset, get email
var pendingEmail string
data := map[string]any{}
row := tx.QueryRow(
context.Background(),
`DELETE FROM pending WHERE id = $1 AND category = 'reset_password' RETURNING email, data;`,
id)
err = row.Scan(&pendingEmail, &data)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusNotFound)
return
case err != nil:
c.Status(http.StatusInternalServerError)
return
}
if pendingEmail != email {
c.Status(http.StatusUnauthorized)
return
}
extra := data["extra"]
// generate password hash
passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), passwordHashCost)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
// update password hash, get user id and name
var user int
var name string
row = tx.QueryRow(
context.Background(),
`UPDATE users SET password_hash = $1 WHERE email = $2 RETURNING id, name;`,
passwordHash, email)
err = row.Scan(&user, &name)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusGone)
return
case err != nil:
c.Status(http.StatusInternalServerError)
return
}
// create session token
var token string
row = tx.QueryRow(
context.Background(),
`INSERT INTO sessions (user_id) VALUES ($1) RETURNING id;`,
user)
err = row.Scan(&token)
switch {
case err == pgx.ErrNoRows:
c.Status(http.StatusTooManyRequests)
return
case err != nil:
switch e := err.(type) {
case *pgconn.PgError:
if e.Code == "P0001" /* && e.Message == "sessions: no capacity" */ {
c.Status(http.StatusTooManyRequests)
return
}
default:
c.Status(http.StatusInternalServerError)