-
Notifications
You must be signed in to change notification settings - Fork 402
/
service.go
1391 lines (1132 loc) · 34.9 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"
"crypto/subtle"
"database/sql"
"fmt"
"time"
"github.com/skyrings/skyring-common/tools/uuid"
"github.com/zeebo/errs"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
"gopkg.in/spacemonkeygo/monkit.v2"
"storj.io/storj/pkg/auth"
"storj.io/storj/pkg/macaroon"
"storj.io/storj/satellite/console/consoleauth"
"storj.io/storj/satellite/payments"
"storj.io/storj/satellite/rewards"
)
var mon = monkit.Package()
const (
// maxLimit specifies the limit for all paged queries
maxLimit = 50
tokenExpirationTime = 24 * time.Hour
// DefaultPasswordCost is the hashing complexity
DefaultPasswordCost = bcrypt.DefaultCost
// TestPasswordCost is the hashing complexity to use for testing
TestPasswordCost = bcrypt.MinCost
)
// Error messages
const (
unauthorizedErrMsg = "You are not authorized to perform this action"
vanguardRegTokenErrMsg = "We are unable to create your account. This is an invite-only alpha, please join our waitlist to receive an invitation"
emailUsedErrMsg = "This email is already in use, try another"
activationTokenIsExpiredErrMsg = "Your account activation link has expired, please sign up again"
passwordRecoveryTokenIsExpiredErrMsg = "Your password recovery link has expired, please request another one"
credentialsErrMsg = "Your email or password was incorrect, please try again"
oldPassIncorrectErrMsg = "Old password is incorrect, please try again"
passwordIncorrectErrMsg = "Your password needs at least %d characters long"
projectOwnerDeletionForbiddenErrMsg = "%s is a project owner and can not be deleted"
teamMemberDoesNotExistErrMsg = `There is no account on this Satellite for the user(s) you have entered.
Please add team members with active accounts`
// TODO: remove after vanguard release
usedRegTokenVanguardErrMsg = "This registration token has already been used"
projLimitVanguardErrMsg = "Sorry, during the Vanguard release you have a limited number of projects"
)
// ErrConsoleInternal describes internal console error
var ErrConsoleInternal = errs.Class("internal error")
// Service is handling accounts related logic
//
// architecture: Service
type Service struct {
Signer
log *zap.Logger
pm payments.Service
store DB
rewards rewards.DB
passwordCost int
}
// NewService returns new instance of Service
func NewService(log *zap.Logger, signer Signer, store DB, rewards rewards.DB, pm payments.Service, passwordCost int) (*Service, error) {
if signer == nil {
return nil, errs.New("signer can't be nil")
}
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 passwordCost == 0 {
passwordCost = bcrypt.DefaultCost
}
return &Service{
log: log,
Signer: signer,
store: store,
rewards: rewards,
pm: pm,
passwordCost: passwordCost,
}, nil
}
// CreateUser gets password hash value and creates new inactive User
func (s *Service) CreateUser(ctx context.Context, user CreateUser, tokenSecret RegistrationSecret, refUserID string) (u *User, err error) {
defer mon.Task()(&ctx)(&err)
if err := user.IsValid(); err != nil {
return nil, err
}
offerType := rewards.FreeCredit
if user.PartnerID != "" {
offerType = rewards.Partner
} else if refUserID != "" {
offerType = rewards.Referral
}
//TODO: Create a current offer cache to replace database call
offers, err := s.rewards.GetActiveOffersByType(ctx, offerType)
if err != nil && !rewards.NoCurrentOfferErr.Has(err) {
s.log.Error("internal error", zap.Error(err))
return nil, ErrConsoleInternal.Wrap(err)
}
currentReward, err := offers.GetActiveOffer(offerType, user.PartnerID)
if err != nil && !rewards.NoCurrentOfferErr.Has(err) {
s.log.Error("internal error", zap.Error(err))
return nil, ErrConsoleInternal.Wrap(err)
}
// TODO: remove after vanguard release
// when user uses an open source partner referral link, there won't be a registration token in the link.
// therefore, we need to create one so we can still control the project limit on the account level
var registrationToken *RegistrationToken
if user.PartnerID != "" {
// set the project limit to be 1 for open source partner invitees
registrationToken, err = s.store.RegistrationTokens().Create(ctx, 1)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
} else {
registrationToken, err = s.store.RegistrationTokens().GetBySecret(ctx, tokenSecret)
if err != nil {
return nil, errs.New(vanguardRegTokenErrMsg)
}
// 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, errs.New(usedRegTokenVanguardErrMsg)
}
}
u, err = s.store.Users().GetByEmail(ctx, user.Email)
if err == nil {
return nil, errs.New(emailUsedErrMsg)
}
hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), s.passwordCost)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
// store data
tx, err := s.store.BeginTx(ctx)
if err != nil {
return nil, err
}
err = withTx(tx, func(tx DBTx) error {
newUser := &User{
Email: user.Email,
FullName: user.FullName,
ShortName: user.ShortName,
PasswordHash: hash,
}
if user.PartnerID != "" {
partnerID, err := uuid.Parse(user.PartnerID)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
newUser.PartnerID = *partnerID
}
u, err = tx.Users().Insert(ctx,
newUser,
)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
err = tx.RegistrationTokens().UpdateOwner(ctx, registrationToken.Secret, u.ID)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
if currentReward != nil {
var refID *uuid.UUID
if refUserID != "" {
refID, err = uuid.Parse(refUserID)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
}
newCredit, err := NewCredit(currentReward, Invitee, u.ID, refID)
if err != nil {
return err
}
err = tx.UserCredits().Create(ctx, *newCredit)
if err != nil {
return err
}
}
cus, err := s.pm.CreateCustomer(ctx, payments.CreateCustomerParams{
Email: user.Email,
Name: user.FullName,
})
if err != nil {
return err
}
_, err = tx.UserPayments().Create(ctx, UserPayment{
UserID: u.ID,
CustomerID: cus.ID,
})
return err
})
if err != nil {
return nil, err
}
return u, nil
}
// AddNewPaymentMethod adds new payment method for project
func (s *Service) AddNewPaymentMethod(ctx context.Context, paymentMethodToken string, isDefault bool, projectID uuid.UUID) (payment *ProjectPayment, err error) {
defer mon.Task()(&ctx)(&err)
authorization, err := GetAuth(ctx)
if err != nil {
return nil, err
}
userPayments, err := s.store.UserPayments().Get(ctx, authorization.User.ID)
if err != nil {
return nil, err
}
params := payments.AddPaymentMethodParams{
Token: paymentMethodToken,
CustomerID: string(userPayments.CustomerID),
}
method, err := s.pm.AddPaymentMethod(ctx, params)
if err != nil {
return nil, err
}
tx, err := s.store.BeginTx(ctx)
if err != nil {
return nil, err
}
var pp *ProjectPayment
err = withTx(tx, func(tx DBTx) error {
if isDefault {
projectPayment, err := tx.ProjectPayments().GetDefaultByProjectID(ctx, projectID)
if err != nil {
if err != sql.ErrNoRows {
return err
}
}
if projectPayment != nil {
projectPayment.IsDefault = false
err = tx.ProjectPayments().Update(ctx, *projectPayment)
if err != nil {
return err
}
}
}
projectPaymentInfo := ProjectPayment{
ProjectID: projectID,
PayerID: authorization.User.ID,
PaymentMethodID: method.ID,
CreatedAt: time.Now(),
IsDefault: isDefault,
}
pp, err = tx.ProjectPayments().Create(ctx, projectPaymentInfo)
return err
})
return pp, nil
}
// SetDefaultPaymentMethod set default payment method for given project
func (s *Service) SetDefaultPaymentMethod(ctx context.Context, projectPaymentID uuid.UUID, projectID uuid.UUID) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = GetAuth(ctx)
if err != nil {
return err
}
tx, err := s.store.BeginTx(ctx)
if err != nil {
return err
}
err = withTx(tx, func(tx DBTx) error {
projectPayment, err := tx.ProjectPayments().GetDefaultByProjectID(ctx, projectID)
if err != nil {
return err
}
projectPayment.IsDefault = false
err = tx.ProjectPayments().Update(ctx, *projectPayment)
if err != nil {
return err
}
projectPayment, err = tx.ProjectPayments().GetByID(ctx, projectPaymentID)
if err != nil {
return err
}
projectPayment.IsDefault = true
return tx.ProjectPayments().Update(ctx, *projectPayment)
})
return err
}
// DeleteProjectPaymentMethod deletes selected payment method
func (s *Service) DeleteProjectPaymentMethod(ctx context.Context, projectPayment uuid.UUID) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = GetAuth(ctx)
if err != nil {
return err
}
return s.store.ProjectPayments().Delete(ctx, projectPayment)
}
// GetProjectPaymentMethods retrieves project payment methods
func (s *Service) GetProjectPaymentMethods(ctx context.Context, projectID uuid.UUID) ([]ProjectPayment, error) {
var err error
defer mon.Task()(&ctx)(&err)
_, err = GetAuth(ctx)
if err != nil {
return nil, err
}
projectPaymentInfos, err := s.store.ProjectPayments().GetByProjectID(ctx, projectID)
if err != nil {
return nil, err
}
var projectPayments []ProjectPayment
for _, payment := range projectPaymentInfos {
pm, err := s.pm.GetPaymentMethod(ctx, payment.PaymentMethodID)
if err != nil {
return nil, err
}
projectPayment := ProjectPayment{
ID: payment.ID,
CreatedAt: pm.CreatedAt,
PaymentMethodID: pm.ID,
IsDefault: payment.IsDefault,
PayerID: payment.PayerID,
ProjectID: projectID,
Card: Card{
LastFour: pm.Card.LastFour,
Name: pm.Card.Name,
Brand: pm.Card.Brand,
Country: pm.Card.Country,
ExpirationMonth: pm.Card.ExpMonth,
ExpirationYear: pm.Card.ExpYear,
},
}
projectPayments = append(projectPayments, projectPayment)
}
return projectPayments, nil
}
// 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)
//TODO: activation token should differ from auth token
claims := &consoleauth.Claims{
ID: id,
Email: email,
Expiration: time.Now().Add(time.Hour * 24),
}
return s.createToken(ctx, claims)
}
// 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 "", err
}
}
resetPasswordToken, err = s.store.ResetPasswordTokens().Create(ctx, id)
if err != nil {
return "", err
}
return resetPasswordToken.Secret.String(), nil
}
// ActivateAccount - is a method for activating user account after registration
func (s *Service) ActivateAccount(ctx context.Context, activationToken string) (err error) {
defer mon.Task()(&ctx)(&err)
token, err := consoleauth.FromBase64URLString(activationToken)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
claims, err := s.authenticate(ctx, token)
if err != nil {
return
}
_, err = s.store.Users().GetByEmail(ctx, claims.Email)
if err == nil {
return errs.New(emailUsedErrMsg)
}
user, err := s.store.Users().Get(ctx, claims.ID)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
now := time.Now()
if user.Status != Inactive {
return errs.New("account is already active")
}
if now.After(user.CreatedAt.Add(tokenExpirationTime)) {
return errs.New(activationTokenIsExpiredErrMsg)
}
user.Status = Active
err = s.store.Users().Update(ctx, user)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
err = s.store.UserCredits().UpdateEarnedCredits(ctx, user.ID)
if err != nil && !NoCreditForUpdateErr.Has(err) {
return ErrConsoleInternal.Wrap(err)
}
return nil
}
// ResetPassword - is a method for reseting user password
func (s *Service) ResetPassword(ctx context.Context, resetPasswordToken, password string) (err error) {
defer mon.Task()(&ctx)(&err)
secret, err := ResetPasswordSecretFromBase64(resetPasswordToken)
if err != nil {
return
}
token, err := s.store.ResetPasswordTokens().GetBySecret(ctx, secret)
if err != nil {
return
}
user, err := s.store.Users().Get(ctx, *token.OwnerID)
if err != nil {
return
}
if err := validatePassword(password); err != nil {
return err
}
if time.Since(token.CreatedAt) > tokenExpirationTime {
return errs.New(passwordRecoveryTokenIsExpiredErrMsg)
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), s.passwordCost)
if err != nil {
return err
}
user.PasswordHash = hash
err = s.store.Users().Update(ctx, user)
if err != nil {
return err
}
return s.store.ResetPasswordTokens().Delete(ctx, token.Secret)
}
// RevokeResetPasswordToken - is a method to revoke reset password token
func (s *Service) RevokeResetPasswordToken(ctx context.Context, resetPasswordToken string) (err error) {
defer mon.Task()(&ctx)(&err)
secret, err := ResetPasswordSecretFromBase64(resetPasswordToken)
if err != nil {
return
}
return s.store.ResetPasswordTokens().Delete(ctx, secret)
}
// Token authenticates User by credentials and returns auth token
func (s *Service) Token(ctx context.Context, email, password string) (token string, err error) {
defer mon.Task()(&ctx)(&err)
user, err := s.store.Users().GetByEmail(ctx, email)
if err != nil {
return "", errs.New(credentialsErrMsg)
}
err = bcrypt.CompareHashAndPassword(user.PasswordHash, []byte(password))
if err != nil {
return "", ErrUnauthorized.New(credentialsErrMsg)
}
claims := consoleauth.Claims{
ID: user.ID,
Expiration: time.Now().Add(tokenExpirationTime),
}
token, err = s.createToken(ctx, &claims)
if err != nil {
return "", err
}
return token, nil
}
// GetUser returns User by id
func (s *Service) GetUser(ctx context.Context, id uuid.UUID) (u *User, err error) {
defer mon.Task()(&ctx)(&err)
user, err := s.store.Users().Get(ctx, id)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
return user, nil
}
// GetUserByEmail returns User by email
func (s *Service) GetUserByEmail(ctx context.Context, email string) (u *User, err error) {
defer mon.Task()(&ctx)(&err)
return s.store.Users().GetByEmail(ctx, email)
}
// UpdateAccount updates User
func (s *Service) UpdateAccount(ctx context.Context, info UserInfo) (err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return err
}
if err = info.IsValid(); err != nil {
return err
}
err = s.store.Users().Update(ctx, &User{
ID: auth.User.ID,
FullName: info.FullName,
ShortName: info.ShortName,
Email: auth.User.Email,
PasswordHash: nil,
Status: auth.User.Status,
})
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
return nil
}
// ChangePassword updates password for a given user
func (s *Service) ChangePassword(ctx context.Context, pass, newPass string) (err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return err
}
err = bcrypt.CompareHashAndPassword(auth.User.PasswordHash, []byte(pass))
if err != nil {
return errs.New(oldPassIncorrectErrMsg)
}
if err := validatePassword(newPass); err != nil {
return err
}
hash, err := bcrypt.GenerateFromPassword([]byte(newPass), s.passwordCost)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
auth.User.PasswordHash = hash
err = s.store.Users().Update(ctx, &auth.User)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
return nil
}
// DeleteAccount deletes User
func (s *Service) DeleteAccount(ctx context.Context, password string) (err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return err
}
err = bcrypt.CompareHashAndPassword(auth.User.PasswordHash, []byte(password))
if err != nil {
return ErrUnauthorized.New(oldPassIncorrectErrMsg)
}
err = s.store.Users().Delete(ctx, auth.User.ID)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
return nil
}
// GetProject is a method for querying project by id
func (s *Service) GetProject(ctx context.Context, projectID uuid.UUID) (p *Project, err error) {
defer mon.Task()(&ctx)(&err)
_, err = GetAuth(ctx)
if err != nil {
return nil, err
}
p, err = s.store.Projects().Get(ctx, projectID)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
return
}
// GetUsersProjects is a method for querying all projects
func (s *Service) GetUsersProjects(ctx context.Context) (ps []Project, err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return nil, err
}
ps, err = s.store.Projects().GetByUserID(ctx, auth.User.ID)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
return
}
// GetCurrentRewardByType is a method for querying current active reward offer based on its type
func (s *Service) GetCurrentRewardByType(ctx context.Context, offerType rewards.OfferType) (offer *rewards.Offer, err error) {
defer mon.Task()(&ctx)(&err)
offers, err := s.rewards.GetActiveOffersByType(ctx, offerType)
if err != nil {
s.log.Error("internal error", zap.Error(err))
return nil, ErrConsoleInternal.Wrap(err)
}
return offers.GetActiveOffer(offerType, "")
}
// GetUserCreditUsage is a method for querying users' credit information up until now
func (s *Service) GetUserCreditUsage(ctx context.Context) (usage *UserCreditUsage, err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return nil, errs.Wrap(err)
}
usage, err = s.store.UserCredits().GetCreditUsage(ctx, auth.User.ID, time.Now().UTC())
if err != nil {
return nil, errs.Wrap(err)
}
return usage, nil
}
// CreateProject is a method for creating new project
func (s *Service) CreateProject(ctx context.Context, projectInfo ProjectInfo) (p *Project, err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return nil, err
}
// TODO: remove after vanguard release
err = s.checkProjectLimit(ctx, auth.User.ID)
if err != nil {
return
}
tx, err := s.store.BeginTx(ctx)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
err = withTx(tx, func(tx DBTx) (err error) {
p, err = tx.Projects().Insert(ctx,
&Project{
Description: projectInfo.Description,
Name: projectInfo.Name,
OwnerID: auth.User.ID,
PartnerID: auth.User.PartnerID,
},
)
if err != nil {
s.log.Error("internal error", zap.Error(err))
return ErrConsoleInternal.Wrap(err)
}
_, err = tx.ProjectMembers().Insert(ctx, auth.User.ID, p.ID)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
return err
})
if err != nil {
return nil, err
}
return p, nil
}
// DeleteProject is a method for deleting project by id
func (s *Service) DeleteProject(ctx context.Context, projectID uuid.UUID) (err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return err
}
if _, err = s.isProjectMember(ctx, auth.User.ID, projectID); err != nil {
return ErrUnauthorized.Wrap(err)
}
err = s.store.Projects().Delete(ctx, projectID)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
return nil
}
// UpdateProject is a method for updating project description by id
func (s *Service) UpdateProject(ctx context.Context, projectID uuid.UUID, description string) (p *Project, err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return nil, err
}
isMember, err := s.isProjectMember(ctx, auth.User.ID, projectID)
if err != nil {
return nil, ErrUnauthorized.Wrap(err)
}
project := isMember.project
project.Description = description
err = s.store.Projects().Update(ctx, project)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
return project, nil
}
// AddProjectMembers adds users by email to given project
func (s *Service) AddProjectMembers(ctx context.Context, projectID uuid.UUID, emails []string) (users []*User, err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return nil, err
}
if _, err = s.isProjectMember(ctx, auth.User.ID, projectID); err != nil {
return nil, ErrUnauthorized.Wrap(err)
}
var userErr errs.Group
// collect user querying errors
for _, email := range emails {
user, err := s.store.Users().GetByEmail(ctx, email)
if err != nil {
userErr.Add(err)
continue
}
users = append(users, user)
}
if err = userErr.Err(); err != nil {
return nil, errs.New(teamMemberDoesNotExistErrMsg)
}
// add project members in transaction scope
tx, err := s.store.BeginTx(ctx)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
defer func() {
if err != nil {
err = errs.Combine(err, tx.Rollback())
return
}
err = tx.Commit()
}()
for _, user := range users {
_, err = tx.ProjectMembers().Insert(ctx, user.ID, projectID)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
}
return users, nil
}
// DeleteProjectMembers removes users by email from given project
func (s *Service) DeleteProjectMembers(ctx context.Context, projectID uuid.UUID, emails []string) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = GetAuth(ctx)
if err != nil {
return err
}
var userIDs []uuid.UUID
var userErr errs.Group
// collect user querying errors
for _, email := range emails {
user, err := s.store.Users().GetByEmail(ctx, email)
if err != nil {
userErr.Add(err)
continue
}
err = s.isProjectOwner(ctx, user.ID, projectID)
if err == nil {
return errs.New(projectOwnerDeletionForbiddenErrMsg, user.Email)
}
if ErrConsoleInternal.Has(err) {
return err
}
userIDs = append(userIDs, user.ID)
}
if err = userErr.Err(); err != nil {
return errs.New(teamMemberDoesNotExistErrMsg)
}
// delete project members in transaction scope
tx, err := s.store.BeginTx(ctx)
if err != nil {
return err
}
defer func() {
if err != nil {
err = errs.Combine(err, tx.Rollback())
return
}
err = tx.Commit()
}()
for _, uID := range userIDs {
err = tx.ProjectMembers().Delete(ctx, uID, projectID)
if err != nil {
return ErrConsoleInternal.Wrap(err)
}
}
return nil
}
// GetProjectMembers returns ProjectMembers for given Project
func (s *Service) GetProjectMembers(ctx context.Context, projectID uuid.UUID, cursor ProjectMembersCursor) (pmp *ProjectMembersPage, err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return nil, err
}
_, err = s.isProjectMember(ctx, auth.User.ID, projectID)
if err != nil {
return nil, ErrUnauthorized.Wrap(err)
}
if cursor.Limit > maxLimit {
cursor.Limit = maxLimit
}
pmp, err = s.store.ProjectMembers().GetPagedByProjectID(ctx, projectID, cursor)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
return
}
// CreateAPIKey creates new api key
func (s *Service) CreateAPIKey(ctx context.Context, projectID uuid.UUID, name string) (_ *APIKeyInfo, _ *macaroon.APIKey, err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return nil, nil, err
}
_, err = s.isProjectMember(ctx, auth.User.ID, projectID)
if err != nil {
return nil, nil, ErrUnauthorized.Wrap(err)
}
secret, err := macaroon.NewSecret()
if err != nil {
return nil, nil, ErrConsoleInternal.Wrap(err)
}
key, err := macaroon.NewAPIKey(secret)
if err != nil {
return nil, nil, err
}
apikey := APIKeyInfo{
Name: name,
ProjectID: projectID,
Secret: secret,
PartnerID: auth.User.PartnerID,
}
info, err := s.store.APIKeys().Create(ctx, key.Head(), apikey)
if err != nil {
return nil, nil, ErrConsoleInternal.Wrap(err)
}
return info, key, nil
}
// GetAPIKeyInfo retrieves api key by id
func (s *Service) GetAPIKeyInfo(ctx context.Context, id uuid.UUID) (_ *APIKeyInfo, err error) {
defer mon.Task()(&ctx)(&err)
auth, err := GetAuth(ctx)
if err != nil {
return nil, err
}
key, err := s.store.APIKeys().Get(ctx, id)
if err != nil {
return nil, ErrConsoleInternal.Wrap(err)
}
_, err = s.isProjectMember(ctx, auth.User.ID, key.ProjectID)
if err != nil {
return nil, ErrUnauthorized.Wrap(err)
}