-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
231 lines (192 loc) · 6.96 KB
/
handler.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
package token
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"net/http"
"time"
"github.com/alexedwards/scs/v2"
"github.com/jmoiron/sqlx"
"github.com/jatolentino/tutorialspoint/api/background"
"github.com/jatolentino/tutorialspoint/api/web"
"github.com/jatolentino/tutorialspoint/api/weberr"
"github.com/jatolentino/tutorialspoint/core/auth"
"github.com/jatolentino/tutorialspoint/core/user"
"github.com/jatolentino/tutorialspoint/database"
"github.com/jatolentino/tutorialspoint/rate"
"github.com/jatolentino/tutorialspoint/validate"
"golang.org/x/crypto/bcrypt"
)
// Mailer should be able to send emails to users
// for handling their activation and their password recovery.
type Mailer interface {
SendActivationToken(token string, to string) error
SendRecoveryToken(token string, to string) error
}
// HandleToken is used to send specific tokens to users via email.
// A valid scope must be provided by users, together with their email.
// It doesn't require a user to be logged in, because users who need
// tokens will probably not be able to login at all.
// This function leverages a rate limiter to avoid too many emails.
func HandleToken(db *sqlx.DB, mailer Mailer, timeout time.Duration, bg *background.Background) web.Handler {
rps := rate.Every(timeout)
limiter := rate.NewLimiter(1, 10, float64(rps))
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var in struct {
Email string `json:"email" validate:"required,email"`
Scope string `json:"scope" validate:"required"`
}
if err := web.Decode(w, r, &in); err != nil {
return weberr.BadRequest(fmt.Errorf("unable to decode payload: %w", err))
}
if err := validate.Check(in); err != nil {
return weberr.NewError(err, err.Error(), http.StatusUnprocessableEntity)
}
if !limiter.Check(in.Email) {
err := errors.New("too many requests")
return weberr.NewError(err, err.Error(), http.StatusTooManyRequests)
}
usr, err := user.FetchByEmail(ctx, db, in.Email)
if err != nil {
err := fmt.Errorf("fetching token by user[%s]: %w", in.Email, err)
if errors.Is(err, database.ErrDBNotFound) {
return weberr.NewError(err, "Email is not registered", http.StatusUnprocessableEntity)
}
return err
}
scope := in.Scope
switch scope {
case ActivationToken:
if usr.Active {
return weberr.BadRequest(fmt.Errorf("user %s is already active", usr.Email))
}
case RecoveryToken:
default:
return weberr.BadRequest(fmt.Errorf("scope %s is not supported", scope))
}
text, token, err := GenToken(usr.ID, 6*time.Hour, scope)
if err != nil {
return fmt.Errorf("generating random token: %w", err)
}
// Delete pending tokens only if the new token is actually stored.
err = database.Transaction(db, func(tx sqlx.ExtContext) error {
if err := DeleteByUser(ctx, tx, usr.ID, scope); err != nil {
return fmt.Errorf("deleting token by user[%s]: %w", usr.ID, err)
}
if err := Create(ctx, tx, token); err != nil {
return fmt.Errorf("creating new token for user[%s]: %w", usr.ID, err)
}
return nil
})
if err != nil {
return err
}
// Send the email in background.
bg.Add(func() error {
switch scope {
case ActivationToken:
if err := mailer.SendActivationToken(text, usr.Email); err != nil {
return fmt.Errorf("failed to send activation token %s to %s: %w", scope, usr.Email, err)
}
case RecoveryToken:
if err := mailer.SendRecoveryToken(text, usr.Email); err != nil {
return fmt.Errorf("failed to send recovery token %s to %s: %w", scope, usr.Email, err)
}
default:
return fmt.Errorf("scope %s is not supported", scope)
}
return nil
})
return web.Respond(ctx, w, nil, http.StatusNoContent)
}
}
// HandleActivation validates the passed token and, if correct,
// it activates the user.
func HandleActivation(db *sqlx.DB, session *scs.SessionManager) web.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var in struct {
Token string `json:"token" validate:"required"`
}
if err := web.Decode(w, r, &in); err != nil {
return weberr.BadRequest(fmt.Errorf("unable to decode payload: %w", err))
}
if err := validate.Check(in); err != nil {
return weberr.NewError(err, err.Error(), http.StatusUnprocessableEntity)
}
hash := sha256.Sum256([]byte(in.Token))
usr, err := user.FetchByToken(ctx, db, hash[:], ActivationToken)
if err != nil {
err := fmt.Errorf("fetching user by token: %w", err)
if errors.Is(err, database.ErrDBNotFound) {
return weberr.BadRequest(err)
}
return err
}
// Delete the token only if the user gets updated correctly (and viceversa).
err = database.Transaction(db, func(tx sqlx.ExtContext) error {
if err := DeleteByUser(ctx, tx, usr.ID, ActivationToken); err != nil {
return fmt.Errorf("deleting token by user[%s]: %w", usr.ID, err)
}
usr.Active = true
usr.UpdatedAt = time.Now().UTC()
if _, err := user.Update(ctx, tx, usr); err != nil {
return fmt.Errorf("activating user[%s]: %w", usr.ID, err)
}
return nil
})
if err != nil {
return err
}
if err := auth.SaveUserSession(ctx, session, usr.ID, usr.Role); err != nil {
return fmt.Errorf("store user[%s] in session: %w", usr.ID, err)
}
return web.Respond(ctx, w, nil, http.StatusNoContent)
}
}
// HandleRecovery validates the passed token and, if correct,
// changes the user's password with the one provided.
func HandleRecovery(db *sqlx.DB) web.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var in struct {
Token string `json:"token" validate:"required"`
Password string `json:"password" validate:"required,gte=8,lte=50"`
PasswordConfirm string `json:"passwordConfirm" validate:"eqfield=Password"`
}
if err := web.Decode(w, r, &in); err != nil {
return weberr.BadRequest(fmt.Errorf("unable to decode payload: %w", err))
}
if err := validate.Check(in); err != nil {
return weberr.NewError(err, err.Error(), http.StatusUnprocessableEntity)
}
tokh := sha256.Sum256([]byte(in.Token))
usr, err := user.FetchByToken(ctx, db, tokh[:], RecoveryToken)
if err != nil {
err := fmt.Errorf("fetch user by token: %w", err)
if errors.Is(err, database.ErrDBNotFound) {
return weberr.BadRequest(err)
}
return err
}
passh, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("generating password hash: %w", err)
}
// Delete the token only if the user gets updated correctly (and viceversa).
err = database.Transaction(db, func(tx sqlx.ExtContext) error {
if err := DeleteByUser(ctx, tx, usr.ID, RecoveryToken); err != nil {
return fmt.Errorf("deleting token by user[%s]: %w", usr.ID, err)
}
usr.PasswordHash = passh
usr.UpdatedAt = time.Now().UTC()
if _, err := user.Update(ctx, tx, usr); err != nil {
return fmt.Errorf("recoverying user[%s]: %w", usr.ID, err)
}
return nil
})
if err != nil {
return err
}
return nil
}
}