-
Notifications
You must be signed in to change notification settings - Fork 402
/
service.go
3370 lines (2802 loc) · 100 KB
/
service.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package console
import (
"context"
"database/sql"
"errors"
"fmt"
"math"
"net/http"
"net/mail"
"sort"
"strings"
"time"
"github.com/spacemonkeygo/monkit/v3"
"github.com/spf13/pflag"
"github.com/stripe/stripe-go/v72"
"github.com/zeebo/errs"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
"storj.io/common/currency"
"storj.io/common/macaroon"
"storj.io/common/memory"
"storj.io/common/uuid"
"storj.io/private/cfgstruct"
"storj.io/storj/private/api"
"storj.io/storj/private/blockchain"
"storj.io/storj/private/post"
"storj.io/storj/satellite/accounting"
"storj.io/storj/satellite/analytics"
"storj.io/storj/satellite/buckets"
"storj.io/storj/satellite/console/consoleauth"
"storj.io/storj/satellite/mailservice"
"storj.io/storj/satellite/payments"
"storj.io/storj/satellite/payments/billing"
"storj.io/storj/satellite/satellitedb/dbx"
)
var mon = monkit.Package()
const (
// maxLimit specifies the limit for all paged queries.
maxLimit = 50
// TestPasswordCost is the hashing complexity to use for testing.
TestPasswordCost = bcrypt.MinCost
)
// Error messages.
const (
unauthorizedErrMsg = "You are not authorized to perform this action"
emailUsedErrMsg = "This email is already in use, try another"
emailNotFoundErrMsg = "There are no users with the specified email"
passwordRecoveryTokenIsExpiredErrMsg = "Your password recovery link has expired, please request another one"
credentialsErrMsg = "Your login credentials are incorrect, please try again"
generateSessionTokenErrMsg = "Failed to generate session token"
failedToRetrieveUserErrMsg = "Failed to retrieve user from database"
apiKeyCredentialsErrMsg = "Your API Key is incorrect"
changePasswordErrMsg = "Your old password is incorrect, please try again"
passwordTooShortErrMsg = "Your password needs to be at least %d characters long"
passwordTooLongErrMsg = "Your password must be no longer than %d characters"
projectOwnerDeletionForbiddenErrMsg = "%s is a project owner and can not be deleted"
apiKeyWithNameExistsErrMsg = "An API Key with this name already exists in this project, please use a different name"
apiKeyWithNameDoesntExistErrMsg = "An API Key with this name doesn't exist in this project."
teamMemberDoesNotExistErrMsg = `There is no account on this Satellite for the user(s) you have entered.
Please add team members with active accounts`
activationTokenExpiredErrMsg = "This activation token has expired, please request another one"
usedRegTokenErrMsg = "This registration token has already been used"
projLimitErrMsg = "Sorry, project creation is limited for your account. Please contact support!"
projNameErrMsg = "The new project must have a name you haven't used before!"
)
var (
// Error describes internal console error.
Error = errs.Class("console service")
// ErrUnauthorized is error class for authorization related errors.
ErrUnauthorized = errs.Class("unauthorized")
// ErrNoMembership is error type of not belonging to a specific project.
ErrNoMembership = errs.Class("no membership")
// ErrTokenExpiration is error type of token reached expiration time.
ErrTokenExpiration = errs.Class("token expiration")
// ErrTokenInvalid is error type of tokens which are invalid.
ErrTokenInvalid = errs.Class("invalid token")
// ErrProjLimit is error type of project limit.
ErrProjLimit = errs.Class("project limit")
// ErrUsage is error type of project usage.
ErrUsage = errs.Class("project usage")
// ErrLoginCredentials occurs when provided invalid login credentials.
ErrLoginCredentials = errs.Class("login credentials")
// ErrChangePassword occurs when provided old password is incorrect.
ErrChangePassword = errs.Class("change password")
// ErrEmailUsed is error type that occurs on repeating auth attempts with email.
ErrEmailUsed = errs.Class("email used")
// ErrEmailNotFound occurs when no users have the specified email.
ErrEmailNotFound = errs.Class("email not found")
// ErrNoAPIKey is error type that occurs when there is no api key found.
ErrNoAPIKey = errs.Class("no api key found")
// ErrAPIKeyRequest is returned when there is an error parsing a request for api keys.
ErrAPIKeyRequest = errs.Class("api key request")
// ErrRegToken describes registration token errors.
ErrRegToken = errs.Class("registration token")
// ErrCaptcha describes captcha validation errors.
ErrCaptcha = errs.Class("captcha validation")
// ErrRecoveryToken describes account recovery token errors.
ErrRecoveryToken = errs.Class("recovery token")
// ErrProjName is error that occurs with reused project names.
ErrProjName = errs.Class("project name")
// ErrPurchaseDesc is error that occurs when something is wrong with Purchase description.
ErrPurchaseDesc = errs.Class("purchase description")
// ErrAlreadyHasPackage is error that occurs when a user tries to update package, but already has one.
ErrAlreadyHasPackage = errs.Class("user already has package")
)
// Service is handling accounts related logic.
//
// architecture: Service
type Service struct {
log, auditLogger *zap.Logger
store DB
restKeys RESTKeys
projectAccounting accounting.ProjectAccounting
projectUsage *accounting.Service
buckets buckets.DB
accounts payments.Accounts
depositWallets payments.DepositWallets
billing billing.TransactionsDB
registrationCaptchaHandler CaptchaHandler
loginCaptchaHandler CaptchaHandler
analytics *analytics.Service
tokens *consoleauth.Service
mailService *mailservice.Service
satelliteAddress string
config Config
}
func init() {
var c Config
cfgstruct.Bind(pflag.NewFlagSet("", pflag.PanicOnError), &c, cfgstruct.UseTestDefaults())
if c.PasswordCost != TestPasswordCost {
panic("invalid test constant defined in struct tag")
}
cfgstruct.Bind(pflag.NewFlagSet("", pflag.PanicOnError), &c, cfgstruct.UseReleaseDefaults())
if c.PasswordCost != 0 {
panic("invalid release constant defined in struct tag. should be 0 (=automatic)")
}
}
// Config keeps track of core console service configuration parameters.
type Config struct {
PasswordCost int `help:"password hashing cost (0=automatic)" testDefault:"4" default:"0"`
OpenRegistrationEnabled bool `help:"enable open registration" default:"false" testDefault:"true"`
DefaultProjectLimit int `help:"default project limits for users" default:"1" testDefault:"5"`
AsOfSystemTimeDuration time.Duration `help:"default duration for AS OF SYSTEM TIME" devDefault:"-5m" releaseDefault:"-5m" testDefault:"0"`
LoginAttemptsWithoutPenalty int `help:"number of times user can try to login without penalty" default:"3"`
FailedLoginPenalty float64 `help:"incremental duration of penalty for failed login attempts in minutes" default:"2.0"`
UsageLimits UsageLimitsConfig
Captcha CaptchaConfig
Session SessionConfig
}
// CaptchaConfig contains configurations for login/registration captcha system.
type CaptchaConfig struct {
Login MultiCaptchaConfig `json:"login"`
Registration MultiCaptchaConfig `json:"registration"`
}
// MultiCaptchaConfig contains configurations for Recaptcha and Hcaptcha systems.
type MultiCaptchaConfig struct {
Recaptcha SingleCaptchaConfig `json:"recaptcha"`
Hcaptcha SingleCaptchaConfig `json:"hcaptcha"`
}
// SingleCaptchaConfig contains configurations abstract captcha system.
type SingleCaptchaConfig struct {
Enabled bool `help:"whether or not captcha is enabled" default:"false" json:"enabled"`
SiteKey string `help:"captcha site key" json:"siteKey"`
SecretKey string `help:"captcha secret key" json:"-"`
}
// SessionConfig contains configurations for session management.
type SessionConfig struct {
InactivityTimerEnabled bool `help:"indicates if session can be timed out due inactivity" default:"true"`
InactivityTimerDuration int `help:"inactivity timer delay in seconds" default:"600"`
InactivityTimerViewerEnabled bool `help:"indicates whether remaining session time is shown for debugging" default:"false"`
Duration time.Duration `help:"duration a session is valid for (superseded by inactivity timer delay if inactivity timer is enabled)" default:"168h"`
}
// Payments separates all payment related functionality.
type Payments struct {
service *Service
}
// NewService returns new instance of Service.
func NewService(log *zap.Logger, store DB, restKeys RESTKeys, projectAccounting accounting.ProjectAccounting, projectUsage *accounting.Service, buckets buckets.DB, accounts payments.Accounts, depositWallets payments.DepositWallets, billing billing.TransactionsDB, analytics *analytics.Service, tokens *consoleauth.Service, mailService *mailservice.Service, satelliteAddress string, config Config) (*Service, error) {
if store == nil {
return nil, errs.New("store can't be nil")
}
if log == nil {
return nil, errs.New("log can't be nil")
}
if config.PasswordCost == 0 {
config.PasswordCost = bcrypt.DefaultCost
}
// We have two separate captcha handlers for login and registration.
// We want to easily swap between captchas independently.
// For example, google recaptcha for login screen and hcaptcha for registration screen.
var registrationCaptchaHandler CaptchaHandler
if config.Captcha.Registration.Recaptcha.Enabled {
registrationCaptchaHandler = NewDefaultCaptcha(Recaptcha, config.Captcha.Registration.Recaptcha.SecretKey)
} else if config.Captcha.Registration.Hcaptcha.Enabled {
registrationCaptchaHandler = NewDefaultCaptcha(Hcaptcha, config.Captcha.Registration.Hcaptcha.SecretKey)
}
var loginCaptchaHandler CaptchaHandler
if config.Captcha.Login.Recaptcha.Enabled {
loginCaptchaHandler = NewDefaultCaptcha(Recaptcha, config.Captcha.Login.Recaptcha.SecretKey)
} else if config.Captcha.Login.Hcaptcha.Enabled {
loginCaptchaHandler = NewDefaultCaptcha(Hcaptcha, config.Captcha.Login.Hcaptcha.SecretKey)
}
return &Service{
log: log,
auditLogger: log.Named("auditlog"),
store: store,
restKeys: restKeys,
projectAccounting: projectAccounting,
projectUsage: projectUsage,
buckets: buckets,
accounts: accounts,
depositWallets: depositWallets,
billing: billing,
registrationCaptchaHandler: registrationCaptchaHandler,
loginCaptchaHandler: loginCaptchaHandler,
analytics: analytics,
tokens: tokens,
mailService: mailService,
satelliteAddress: satelliteAddress,
config: config,
}, nil
}
func getRequestingIP(ctx context.Context) (source, forwardedFor string) {
if req := GetRequest(ctx); req != nil {
return req.RemoteAddr, req.Header.Get("X-Forwarded-For")
}
return "", ""
}
func (s *Service) auditLog(ctx context.Context, operation string, userID *uuid.UUID, email string, extra ...zap.Field) {
sourceIP, forwardedForIP := getRequestingIP(ctx)
fields := append(
make([]zap.Field, 0, len(extra)+5),
zap.String("operation", operation),
zap.String("source-ip", sourceIP),
zap.String("forwarded-for-ip", forwardedForIP),
)
if userID != nil {
fields = append(fields, zap.String("userID", userID.String()))
}
if email != "" {
fields = append(fields, zap.String("email", email))
}
fields = append(fields, fields...)
s.auditLogger.Info("console activity", fields...)
}
func (s *Service) getUserAndAuditLog(ctx context.Context, operation string, extra ...zap.Field) (*User, error) {
user, err := GetUser(ctx)
if err != nil {
sourceIP, forwardedForIP := getRequestingIP(ctx)
s.auditLogger.Info("console activity unauthorized",
append(append(
make([]zap.Field, 0, len(extra)+4),
zap.String("operation", operation),
zap.Error(err),
zap.String("source-ip", sourceIP),
zap.String("forwarded-for-ip", forwardedForIP),
), extra...)...)
return nil, err
}
s.auditLog(ctx, operation, &user.ID, user.Email, extra...)
return user, nil
}
// Payments separates all payment related functionality.
func (s *Service) Payments() Payments {
return Payments{service: s}
}
// SetupAccount creates payment account for authorized user.
func (payment Payments) SetupAccount(ctx context.Context) (_ payments.CouponType, err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "setup payment account")
if err != nil {
return payments.NoCoupon, Error.Wrap(err)
}
return payment.service.accounts.Setup(ctx, user.ID, user.Email, user.SignupPromoCode)
}
// AccountBalance return account balance.
func (payment Payments) AccountBalance(ctx context.Context) (balance payments.Balance, err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "get account balance")
if err != nil {
return payments.Balance{}, Error.Wrap(err)
}
return payment.service.accounts.Balances().Get(ctx, user.ID)
}
// AddCreditCard is used to save new credit card and attach it to payment account.
func (payment Payments) AddCreditCard(ctx context.Context, creditCardToken string) (card payments.CreditCard, err error) {
defer mon.Task()(&ctx, creditCardToken)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "add credit card")
if err != nil {
return payments.CreditCard{}, Error.Wrap(err)
}
card, err = payment.service.accounts.CreditCards().Add(ctx, user.ID, creditCardToken)
if err != nil {
return payments.CreditCard{}, Error.Wrap(err)
}
payment.service.analytics.TrackCreditCardAdded(user.ID, user.Email)
if !user.PaidTier {
// put this user into the paid tier and convert projects to upgraded limits.
err = payment.service.store.Users().UpdatePaidTier(ctx, user.ID, true,
payment.service.config.UsageLimits.Bandwidth.Paid,
payment.service.config.UsageLimits.Storage.Paid,
payment.service.config.UsageLimits.Segment.Paid,
payment.service.config.UsageLimits.Project.Paid,
)
if err != nil {
return payments.CreditCard{}, Error.Wrap(err)
}
projects, err := payment.service.store.Projects().GetOwn(ctx, user.ID)
if err != nil {
return payments.CreditCard{}, Error.Wrap(err)
}
for _, project := range projects {
if project.StorageLimit == nil || *project.StorageLimit < payment.service.config.UsageLimits.Storage.Paid {
project.StorageLimit = new(memory.Size)
*project.StorageLimit = payment.service.config.UsageLimits.Storage.Paid
}
if project.BandwidthLimit == nil || *project.BandwidthLimit < payment.service.config.UsageLimits.Bandwidth.Paid {
project.BandwidthLimit = new(memory.Size)
*project.BandwidthLimit = payment.service.config.UsageLimits.Bandwidth.Paid
}
if project.SegmentLimit == nil || *project.SegmentLimit < payment.service.config.UsageLimits.Segment.Paid {
*project.SegmentLimit = payment.service.config.UsageLimits.Segment.Paid
}
err = payment.service.store.Projects().Update(ctx, &project)
if err != nil {
return payments.CreditCard{}, Error.Wrap(err)
}
}
}
return card, nil
}
// MakeCreditCardDefault makes a credit card default payment method.
func (payment Payments) MakeCreditCardDefault(ctx context.Context, cardID string) (err error) {
defer mon.Task()(&ctx, cardID)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "make credit card default")
if err != nil {
return Error.Wrap(err)
}
return payment.service.accounts.CreditCards().MakeDefault(ctx, user.ID, cardID)
}
// ProjectsCharges returns how much money current user will be charged for each project which he owns.
func (payment Payments) ProjectsCharges(ctx context.Context, since, before time.Time) (_ payments.ProjectChargesResponse, err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "project charges")
if err != nil {
return nil, Error.Wrap(err)
}
return payment.service.accounts.ProjectCharges(ctx, user.ID, since, before)
}
// ListCreditCards returns a list of credit cards for a given payment account.
func (payment Payments) ListCreditCards(ctx context.Context) (_ []payments.CreditCard, err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "list credit cards")
if err != nil {
return nil, Error.Wrap(err)
}
return payment.service.accounts.CreditCards().List(ctx, user.ID)
}
// RemoveCreditCard is used to detach a credit card from payment account.
func (payment Payments) RemoveCreditCard(ctx context.Context, cardID string) (err error) {
defer mon.Task()(&ctx, cardID)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "remove credit card")
if err != nil {
return Error.Wrap(err)
}
return payment.service.accounts.CreditCards().Remove(ctx, user.ID, cardID)
}
// BillingHistory returns a list of billing history items for payment account.
func (payment Payments) BillingHistory(ctx context.Context) (billingHistory []*BillingHistoryItem, err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "get billing history")
if err != nil {
return nil, Error.Wrap(err)
}
invoices, couponUsages, err := payment.service.accounts.Invoices().ListWithDiscounts(ctx, user.ID)
if err != nil {
return nil, Error.Wrap(err)
}
for _, invoice := range invoices {
billingHistory = append(billingHistory, &BillingHistoryItem{
ID: invoice.ID,
Description: invoice.Description,
Amount: invoice.Amount,
Status: invoice.Status,
Link: invoice.Link,
End: invoice.End,
Start: invoice.Start,
Type: Invoice,
})
}
txsInfos, err := payment.service.accounts.StorjTokens().ListTransactionInfos(ctx, user.ID)
if err != nil {
return nil, Error.Wrap(err)
}
for _, info := range txsInfos {
billingHistory = append(billingHistory, &BillingHistoryItem{
ID: info.ID.String(),
Description: "STORJ Token Deposit",
Amount: info.AmountCents,
Received: info.ReceivedCents,
Status: info.Status.String(),
Link: info.Link,
Start: info.CreatedAt,
End: info.ExpiresAt,
Type: Transaction,
})
}
charges, err := payment.service.accounts.Charges(ctx, user.ID)
if err != nil {
return nil, Error.Wrap(err)
}
for _, charge := range charges {
desc := fmt.Sprintf("Payment(%s %s)", charge.CardInfo.Brand, charge.CardInfo.LastFour)
billingHistory = append(billingHistory, &BillingHistoryItem{
ID: charge.ID,
Description: desc,
Amount: charge.Amount,
Start: charge.CreatedAt,
Type: Charge,
})
}
for _, usage := range couponUsages {
desc := "Coupon"
if usage.Coupon.Name != "" {
desc = usage.Coupon.Name
}
if usage.Coupon.PromoCode != "" {
desc += " (" + usage.Coupon.PromoCode + ")"
}
billingHistory = append(billingHistory, &BillingHistoryItem{
Description: desc,
Amount: usage.Amount,
Start: usage.PeriodStart,
End: usage.PeriodEnd,
Type: Coupon,
})
}
bonuses, err := payment.service.accounts.StorjTokens().ListDepositBonuses(ctx, user.ID)
if err != nil {
return nil, Error.Wrap(err)
}
for _, bonus := range bonuses {
billingHistory = append(billingHistory,
&BillingHistoryItem{
Description: fmt.Sprintf("%d%% Bonus for STORJ Token Deposit", bonus.Percentage),
Amount: bonus.AmountCents,
Status: "Added to balance",
Start: bonus.CreatedAt,
Type: DepositBonus,
},
)
}
sort.SliceStable(billingHistory,
func(i, j int) bool {
return billingHistory[i].Start.After(billingHistory[j].Start)
},
)
return billingHistory, nil
}
// checkOutstandingInvoice returns if the payment account has any unpaid/outstanding invoices or/and invoice items.
func (payment Payments) checkOutstandingInvoice(ctx context.Context) (err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "get outstanding invoices")
if err != nil {
return err
}
invoices, err := payment.service.accounts.Invoices().List(ctx, user.ID)
if err != nil {
return err
}
if len(invoices) > 0 {
for _, invoice := range invoices {
if invoice.Status != string(stripe.InvoiceStatusPaid) {
return ErrUsage.New("user has unpaid/pending invoices")
}
}
}
hasItems, err := payment.service.accounts.Invoices().CheckPendingItems(ctx, user.ID)
if err != nil {
return err
}
if hasItems {
return ErrUsage.New("user has pending invoice items")
}
return nil
}
// checkProjectInvoicingStatus returns error if for the given project there are outstanding project records and/or usage
// which have not been applied/invoiced yet (meaning sent over to stripe).
func (payment Payments) checkProjectInvoicingStatus(ctx context.Context, projectID uuid.UUID) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = payment.service.getUserAndAuditLog(ctx, "project invoicing status")
if err != nil {
return Error.Wrap(err)
}
return payment.service.accounts.CheckProjectInvoicingStatus(ctx, projectID)
}
// checkProjectUsageStatus returns error if for the given project there is some usage for current or previous month.
func (payment Payments) checkProjectUsageStatus(ctx context.Context, projectID uuid.UUID) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = payment.service.getUserAndAuditLog(ctx, "project usage status")
if err != nil {
return Error.Wrap(err)
}
return payment.service.accounts.CheckProjectUsageStatus(ctx, projectID)
}
// ApplyCoupon applies a coupon to an account based on couponID.
func (payment Payments) ApplyCoupon(ctx context.Context, couponID string) (coupon *payments.Coupon, err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "apply coupon")
if err != nil {
return nil, Error.Wrap(err)
}
coupon, err = payment.service.accounts.Coupons().ApplyCoupon(ctx, user.ID, couponID)
if err != nil {
return coupon, Error.Wrap(err)
}
return coupon, nil
}
// ApplyFreeTierCoupon applies the default free tier coupon to an account.
func (payment Payments) ApplyFreeTierCoupon(ctx context.Context) (coupon *payments.Coupon, err error) {
defer mon.Task()(&ctx)(&err)
user, err := GetUser(ctx)
if err != nil {
return nil, Error.Wrap(err)
}
coupon, err = payment.service.accounts.Coupons().ApplyFreeTierCoupon(ctx, user.ID)
if err != nil {
return coupon, Error.Wrap(err)
}
return coupon, nil
}
// ApplyCouponCode applies a coupon code to a Stripe customer
// and returns the coupon corresponding to the code.
func (payment Payments) ApplyCouponCode(ctx context.Context, couponCode string) (coupon *payments.Coupon, err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "apply coupon code")
if err != nil {
return nil, Error.Wrap(err)
}
coupon, err = payment.service.accounts.Coupons().ApplyCouponCode(ctx, user.ID, couponCode)
if err != nil {
return nil, Error.Wrap(err)
}
return coupon, nil
}
// GetCoupon returns the coupon applied to the user's account.
func (payment Payments) GetCoupon(ctx context.Context) (coupon *payments.Coupon, err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "get coupon")
if err != nil {
return nil, Error.Wrap(err)
}
coupon, err = payment.service.accounts.Coupons().GetByUserID(ctx, user.ID)
if err != nil {
return nil, Error.Wrap(err)
}
return coupon, nil
}
// AttemptPayOverdueInvoices attempts to pay a user's open, overdue invoices.
func (payment Payments) AttemptPayOverdueInvoices(ctx context.Context) (err error) {
defer mon.Task()(&ctx)(&err)
user, err := payment.service.getUserAndAuditLog(ctx, "attempt to pay overdue invoices")
if err != nil {
return Error.Wrap(err)
}
err = payment.service.accounts.Invoices().AttemptPayOverdueInvoices(ctx, user.ID)
if err != nil {
return Error.Wrap(err)
}
return nil
}
// checkRegistrationSecret returns a RegistrationToken if applicable (nil if not), and an error
// if and only if the registration shouldn't proceed.
func (s *Service) checkRegistrationSecret(ctx context.Context, tokenSecret RegistrationSecret) (*RegistrationToken, error) {
if s.config.OpenRegistrationEnabled && tokenSecret.IsZero() {
// in this case we're going to let the registration happen without a token
return nil, nil
}
// in all other cases, require a registration token
registrationToken, err := s.store.RegistrationTokens().GetBySecret(ctx, tokenSecret)
if err != nil {
return nil, ErrUnauthorized.Wrap(err)
}
// if a registration token is already associated with an user ID, that means the token is already used
// we should terminate the account creation process and return an error
if registrationToken.OwnerID != nil {
return nil, ErrValidation.New(usedRegTokenErrMsg)
}
return registrationToken, nil
}
// CreateUser gets password hash value and creates new inactive User.
func (s *Service) CreateUser(ctx context.Context, user CreateUser, tokenSecret RegistrationSecret) (u *User, err error) {
defer mon.Task()(&ctx)(&err)
var captchaScore *float64
mon.Counter("create_user_attempt").Inc(1) //mon:locked
if s.config.Captcha.Registration.Recaptcha.Enabled || s.config.Captcha.Registration.Hcaptcha.Enabled {
valid, score, err := s.registrationCaptchaHandler.Verify(ctx, user.CaptchaResponse, user.IP)
if err != nil {
mon.Counter("create_user_captcha_error").Inc(1) //mon:locked
s.log.Error("captcha authorization failed", zap.Error(err))
return nil, ErrCaptcha.Wrap(err)
}
if !valid {
mon.Counter("create_user_captcha_unsuccessful").Inc(1) //mon:locked
return nil, ErrCaptcha.New("captcha validation unsuccessful")
}
captchaScore = score
}
if err := user.IsValid(); err != nil {
// NOTE: error is already wrapped with an appropriated class.
return nil, err
}
registrationToken, err := s.checkRegistrationSecret(ctx, tokenSecret)
if err != nil {
return nil, ErrRegToken.Wrap(err)
}
verified, unverified, err := s.store.Users().GetByEmailWithUnverified(ctx, user.Email)
if err != nil {
return nil, Error.Wrap(err)
}
if verified != nil {
mon.Counter("create_user_duplicate_verified").Inc(1) //mon:locked
return nil, ErrEmailUsed.New(emailUsedErrMsg)
} else if len(unverified) != 0 {
mon.Counter("create_user_duplicate_unverified").Inc(1) //mon:locked
return nil, ErrEmailUsed.New(emailUsedErrMsg)
}
hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), s.config.PasswordCost)
if err != nil {
return nil, Error.Wrap(err)
}
// store data
err = s.store.WithTx(ctx, func(ctx context.Context, tx DBTx) error {
userID, err := uuid.New()
if err != nil {
return Error.Wrap(err)
}
newUser := &User{
ID: userID,
Email: user.Email,
FullName: user.FullName,
ShortName: user.ShortName,
PasswordHash: hash,
Status: Inactive,
IsProfessional: user.IsProfessional,
Position: user.Position,
CompanyName: user.CompanyName,
EmployeeCount: user.EmployeeCount,
HaveSalesContact: user.HaveSalesContact,
SignupPromoCode: user.SignupPromoCode,
SignupCaptcha: captchaScore,
}
if user.UserAgent != nil {
newUser.UserAgent = user.UserAgent
}
if registrationToken != nil {
newUser.ProjectLimit = registrationToken.ProjectLimit
} else {
newUser.ProjectLimit = s.config.UsageLimits.Project.Free
}
// TODO: move the project limits into the registration token.
newUser.ProjectStorageLimit = s.config.UsageLimits.Storage.Free.Int64()
newUser.ProjectBandwidthLimit = s.config.UsageLimits.Bandwidth.Free.Int64()
newUser.ProjectSegmentLimit = s.config.UsageLimits.Segment.Free
u, err = tx.Users().Insert(ctx,
newUser,
)
if err != nil {
return Error.Wrap(err)
}
if registrationToken != nil {
err = tx.RegistrationTokens().UpdateOwner(ctx, registrationToken.Secret, u.ID)
if err != nil {
return Error.Wrap(err)
}
}
return nil
})
if err != nil {
return nil, Error.Wrap(err)
}
s.auditLog(ctx, "create user", nil, user.Email)
mon.Counter("create_user_success").Inc(1) //mon:locked
return u, nil
}
// TestSwapCaptchaHandler replaces the existing handler for captchas with
// the one specified for use in testing.
func (s *Service) TestSwapCaptchaHandler(h CaptchaHandler) {
s.registrationCaptchaHandler = h
s.loginCaptchaHandler = h
}
// GenerateActivationToken - is a method for generating activation token.
func (s *Service) GenerateActivationToken(ctx context.Context, id uuid.UUID, email string) (token string, err error) {
defer mon.Task()(&ctx)(&err)
return s.tokens.CreateToken(ctx, id, email)
}
// GeneratePasswordRecoveryToken - is a method for generating password recovery token.
func (s *Service) GeneratePasswordRecoveryToken(ctx context.Context, id uuid.UUID) (token string, err error) {
defer mon.Task()(&ctx)(&err)
resetPasswordToken, err := s.store.ResetPasswordTokens().GetByOwnerID(ctx, id)
if err == nil {
err := s.store.ResetPasswordTokens().Delete(ctx, resetPasswordToken.Secret)
if err != nil {
return "", Error.Wrap(err)
}
}
resetPasswordToken, err = s.store.ResetPasswordTokens().Create(ctx, id)
if err != nil {
return "", Error.Wrap(err)
}
s.auditLog(ctx, "generate password recovery token", &id, "")
return resetPasswordToken.Secret.String(), nil
}
// GenerateSessionToken creates a new session and returns the string representation of its token.
func (s *Service) GenerateSessionToken(ctx context.Context, userID uuid.UUID, email, ip, userAgent string) (_ *TokenInfo, err error) {
defer mon.Task()(&ctx)(&err)
sessionID, err := uuid.New()
if err != nil {
return nil, Error.Wrap(err)
}
duration := s.config.Session.Duration
if s.config.Session.InactivityTimerEnabled {
settings, err := s.store.Users().GetSettings(ctx, userID)
if err != nil && !errs.Is(err, sql.ErrNoRows) {
return nil, Error.Wrap(err)
}
if settings != nil && settings.SessionDuration != nil {
duration = *settings.SessionDuration
} else {
duration = time.Duration(s.config.Session.InactivityTimerDuration) * time.Second
}
}
expiresAt := time.Now().Add(duration)
_, err = s.store.WebappSessions().Create(ctx, sessionID, userID, ip, userAgent, expiresAt)
if err != nil {
return nil, err
}
token := consoleauth.Token{Payload: sessionID.Bytes()}
signature, err := s.tokens.SignToken(token)
if err != nil {
return nil, err
}
token.Signature = signature
s.auditLog(ctx, "login", &userID, email)
s.analytics.TrackSignedIn(userID, email)
return &TokenInfo{
Token: token,
ExpiresAt: expiresAt,
}, nil
}
// ActivateAccount - is a method for activating user account after registration.
func (s *Service) ActivateAccount(ctx context.Context, activationToken string) (user *User, err error) {
defer mon.Task()(&ctx)(&err)
parsedActivationToken, err := consoleauth.FromBase64URLString(activationToken)
if err != nil {
return nil, ErrTokenInvalid.Wrap(err)
}
valid, err := s.tokens.ValidateToken(parsedActivationToken)
if err != nil {
return nil, Error.Wrap(err)
}
if !valid {
return nil, ErrTokenInvalid.New("incorrect signature")
}
claims, err := consoleauth.FromJSON(parsedActivationToken.Payload)
if err != nil {
return nil, ErrTokenInvalid.New("JSON decoder: %w", err)
}
if time.Now().After(claims.Expiration) {
return nil, ErrTokenExpiration.New(activationTokenExpiredErrMsg)
}
_, err = s.store.Users().GetByEmail(ctx, claims.Email)
if err == nil {
return nil, ErrEmailUsed.New(emailUsedErrMsg)
}
user, err = s.store.Users().Get(ctx, claims.ID)
if err != nil {
return nil, Error.Wrap(err)
}
status := Active
err = s.store.Users().Update(ctx, user.ID, UpdateUserRequest{
Status: &status,
})
if err != nil {
return nil, Error.Wrap(err)
}
s.auditLog(ctx, "activate account", &user.ID, user.Email)
s.analytics.TrackAccountVerified(user.ID, user.Email)
return user, nil
}
// ResetPassword - is a method for resetting user password.
func (s *Service) ResetPassword(ctx context.Context, resetPasswordToken, password string, passcode string, recoveryCode string, t time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
secret, err := ResetPasswordSecretFromBase64(resetPasswordToken)
if err != nil {
return ErrRecoveryToken.Wrap(err)
}
token, err := s.store.ResetPasswordTokens().GetBySecret(ctx, secret)
if err != nil {
return ErrRecoveryToken.Wrap(err)
}
user, err := s.store.Users().Get(ctx, *token.OwnerID)
if err != nil {
return Error.Wrap(err)
}
if user.MFAEnabled {
if recoveryCode != "" {
found := false
for _, code := range user.MFARecoveryCodes {
if code == recoveryCode {
found = true
break
}
}
if !found {
return ErrUnauthorized.Wrap(ErrMFARecoveryCode.New(mfaRecoveryInvalidErrMsg))
}
} else if passcode != "" {
valid, err := ValidateMFAPasscode(passcode, user.MFASecretKey, t)
if err != nil {
return ErrValidation.Wrap(ErrMFAPasscode.Wrap(err))
}
if !valid {
return ErrValidation.Wrap(ErrMFAPasscode.New(mfaPasscodeInvalidErrMsg))
}
} else {
return ErrMFAMissing.New(mfaRequiredErrMsg)
}
}
if err := ValidateNewPassword(password); err != nil {