forked from volatiletech/authboss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover.go
324 lines (262 loc) · 9.87 KB
/
recover.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
// Package recover implements password reset via e-mail.
package recover
import (
"context"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"path"
"time"
"github.com/justin-wilxite/authboss/v3"
)
// Constants for templates etc.
const (
DataRecoverToken = "recover_token"
DataRecoverURL = "recover_url"
FormValueToken = "token"
EmailRecoverHTML = "recover_html"
EmailRecoverTxt = "recover_txt"
PageRecoverStart = "recover_start"
PageRecoverMiddle = "recover_middle"
PageRecoverEnd = "recover_end"
recoverInitiateSuccessFlash = "An email has been sent to you with further instructions on how to reset your password."
)
// Recover module
type Recover struct {
*authboss.Authboss
}
// Init module
func (r *Recover) Init(ab *authboss.Authboss) (err error) {
r.Authboss = ab
if err := r.Authboss.Config.Core.ViewRenderer.Load(PageRecoverStart, PageRecoverEnd); err != nil {
return err
}
if err := r.Authboss.Config.Core.MailRenderer.Load(EmailRecoverHTML, EmailRecoverTxt); err != nil {
return err
}
r.Authboss.Config.Core.Router.Get("/recover", r.Core.ErrorHandler.Wrap(r.StartGet))
r.Authboss.Config.Core.Router.Post("/recover", r.Core.ErrorHandler.Wrap(r.StartPost))
r.Authboss.Config.Core.Router.Get("/recover/end", r.Core.ErrorHandler.Wrap(r.EndGet))
r.Authboss.Config.Core.Router.Post("/recover/end", r.Core.ErrorHandler.Wrap(r.EndPost))
return nil
}
// StartGet starts the recover procedure by rendering a form for the user.
func (r *Recover) StartGet(w http.ResponseWriter, req *http.Request) error {
return r.Authboss.Config.Core.Responder.Respond(w, req, http.StatusOK, PageRecoverStart, nil)
}
// StartPost starts the recover procedure using values provided from the user
// usually from the StartGet's form.
func (r *Recover) StartPost(w http.ResponseWriter, req *http.Request) error {
logger := r.RequestLogger(req)
validatable, err := r.Authboss.Core.BodyReader.Read(PageRecoverStart, req)
if err != nil {
return err
}
if errs := validatable.Validate(); errs != nil {
logger.Info("recover validation failed")
data := authboss.HTMLData{authboss.DataValidation: authboss.ErrorMap(errs)}
return r.Authboss.Core.Responder.Respond(w, req, http.StatusOK, PageRecoverStart, data)
}
recoverVals := authboss.MustHaveRecoverStartValues(validatable)
user, err := r.Authboss.Storage.Server.Load(req.Context(), recoverVals.GetPID())
if err == authboss.ErrUserNotFound {
logger.Infof("user %s was attempted to be recovered, user does not exist, faking successful response", recoverVals.GetPID())
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: r.Authboss.Config.Paths.RecoverOK,
Success: recoverInitiateSuccessFlash,
}
return r.Authboss.Core.Redirector.Redirect(w, req, ro)
}
ru := authboss.MustBeRecoverable(user)
req = req.WithContext(context.WithValue(req.Context(), authboss.CTXKeyUser, user))
handled, err := r.Authboss.Events.FireBefore(authboss.EventRecoverStart, w, req)
if err != nil {
return err
} else if handled {
return nil
}
selector, verifier, token, err := r.Authboss.Config.Core.CredsGenerator.GenerateCreds()
if err != nil {
return err
}
ru.PutRecoverSelector(selector)
ru.PutRecoverVerifier(verifier)
ru.PutRecoverExpiry(time.Now().UTC().Add(r.Config.Modules.RecoverTokenDuration))
if err := r.Authboss.Storage.Server.Save(req.Context(), ru); err != nil {
return err
}
if r.Authboss.Modules.MailNoGoroutine {
r.SendRecoverEmail(req.Context(), ru.GetEmail(), token)
} else {
go r.SendRecoverEmail(req.Context(), ru.GetEmail(), token)
}
_, err = r.Authboss.Events.FireAfter(authboss.EventRecoverStart, w, req)
if err != nil {
return err
}
logger.Infof("user %s password recovery initiated", ru.GetPID())
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: r.Authboss.Config.Paths.RecoverOK,
Success: recoverInitiateSuccessFlash,
}
return r.Authboss.Core.Redirector.Redirect(w, req, ro)
}
// SendRecoverEmail to a specific e-mail address passing along the encodedToken
// in an escaped URL to the templates.
func (r *Recover) SendRecoverEmail(ctx context.Context, to, encodedToken string) {
logger := r.Authboss.Logger(ctx)
mailURL := r.mailURL(encodedToken)
email := authboss.Email{
To: []string{to},
From: r.Authboss.Config.Mail.From,
FromName: r.Authboss.Config.Mail.FromName,
Subject: r.Authboss.Config.Mail.SubjectPrefix + "Password Reset",
}
ro := authboss.EmailResponseOptions{
HTMLTemplate: EmailRecoverHTML,
TextTemplate: EmailRecoverTxt,
Data: authboss.HTMLData{
DataRecoverURL: mailURL,
},
}
logger.Infof("sending recover e-mail to: %s", to)
if err := r.Authboss.Email(ctx, email, ro); err != nil {
logger.Errorf("failed to recover send e-mail to %s: %+v", to, err)
}
}
// EndGet shows a password recovery form, and it should have the token that
// the user brought in the query parameters in it on submission.
func (r *Recover) EndGet(w http.ResponseWriter, req *http.Request) error {
validatable, err := r.Authboss.Core.BodyReader.Read(PageRecoverMiddle, req)
if err != nil {
return err
}
values := authboss.MustHaveRecoverMiddleValues(validatable)
token := values.GetToken()
data := authboss.HTMLData{
DataRecoverToken: token,
}
return r.Authboss.Config.Core.Responder.Respond(w, req, http.StatusOK, PageRecoverEnd, data)
}
// EndPost retrieves the token
func (r *Recover) EndPost(w http.ResponseWriter, req *http.Request) error {
logger := r.RequestLogger(req)
validatable, err := r.Authboss.Core.BodyReader.Read(PageRecoverEnd, req)
if err != nil {
return err
}
values := authboss.MustHaveRecoverEndValues(validatable)
password := values.GetPassword()
token := values.GetToken()
if errs := validatable.Validate(); errs != nil {
logger.Info("recovery validation failed")
data := authboss.HTMLData{
authboss.DataValidation: authboss.ErrorMap(errs),
DataRecoverToken: token,
}
return r.Config.Core.Responder.Respond(w, req, http.StatusOK, PageRecoverEnd, data)
}
rawToken, err := base64.URLEncoding.DecodeString(token)
if err != nil {
logger.Infof("invalid recover token submitted, base64 decode failed: %+v", err)
return r.invalidToken(PageRecoverEnd, w, req)
}
credsGenerator := r.Authboss.Core.CredsGenerator
if len(rawToken) != credsGenerator.TokenSize() {
logger.Infof("invalid recover token submitted, size was wrong: %d", len(rawToken))
return r.invalidToken(PageRecoverEnd, w, req)
}
selectorBytes, verifierBytes := credsGenerator.ParseToken(string(rawToken))
selector := base64.StdEncoding.EncodeToString(selectorBytes[:])
storer := authboss.EnsureCanRecover(r.Authboss.Config.Storage.Server)
user, err := storer.LoadByRecoverSelector(req.Context(), selector)
if err == authboss.ErrUserNotFound {
logger.Info("invalid recover token submitted, user not found")
return r.invalidToken(PageRecoverEnd, w, req)
} else if err != nil {
return err
}
if time.Now().UTC().After(user.GetRecoverExpiry()) {
logger.Infof("invalid recover token submitted, already expired: %+v", err)
return r.invalidToken(PageRecoverEnd, w, req)
}
dbVerifierBytes, err := base64.StdEncoding.DecodeString(user.GetRecoverVerifier())
if err != nil {
logger.Infof("invalid recover verifier stored in database: %s", user.GetRecoverVerifier())
return r.invalidToken(PageRecoverEnd, w, req)
}
if subtle.ConstantTimeEq(int32(len(verifierBytes)), int32(len(dbVerifierBytes))) != 1 ||
subtle.ConstantTimeCompare(verifierBytes[:], dbVerifierBytes) != 1 {
logger.Info("stored recover verifier does not match provided one")
return r.invalidToken(PageRecoverEnd, w, req)
}
req = req.WithContext(context.WithValue(req.Context(), authboss.CTXKeyUser, user))
handled, err := r.Authboss.Events.FireBefore(authboss.EventRecoverEnd, w, req)
if err != nil {
return err
} else if handled {
return nil
}
pass, err := r.Authboss.Config.Core.Hasher.GenerateHash(password)
if err != nil {
return err
}
user.PutPassword(pass)
user.PutRecoverSelector("") // Don't allow another recovery
user.PutRecoverVerifier("") // Don't allow another recovery
user.PutRecoverExpiry(time.Now().UTC()) // Put current time for those DBs that can't handle 0 time
if err := storer.Save(req.Context(), user); err != nil {
return err
}
successMsg := "Successfully updated password"
_, err = r.Authboss.Events.FireAfter(authboss.EventRecoverEnd, w, req)
if err != nil {
return err
}
if r.Authboss.Config.Modules.RecoverLoginAfterRecovery {
handled, err = r.Events.FireBefore(authboss.EventAuth, w, req)
if err != nil {
return err
} else if handled {
return nil
}
handled, err = r.Events.FireBefore(authboss.EventAuthHijack, w, req)
if err != nil {
return err
} else if handled {
return nil
}
authboss.PutSession(w, authboss.SessionKey, user.GetPID())
successMsg += " and logged in"
handled, err = r.Authboss.Events.FireAfter(authboss.EventAuth, w, req)
if err != nil {
return err
} else if handled {
return nil
}
}
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: r.Authboss.Config.Paths.RecoverOK,
Success: successMsg,
}
return r.Authboss.Config.Core.Redirector.Redirect(w, req, ro)
}
func (r *Recover) invalidToken(page string, w http.ResponseWriter, req *http.Request) error {
errorsAll := []error{errors.New("recovery token is invalid")}
data := authboss.HTMLData{authboss.DataValidation: authboss.ErrorMap(errorsAll)}
return r.Authboss.Core.Responder.Respond(w, req, http.StatusOK, PageRecoverEnd, data)
}
func (r *Recover) mailURL(token string) string {
query := url.Values{FormValueToken: []string{token}}
if len(r.Config.Mail.RootURL) != 0 {
return fmt.Sprintf("%s?%s", r.Config.Mail.RootURL+"/recover/end", query.Encode())
}
p := path.Join(r.Config.Paths.Mount, "recover/end")
return fmt.Sprintf("%s%s?%s", r.Config.Paths.RootURL, p, query.Encode())
}