-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathmocks.go
770 lines (608 loc) · 18.8 KB
/
mocks.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
// Package mocks defines implemented interfaces for testing modules
package mocks
import (
"context"
"golang.org/x/crypto/bcrypt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/friendsofgo/errors"
"github.com/volatiletech/authboss/v3"
)
// User represents all possible fields a authboss User may have
type User struct {
Username string
Email string
Password string
RecoverSelector string
RecoverVerifier string
RecoverTokenExpiry time.Time
ConfirmSelector string
ConfirmVerifier string
Confirmed bool
AttemptCount int
LastAttempt time.Time
Locked time.Time
OAuth2UID string
OAuth2Provider string
OAuth2Token string
OAuth2Refresh string
OAuth2Expiry time.Time
OTPs string
TOTPSecretKey string
TOTPLastCode string
SMSPhoneNumber string
RecoveryCodes string
SMSPhoneNumberSeed string
Arbitrary map[string]string
}
// GetPID from user
func (u User) GetPID() string { return u.Email }
// GetEmail from user
func (u User) GetEmail() string { return u.Email }
// GetUsername from user
func (u User) GetUsername() string { return u.Username }
// GetPassword from user
func (u User) GetPassword() string { return u.Password }
// GetRecoverSelector from user
func (u User) GetRecoverSelector() string { return u.RecoverSelector }
// GetRecoverVerifier from user
func (u User) GetRecoverVerifier() string { return u.RecoverVerifier }
// GetRecoverExpiry from user
func (u User) GetRecoverExpiry() time.Time { return u.RecoverTokenExpiry }
// GetConfirmSelector from user
func (u User) GetConfirmSelector() string { return u.ConfirmSelector }
// GetConfirmVerifier from user
func (u User) GetConfirmVerifier() string { return u.ConfirmVerifier }
// GetConfirmed from user
func (u User) GetConfirmed() bool { return u.Confirmed }
// GetAttemptCount from user
func (u User) GetAttemptCount() int { return u.AttemptCount }
// GetLastAttempt from user
func (u User) GetLastAttempt() time.Time { return u.LastAttempt }
// GetLocked from user
func (u User) GetLocked() time.Time { return u.Locked }
// IsOAuth2User returns true if the user is an oauth2 user
func (u User) IsOAuth2User() bool { return len(u.OAuth2Provider) != 0 }
// GetOAuth2UID from user
func (u User) GetOAuth2UID() string { return u.OAuth2UID }
// GetOAuth2Provider from user
func (u User) GetOAuth2Provider() string { return u.OAuth2Provider }
// GetOAuth2AccessToken from user
func (u User) GetOAuth2AccessToken() string { return u.OAuth2Token }
// GetOAuth2RefreshToken from user
func (u User) GetOAuth2RefreshToken() string { return u.OAuth2Refresh }
// GetOAuth2Expiry from user
func (u User) GetOAuth2Expiry() time.Time { return u.OAuth2Expiry }
// GetArbitrary from user
func (u User) GetArbitrary() map[string]string { return u.Arbitrary }
// GetOTPs from user
func (u User) GetOTPs() string { return u.OTPs }
// GetTOTPSecretKey from user
func (u User) GetTOTPSecretKey() string { return u.TOTPSecretKey }
// GetTOTPLastCode from user
func (u User) GetTOTPLastCode() string { return u.TOTPLastCode }
// GetSMSPhoneNumber from user
func (u User) GetSMSPhoneNumber() string { return u.SMSPhoneNumber }
// GetSMSPhoneNumberSeed from user
func (u User) GetSMSPhoneNumberSeed() string { return u.SMSPhoneNumberSeed }
// GetRecoveryCodes from user
func (u User) GetRecoveryCodes() string { return u.RecoveryCodes }
// PutPID into user
func (u *User) PutPID(email string) { u.Email = email }
// PutUsername into user
func (u *User) PutUsername(username string) { u.Username = username }
// PutEmail into user
func (u *User) PutEmail(email string) { u.Email = email }
// PutPassword into user
func (u *User) PutPassword(password string) { u.Password = password }
// PutRecoverSelector into user
func (u *User) PutRecoverSelector(recoverSelector string) { u.RecoverSelector = recoverSelector }
// PutRecoverVerifier into user
func (u *User) PutRecoverVerifier(recoverVerifier string) { u.RecoverVerifier = recoverVerifier }
// PutRecoverExpiry into user
func (u *User) PutRecoverExpiry(recoverTokenExpiry time.Time) {
u.RecoverTokenExpiry = recoverTokenExpiry
}
// PutConfirmSelector into user
func (u *User) PutConfirmSelector(confirmSelector string) { u.ConfirmSelector = confirmSelector }
// PutConfirmVerifier into user
func (u *User) PutConfirmVerifier(confirmVerifier string) { u.ConfirmVerifier = confirmVerifier }
// PutConfirmed into user
func (u *User) PutConfirmed(confirmed bool) { u.Confirmed = confirmed }
// PutAttemptCount into user
func (u *User) PutAttemptCount(attemptCount int) { u.AttemptCount = attemptCount }
// PutLastAttempt into user
func (u *User) PutLastAttempt(attemptTime time.Time) { u.LastAttempt = attemptTime }
// PutLocked into user
func (u *User) PutLocked(locked time.Time) { u.Locked = locked }
// PutOAuth2UID into user
func (u *User) PutOAuth2UID(uid string) { u.OAuth2UID = uid }
// PutOAuth2Provider into user
func (u *User) PutOAuth2Provider(provider string) { u.OAuth2Provider = provider }
// PutOAuth2AccessToken into user
func (u *User) PutOAuth2AccessToken(token string) { u.OAuth2Token = token }
// PutOAuth2RefreshToken into user
func (u *User) PutOAuth2RefreshToken(refresh string) { u.OAuth2Refresh = refresh }
// PutOAuth2Expiry into user
func (u *User) PutOAuth2Expiry(expiry time.Time) { u.OAuth2Expiry = expiry }
// PutArbitrary into user
func (u *User) PutArbitrary(arb map[string]string) { u.Arbitrary = arb }
// PutOTPs into user
func (u *User) PutOTPs(otps string) { u.OTPs = otps }
// PutTOTPSecretKey into user
func (u *User) PutTOTPSecretKey(key string) { u.TOTPSecretKey = key }
// PutTOTPLastCode into user
func (u *User) PutTOTPLastCode(key string) { u.TOTPLastCode = key }
// PutSMSPhoneNumber into user
func (u *User) PutSMSPhoneNumber(number string) { u.SMSPhoneNumber = number }
// PutRecoveryCodes into user
func (u *User) PutRecoveryCodes(codes string) { u.RecoveryCodes = codes }
// ServerStorer should be valid for any module storer defined in authboss.
type ServerStorer struct {
Users map[string]*User
RMTokens map[string][]string
}
// NewServerStorer constructor
func NewServerStorer() *ServerStorer {
return &ServerStorer{
Users: make(map[string]*User),
RMTokens: make(map[string][]string),
}
}
// New constructs a blank user to later be created
func (s *ServerStorer) New(context.Context) authboss.User {
return &User{}
}
// Create a user
func (s *ServerStorer) Create(ctx context.Context, user authboss.User) error {
u := user.(*User)
if _, ok := s.Users[u.Email]; ok {
return authboss.ErrUserFound
}
s.Users[u.Email] = u
return nil
}
// Load a user
func (s *ServerStorer) Load(ctx context.Context, key string) (authboss.User, error) {
user, ok := s.Users[key]
if ok {
return user, nil
}
return nil, authboss.ErrUserNotFound
}
// Save a user
func (s *ServerStorer) Save(ctx context.Context, user authboss.User) error {
u := user.(*User)
if _, ok := s.Users[u.Email]; !ok {
return authboss.ErrUserNotFound
}
s.Users[u.Email] = u
return nil
}
// NewFromOAuth2 finds a user with the given details, or returns a new one
func (s *ServerStorer) NewFromOAuth2(ctx context.Context, provider string, details map[string]string) (authboss.OAuth2User, error) {
uid := details["uid"]
email := details["email"]
name := details["name"]
pid := authboss.MakeOAuth2PID(provider, uid)
u, ok := s.Users[pid]
if ok {
u.Username = name
u.Email = email
return u, nil
}
return &User{
OAuth2UID: uid,
OAuth2Provider: provider,
Email: email,
Username: name,
}, nil
}
// SaveOAuth2 creates a user if not found, or updates one that exists.
func (s *ServerStorer) SaveOAuth2(ctx context.Context, user authboss.OAuth2User) error {
u := user.(*User)
pid := authboss.MakeOAuth2PID(u.OAuth2Provider, u.OAuth2UID)
// Since we don't have to differentiate between
// insert/update in a map, we just overwrite
s.Users[pid] = u
return nil
}
// LoadByConfirmSelector finds a user by his confirm selector
func (s *ServerStorer) LoadByConfirmSelector(ctx context.Context, selector string) (authboss.ConfirmableUser, error) {
for _, v := range s.Users {
if v.ConfirmSelector == selector {
return v, nil
}
}
return nil, authboss.ErrUserNotFound
}
// LoadByRecoverSelector finds a user by his recover token
func (s *ServerStorer) LoadByRecoverSelector(ctx context.Context, selector string) (authboss.RecoverableUser, error) {
for _, v := range s.Users {
if v.RecoverSelector == selector {
return v, nil
}
}
return nil, authboss.ErrUserNotFound
}
// AddRememberToken for remember me
func (s *ServerStorer) AddRememberToken(ctx context.Context, key, token string) error {
arr := s.RMTokens[key]
s.RMTokens[key] = append(arr, token)
return nil
}
// DelRememberTokens for a user
func (s *ServerStorer) DelRememberTokens(ctx context.Context, key string) error {
delete(s.RMTokens, key)
return nil
}
// UseRememberToken if it exists, deleting it in the process
func (s *ServerStorer) UseRememberToken(ctx context.Context, givenKey, token string) (err error) {
arr, ok := s.RMTokens[givenKey]
if !ok {
return authboss.ErrTokenNotFound
}
for i, tok := range arr {
if tok == token {
if len(arr) == 1 {
delete(s.RMTokens, givenKey)
return nil
}
arr[i] = arr[len(arr)-1]
s.RMTokens[givenKey] = arr[:len(arr)-2]
return nil
}
}
return authboss.ErrTokenNotFound
}
// FailStorer is used for testing module initialize functions that
// recover more than the base storer
type FailStorer struct {
User
}
// Create fails
func (FailStorer) Create(context.Context) error {
return errors.New("fail storer: create")
}
// Save fails
func (FailStorer) Save(context.Context) error {
return errors.New("fail storer: put")
}
// Load fails
func (FailStorer) Load(context.Context) error {
return errors.New("fail storer: get")
}
// ClientState is used for testing the client stores on context
type ClientState struct {
Values map[string]string
GetShouldFail bool
}
// NewClientState constructs a ClientStorer
func NewClientState(data ...string) *ClientState {
if len(data) != 0 && len(data)%2 != 0 {
panic("It should be a key value list of arguments.")
}
values := make(map[string]string)
for i := 0; i < len(data)-1; i += 2 {
values[data[i]] = data[i+1]
}
return &ClientState{Values: values}
}
// Get a key's value
func (m *ClientState) Get(key string) (string, bool) {
if m.GetShouldFail {
return "", false
}
v, ok := m.Values[key]
return v, ok
}
// Put a value
func (m *ClientState) Put(key, val string) { m.Values[key] = val }
// Del a key/value pair
func (m *ClientState) Del(key string) { delete(m.Values, key) }
// ClientStateRW stores things that would originally
// go in a session, or a map, in memory!
type ClientStateRW struct {
ClientValues map[string]string
}
// NewClientRW takes the data from a client state
// and returns.
func NewClientRW() *ClientStateRW {
return &ClientStateRW{
ClientValues: make(map[string]string),
}
}
// ReadState from memory
func (c *ClientStateRW) ReadState(*http.Request) (authboss.ClientState, error) {
return &ClientState{Values: c.ClientValues}, nil
}
// WriteState to memory
func (c *ClientStateRW) WriteState(w http.ResponseWriter, cstate authboss.ClientState, cse []authboss.ClientStateEvent) error {
for _, e := range cse {
switch e.Kind {
case authboss.ClientStateEventPut:
c.ClientValues[e.Key] = e.Value
case authboss.ClientStateEventDel:
delete(c.ClientValues, e.Key)
case authboss.ClientStateEventDelAll:
c.ClientValues = make(map[string]string)
}
}
return nil
}
// Request returns a new request with optional key-value body (form-post)
func Request(method string, postKeyValues ...string) *http.Request {
var body io.Reader
location := "http://localhost"
if len(postKeyValues) > 0 {
urlValues := make(url.Values)
for i := 0; i < len(postKeyValues); i += 2 {
urlValues.Set(postKeyValues[i], postKeyValues[i+1])
}
if method == "POST" || method == "PUT" {
body = strings.NewReader(urlValues.Encode())
} else {
location += "?" + urlValues.Encode()
}
}
req, err := http.NewRequest(method, location, body)
if err != nil {
panic(err.Error())
}
if len(postKeyValues) > 0 {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
return req
}
// Mailer helps simplify mailer testing by storing the last sent email
type Mailer struct {
Last authboss.Email
SendErr string
}
// NewMailer constructs a mailer
func NewMailer() *Mailer {
return &Mailer{}
}
// Send an e-mail
func (m *Mailer) Send(ctx context.Context, email authboss.Email) error {
if len(m.SendErr) > 0 {
return errors.New(m.SendErr)
}
m.Last = email
return nil
}
// AfterCallback is a callback that knows if it was called
type AfterCallback struct {
HasBeenCalled bool
Fn authboss.EventHandler
}
// NewAfterCallback constructs a new aftercallback.
func NewAfterCallback() *AfterCallback {
m := AfterCallback{}
m.Fn = func(http.ResponseWriter, *http.Request, bool) (bool, error) {
m.HasBeenCalled = true
return false, nil
}
return &m
}
// Renderer mock
type Renderer struct {
Pages []string
// Render call variables
Context context.Context
Page string
Data authboss.HTMLData
}
// HasLoadedViews ensures the views were loaded
func (r *Renderer) HasLoadedViews(pages ...string) error {
if len(r.Pages) != len(pages) {
return errors.Errorf("want: %d loaded views, got: %d", len(pages), len(r.Pages))
}
for i, want := range pages {
got := r.Pages[i]
if want != got {
return errors.Errorf("want: %s [%d], got: %s", want, i, got)
}
}
return nil
}
// Load nothing but store the pages that were loaded
func (r *Renderer) Load(pages ...string) error {
r.Pages = append(r.Pages, pages...)
return nil
}
// Render nothing, but record the arguments into the renderer
func (r *Renderer) Render(ctx context.Context, page string, data authboss.HTMLData) ([]byte, string, error) {
r.Context = ctx
r.Page = page
r.Data = data
return nil, "text/html", nil
}
// Responder records how a request was responded to
type Responder struct {
Status int
Page string
Data authboss.HTMLData
}
// Respond stores the arguments in the struct
func (r *Responder) Respond(w http.ResponseWriter, req *http.Request, code int, page string, data authboss.HTMLData) error {
r.Status = code
r.Page = page
r.Data = data
return nil
}
// Redirector stores the redirect options passed to it and writes the Code
// to the ResponseWriter.
type Redirector struct {
Options authboss.RedirectOptions
}
// Redirect a request
func (r *Redirector) Redirect(w http.ResponseWriter, req *http.Request, ro authboss.RedirectOptions) error {
r.Options = ro
if len(ro.RedirectPath) == 0 {
panic("no redirect path on redirect call")
}
http.Redirect(w, req, ro.RedirectPath, ro.Code)
return nil
}
// Emailer that holds the options it was given
type Emailer struct {
Email authboss.Email
}
// Send an e-mail
func (e *Emailer) Send(ctx context.Context, email authboss.Email) error {
e.Email = email
return nil
}
// BodyReader reads the body of a request and returns some values
type BodyReader struct {
Return authboss.Validator
}
// Read the return values
func (b BodyReader) Read(page string, r *http.Request) (authboss.Validator, error) {
return b.Return, nil
}
// Values is returned from the BodyReader
type Values struct {
PID string
Password string
Token string
Code string
Recovery string
PhoneNumber string
Remember bool
Errors []error
}
// GetPID from values
func (v Values) GetPID() string {
return v.PID
}
// GetPassword from values
func (v Values) GetPassword() string {
return v.Password
}
// GetToken from values
func (v Values) GetToken() string {
return v.Token
}
// GetCode from values
func (v Values) GetCode() string {
return v.Code
}
// GetPhoneNumber from values
func (v Values) GetPhoneNumber() string {
return v.PhoneNumber
}
// GetRecoveryCode from values
func (v Values) GetRecoveryCode() string {
return v.Recovery
}
// GetShouldRemember gets the value that tells
// the remember module if it should remember the user
func (v Values) GetShouldRemember() bool {
return v.Remember
}
// Validate the values
func (v Values) Validate() []error {
return v.Errors
}
// ArbValues is arbitrary value storage
type ArbValues struct {
Values map[string]string
Errors []error
}
// GetPID gets the pid
func (a ArbValues) GetPID() string {
return a.Values["email"]
}
// GetPassword gets the password
func (a ArbValues) GetPassword() string {
return a.Values["password"]
}
// GetValues returns all values
func (a ArbValues) GetValues() map[string]string {
return a.Values
}
// Validate nothing
func (a ArbValues) Validate() []error {
return a.Errors
}
// Logger logs to the void
type Logger struct {
}
// Info logging
func (l Logger) Info(string) {}
// Error logging
func (l Logger) Error(string) {}
// Router records the routes that were registered
type Router struct {
Gets []string
Posts []string
Deletes []string
}
// ServeHTTP does nothing
func (Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
// Get records the path in the router
func (r *Router) Get(path string, _ http.Handler) {
r.Gets = append(r.Gets, path)
}
// Post records the path in the router
func (r *Router) Post(path string, _ http.Handler) {
r.Posts = append(r.Posts, path)
}
// Delete records the path in the router
func (r *Router) Delete(path string, _ http.Handler) {
r.Deletes = append(r.Deletes, path)
}
// HasGets ensures all gets routes are present
func (r *Router) HasGets(gets ...string) error {
return r.hasRoutes(gets, r.Gets)
}
// HasPosts ensures all gets routes are present
func (r *Router) HasPosts(posts ...string) error {
return r.hasRoutes(posts, r.Posts)
}
// HasDeletes ensures all gets routes are present
func (r *Router) HasDeletes(deletes ...string) error {
return r.hasRoutes(deletes, r.Deletes)
}
func (r *Router) hasRoutes(want []string, got []string) error {
if len(got) != len(want) {
return errors.Errorf("want: %d get routes, got: %d", len(want), len(got))
}
for i, w := range want {
g := got[i]
if w != g {
return errors.Errorf("wanted route: %s [%d], but got: %s", w, i, g)
}
}
return nil
}
// ErrorHandler just holds the last error
type ErrorHandler struct {
Error error
}
// Wrap an http method
func (e *ErrorHandler) Wrap(handler func(w http.ResponseWriter, r *http.Request) error) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := handler(w, r); err != nil {
e.Error = err
}
})
}
// Hasher is actually just a normal bcrypt hasher
type Hasher struct{}
func (m Hasher) GenerateHash(s string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hash), nil
}
func (m Hasher) CompareHashAndPassword(hashedPassword, password string) error {
return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
}