/
store.go
1111 lines (986 loc) · 30.8 KB
/
store.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
package accounts
import (
"fmt"
"path"
"strings"
"time"
"github.com/appcelerator/amp/api/auth"
"github.com/appcelerator/amp/cmd/amplifier/server/configuration"
"github.com/appcelerator/amp/data/storage"
"github.com/appcelerator/amp/docker/docker/pkg/stringid"
"github.com/golang/protobuf/proto"
"github.com/ory/ladon"
"github.com/ory/ladon/manager/memory"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
"golang.org/x/net/context"
)
const superAccountRootKey = "sa"
const usersRootKey = "users"
const organizationsRootKey = "organizations"
const SuperUser = "su"
const SuperOrganization = "so"
const DefaultOrganization = "default"
const DefaultOrganizationEmail = "default@organization.amp"
const BCryptCost = 12
// Store implements user data.Interface
type Store struct {
registration string
storage storage.Interface
warden *ladon.Ladon
}
// NewStore returns a new accounts storage
func NewStore(s storage.Interface, registration string, SUPassword string) (*Store, error) {
store := &Store{
storage: s,
registration: registration,
warden: &ladon.Ladon{
Manager: memory.NewMemoryManager(),
},
}
// Register policies
for _, policy := range policies {
if err := store.warden.Manager.Create(policy); err != nil {
log.Fatal("Unable to create policy:", err)
}
}
if err := store.createDefaultAccounts(SUPassword); err != nil {
return nil, err
}
return store, nil
}
func (s *Store) createDefaultAccounts(SUPassword string) error {
if SUPassword == "" {
log.Warnf("SUPassword is empty. Skipping creation of super accounts.")
return nil
}
// Check if default accounts haven been created already
ctx := context.Background()
err := s.storage.Create(ctx, path.Join(superAccountRootKey, "created"), &User{}, nil, 0)
switch err {
case nil: // No error, do nothing
case storage.AlreadyExists: // Super accounts have already been created, just return
return nil
default:
return err
}
// Create the initial super user
user, err := s.GetUser(ctx, SuperUser)
if err != nil {
return err
}
if user != nil {
return fmt.Errorf("Initial super user should not exist already. Check the storage.")
}
su := &User{
Name: SuperUser,
Email: "super@user.amp",
IsVerified: true,
CreateDt: time.Now().Unix(),
}
if su.PasswordHash, err = bcrypt.GenerateFromPassword([]byte(SUPassword), BCryptCost); err != nil {
return err
}
if err := s.storage.Create(ctx, path.Join(usersRootKey, su.Name), su, nil, 0); err != nil {
return err
}
log.Infoln("Successfully created initial super user")
// Create the super organization
org, err := s.GetOrganization(ctx, SuperOrganization)
if err != nil {
return err
}
if org != nil {
return fmt.Errorf("Super organization should not exist already. Check the storage.")
}
so := &Organization{
Name: SuperOrganization,
Email: "super@organization.amp",
CreateDt: time.Now().Unix(),
Members: []*OrganizationMember{
{
Name: SuperUser,
Role: OrganizationRole_ORGANIZATION_OWNER,
},
},
}
if err := s.storage.Create(ctx, path.Join(organizationsRootKey, so.Name), so, nil, 0); err != nil {
return err
}
log.Infoln("Successfully created super organization")
// Add a policy giving full access to super organization members
s.warden.Manager.Create(&ladon.DefaultPolicy{
ID: stringid.GenerateNonCryptoID(),
Subjects: []string{"<.*>"},
Resources: []string{"<.*>"},
Actions: []string{"<.*>"},
Effect: ladon.AllowAccess,
Conditions: ladon.Conditions{
"owner": &OwnerCondition{},
},
})
// Create the default organization
org, err = s.GetOrganization(ctx, DefaultOrganization)
if err != nil {
return err
}
if org != nil {
return fmt.Errorf("Default organization should not exist already. Check the storage.")
}
do := &Organization{
Name: DefaultOrganization,
Email: DefaultOrganizationEmail,
CreateDt: time.Now().Unix(),
Members: []*OrganizationMember{},
}
if err := s.storage.Create(ctx, path.Join(organizationsRootKey, do.Name), do, nil, 0); err != nil {
return err
}
log.Infoln("Successfully created default organization")
return nil
}
// Users
func (s *Store) rawUser(ctx context.Context, name string) (*User, error) {
user := &User{}
if err := s.storage.Get(ctx, path.Join(usersRootKey, name), user, true); err != nil {
return nil, err
}
if user.GetName() == "" { // If there's no "name" in the answer, it means the user has not been found, so return nil
return nil, nil
}
return user, nil
}
func (s *Store) secureUser(ctx context.Context, user *User) *User {
if user == nil {
return nil
}
user.PasswordHash = nil // For security reasons, remove the password hash
if !s.IsAuthorized(ctx, &Account{user.Name, ""}, ReadAction, UserRN, user.Name) {
user.Email = ""
}
return user
}
func (s *Store) getUser(ctx context.Context, name string) (user *User, err error) {
if user, err = s.rawUser(ctx, name); err != nil {
return nil, err
}
if user == nil {
return nil, UserNotFound
}
return user, nil
}
func (s *Store) getVerifiedUser(ctx context.Context, name string) (user *User, err error) {
if user, err = s.getUser(ctx, name); err != nil {
return nil, err
}
if !user.IsVerified {
return nil, UserNotVerified
}
return user, nil
}
// CreateUser creates a new user
func (s *Store) CreateUser(ctx context.Context, name string, email string, password string) (user *User, err error) {
// Check if user already exists
userAlreadyExists, err := s.rawUser(ctx, name)
if err != nil {
return nil, err
}
if userAlreadyExists != nil {
return nil, UserAlreadyExists
}
// Check if email is already in use
emailAlreadyUsed, err := s.GetUserByEmail(ctx, email)
if err != nil {
return nil, err
}
if emailAlreadyUsed != nil {
return nil, EmailAlreadyUsed
}
// Check if an organization with the same name already exists.
orgAlreadyExists, err := s.GetOrganization(ctx, name)
if err != nil {
return nil, err
}
if orgAlreadyExists != nil {
return nil, OrganizationAlreadyExists
}
// Create the new user
user = &User{
Email: email,
Name: name,
IsVerified: false,
CreateDt: time.Now().Unix(),
}
if s.registration == configuration.RegistrationNone {
user.IsVerified = true
}
if password, err = CheckPassword(password); err != nil {
return nil, err
}
if user.PasswordHash, err = bcrypt.GenerateFromPassword([]byte(password), BCryptCost); err != nil {
return nil, err
}
if err := user.Validate(); err != nil {
return nil, err
}
if err := s.storage.Create(ctx, path.Join(usersRootKey, name), user, nil, 0); err != nil {
s.storage.Delete(ctx, path.Join(usersRootKey, name), false, nil)
return nil, err
}
return user, nil
}
// VerifyUser verifies a user account
func (s *Store) VerifyUser(ctx context.Context, userName string) error {
// Update user
uf := func(current proto.Message) (proto.Message, error) {
user, ok := current.(*User)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected User): %T", user)
}
if user.TokenUsed {
return nil, TokenAlreadyUsed
}
user.IsVerified = true
user.TokenUsed = true
return user, nil
}
if err := s.storage.Update(ctx, path.Join(usersRootKey, userName), uf, &User{}); err != nil {
if err == storage.NotFound {
return UserNotFound
}
return err
}
return nil
}
// CheckUserPassword checks the given user password
func (s *Store) CheckUserPassword(ctx context.Context, name string, password string) error {
user, err := s.getVerifiedUser(ctx, name)
if err != nil {
return err
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
return WrongPassword
}
return nil
}
// SetUserPassword sets the given user password
func (s *Store) SetUserPassword(ctx context.Context, name string, password string) error {
// Password
if _, err := CheckPassword(password); err != nil {
return err
}
passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), BCryptCost)
if err != nil {
return err
}
// Update user
uf := func(current proto.Message) (proto.Message, error) {
user, ok := current.(*User)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected User): %T", user)
}
user.PasswordHash = passwordHash
return user, nil
}
if err := s.storage.Update(ctx, path.Join(usersRootKey, name), uf, &User{}); err != nil {
if err == storage.NotFound {
return UserNotFound
}
return err
}
return nil
}
// GetUser fetches a user by name
func (s *Store) GetUser(ctx context.Context, name string) (user *User, err error) {
if name, err = CheckName(name); err != nil {
return nil, err
}
user, err = s.rawUser(ctx, name)
if err != nil {
return nil, err
}
return s.secureUser(ctx, user), nil
}
// GetUserByEmail fetches a user by email
func (s *Store) GetUserByEmail(ctx context.Context, email string) (*User, error) {
if _, err := CheckEmailAddress(email); err != nil {
return nil, err
}
protos := []proto.Message{}
if err := s.storage.List(ctx, usersRootKey, storage.Everything, &User{}, &protos); err != nil {
return nil, err
}
for _, proto := range protos {
user := proto.(*User)
if strings.EqualFold(user.Email, email) {
return s.secureUser(ctx, user), nil
}
}
return nil, nil
}
// GetUserEmail fetches a users email
func (s *Store) GetUserEmail(ctx context.Context, user *User) (string, error) {
user, err := s.getUser(ctx, user.Name)
if err != nil {
return "", err
}
if user.Email == "" {
return "", fmt.Errorf("user's email not found.")
}
return user.Email, nil
}
// GetUserOrganizations gets the organizations the given user is member of
func (s *Store) GetUserOrganizations(ctx context.Context, name string) ([]*Organization, error) {
organizations, err := s.ListOrganizations(ctx)
if err != nil {
return nil, err
}
userOrganizations := []*Organization{}
for _, o := range organizations {
if o.HasMember(name) {
userOrganizations = append(userOrganizations, o)
}
}
return userOrganizations, nil
}
// ListUsers lists users
func (s *Store) ListUsers(ctx context.Context) ([]*User, error) {
protos := []proto.Message{}
if err := s.storage.List(ctx, usersRootKey, storage.Everything, &User{}, &protos); err != nil {
return nil, err
}
users := []*User{}
for _, proto := range protos {
users = append(users, s.secureUser(ctx, proto.(*User)))
}
return users, nil
}
// DeleteNotVerifiedUser deletes the user by name only if it's not verified
func (s *Store) DeleteNotVerifiedUser(ctx context.Context, name string) error {
//Get user to verify it is well not verified
user, err := s.GetUser(ctx, name)
if err != nil {
return err
}
if user != nil && !user.IsVerified {
if err := s.storage.Delete(ctx, path.Join(usersRootKey, name), false, nil); err != nil {
return err
}
}
return nil
}
// DeleteUser deletes a user by name
func (s *Store) DeleteUser(ctx context.Context, name string) (*User, error) {
// Check authorization
if !s.IsAuthorized(ctx, &Account{name, ""}, DeleteAction, UserRN, name) {
return nil, NotAuthorized
}
// Get organizations this user is member of
organizations, err := s.GetUserOrganizations(ctx, name)
if err != nil {
return nil, err
}
// Check if user can be removed from all organizations
for _, o := range organizations {
if err := s.canRemoveUserFromOrganization(ctx, o.Name, name); err != nil {
return nil, err
}
}
// If yes, remove the user from all organizations
for _, o := range organizations {
if err := s.RemoveUserFromOrganization(ctx, o.Name, name); err != nil {
return nil, err
}
}
// Delete the user
user := &User{}
if err := s.storage.Delete(ctx, path.Join(usersRootKey, name), false, user); err != nil {
return nil, err
}
return user, nil
}
// Organizations
func (s *Store) getOrganization(ctx context.Context, name string) (organization *Organization, err error) {
if organization, err = s.GetOrganization(ctx, name); err != nil {
return nil, err
}
if organization == nil {
return nil, OrganizationNotFound
}
return organization, nil
}
func (s *Store) updateOrganization(ctx context.Context, in *Organization) error {
if err := in.Validate(); err != nil {
return err
}
if err := s.storage.Put(ctx, path.Join(organizationsRootKey, in.Name), in, 0); err != nil {
return err
}
return nil
}
// CreateOrganization creates a new organization
func (s *Store) CreateOrganization(ctx context.Context, name string, email string) error {
// Check if user with the same name already exists
userAlreadyExists, err := s.rawUser(ctx, name)
if err != nil {
return err
}
if userAlreadyExists != nil {
return UserAlreadyExists
}
// Check if organization already exists
orgAlreadyExists, err := s.GetOrganization(ctx, name)
if err != nil {
return err
}
if orgAlreadyExists != nil {
return OrganizationAlreadyExists
}
// Create the new organization
organization := &Organization{
Email: email,
Name: name,
CreateDt: time.Now().Unix(),
Members: []*OrganizationMember{
{
Name: auth.GetUser(ctx),
Role: OrganizationRole_ORGANIZATION_MEMBER,
},
},
}
if err := organization.Validate(); err != nil {
return err
}
if err := s.storage.Create(ctx, path.Join(organizationsRootKey, organization.Name), organization, nil, 0); err != nil {
return err
}
return nil
}
// AddUserToOrganization adds a user to the given organization
func (s *Store) AddUserToOrganization(ctx context.Context, organizationName string, userName string) (err error) {
// Check authorization
if !s.IsAuthorized(ctx, &Account{"", organizationName}, UpdateAction, OrganizationRN, organizationName) {
return NotAuthorized
}
// Get the user
//user, err := s.getVerifiedUser(ctx, userName)
user, err := s.getUser(ctx, userName)
if err != nil {
return err
}
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Check if user is already a member
if organization.HasMember(user.Name) {
return nil, UserAlreadyExists
}
// Special case of default organization
role := OrganizationRole_ORGANIZATION_MEMBER
if organization.Name == DefaultOrganization && len(organization.Members) == 0 {
role = OrganizationRole_ORGANIZATION_OWNER
}
// Add the user as a team member
organization.Members = append(organization.Members, &OrganizationMember{
Name: user.Name,
Role: role,
})
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
func (s *Store) canRemoveUserFromOrganization(ctx context.Context, organizationName string, userName string) error {
// Get organization
organization, err := s.getOrganization(ctx, organizationName)
if err != nil {
return err
}
// Get the user
user, err := s.getUser(ctx, userName)
if err != nil {
return err
}
// Check if user is part of the organization
memberIndex := organization.getMemberIndex(user.Name)
if memberIndex == -1 {
return nil // User is not a member of the organization, return
}
// Remove the user from members. For details, check http://stackoverflow.com/questions/25025409/delete-element-in-a-slice
organization.Members = append(organization.Members[:memberIndex], organization.Members[memberIndex+1:]...)
if err := organization.Validate(); err != nil {
return err
}
return nil
}
// RemoveUserFromOrganization removes a user from the given organization
func (s *Store) RemoveUserFromOrganization(ctx context.Context, organizationName string, userName string) (err error) {
// Check authorization
if !(s.IsAuthorized(ctx, &Account{"", organizationName}, UpdateAction, OrganizationRN, organizationName) ||
s.IsAuthorized(ctx, &Account{userName, ""}, LeaveAction, OrganizationRN, organizationName)) {
return NotAuthorized
}
// Get the user
user, err := s.getUser(ctx, userName)
if err != nil {
return err
}
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Check if user is part of the organization
memberIndex := organization.getMemberIndex(user.Name)
if memberIndex == -1 {
return nil, UserNotFound
}
// Remove the user from members. For details, check http://stackoverflow.com/questions/25025409/delete-element-in-a-slice
organization.Members = append(organization.Members[:memberIndex], organization.Members[memberIndex+1:]...)
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
// ChangeOrganizationMemberRole changes the role of given user in the given organization
func (s *Store) ChangeOrganizationMemberRole(ctx context.Context, organizationName string, userName string, role OrganizationRole) (err error) {
// Check authorization
if !s.IsAuthorized(ctx, &Account{"", organizationName}, UpdateAction, OrganizationRN, organizationName) {
return NotAuthorized
}
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Check if user is already a member
member := organization.getMember(userName)
if member == nil {
return nil, UserNotFound
}
// Change the role of the user
member.Role = role
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
// GetOrganization fetches a organization by name
func (s *Store) GetOrganization(ctx context.Context, name string) (organization *Organization, err error) {
if name, err = CheckName(name); err != nil {
return nil, err
}
organization = &Organization{}
if err := s.storage.Get(ctx, path.Join(organizationsRootKey, name), organization, true); err != nil {
return nil, err
}
// If there's no "name" in the answer, it means the organization has not been found, so return nil
if organization.GetName() == "" {
return nil, nil
}
return organization, nil
}
// ListOrganizations lists organizations
func (s *Store) ListOrganizations(ctx context.Context) ([]*Organization, error) {
protos := []proto.Message{}
if err := s.storage.List(ctx, organizationsRootKey, storage.Everything, &Organization{}, &protos); err != nil {
return nil, err
}
organizations := []*Organization{}
for _, proto := range protos {
organizations = append(organizations, proto.(*Organization))
}
return organizations, nil
}
// DeleteOrganization deletes a organization by name
func (s *Store) DeleteOrganization(ctx context.Context, name string) error {
// Check authorization
if name == SuperOrganization || name == DefaultOrganization {
return NotAuthorized
}
if !s.IsAuthorized(ctx, &Account{"", name}, DeleteAction, OrganizationRN, name) {
return NotAuthorized
}
// Delete organization
if err := s.storage.Delete(ctx, path.Join(organizationsRootKey, name), false, nil); err != nil {
return err
}
return nil
}
// Teams
// CreateTeam creates a new team
func (s *Store) CreateTeam(ctx context.Context, organizationName, teamName string) error {
// Check authorization
if !s.IsAuthorized(ctx, &Account{"", organizationName}, CreateAction, TeamRN, teamName) {
return NotAuthorized
}
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Check if team already exists
if organization.hasTeam(teamName) {
return nil, TeamAlreadyExists
}
// Create the new team
team := &Team{
Name: teamName,
Owner: GetRequesterAccount(ctx),
CreateDt: time.Now().Unix(),
Members: []string{auth.GetUser(ctx)},
}
// Add the team to the organization
organization.Teams = append(organization.Teams, team)
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
// AddUserToTeam adds a user to the given team
func (s *Store) AddUserToTeam(ctx context.Context, organizationName string, teamName string, userName string) error {
// Get the user
user, err := s.getVerifiedUser(ctx, userName)
if err != nil {
return err
}
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Get team
team := organization.getTeam(teamName)
if team == nil {
return nil, TeamNotFound
}
// Check authorization
if !s.IsAuthorized(ctx, team.Owner, UpdateAction, TeamRN, teamName) {
return nil, NotAuthorized
}
// Check if user is part of the organization
if !organization.HasMember(user.Name) {
return nil, NotPartOfOrganization
}
// Check if user is part of the team
if team.hasMember(user.Name) {
return nil, UserAlreadyExists
}
// Add the user as a team member
team.Members = append(team.Members, user.Name)
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
// RemoveUserFromTeam removes a user from the given team
func (s *Store) RemoveUserFromTeam(ctx context.Context, organizationName string, teamName string, userName string) error {
// Get the user
user, err := s.getVerifiedUser(ctx, userName)
if err != nil {
return err
}
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Get team
team := organization.getTeam(teamName)
if team == nil {
return nil, TeamNotFound
}
// Check authorization
if !s.IsAuthorized(ctx, team.Owner, UpdateAction, TeamRN, teamName) {
return nil, NotAuthorized
}
// Check if user is actually a member
memberIndex := team.getMemberIndex(user.Name)
if memberIndex == -1 {
return nil, UserNotFound
}
// Remove the user from members. For details, check http://stackoverflow.com/questions/25025409/delete-element-in-a-slice
team.Members = append(team.Members[:memberIndex], team.Members[memberIndex+1:]...)
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
// AddResourceToTeam adds a resource to the given team
func (s *Store) AddResourceToTeam(ctx context.Context, organizationName string, teamName string, resourceID string) error {
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Get team
team := organization.getTeam(teamName)
if team == nil {
return nil, TeamNotFound
}
// Check authorization
if !s.IsAuthorized(ctx, team.Owner, UpdateAction, TeamRN, teamName) {
return nil, NotAuthorized
}
// Check if resource is already added to the team
if team.hasResource(resourceID) {
return nil, ResourceAlreadyExists
}
// Add the resource
team.Resources = append(team.Resources, &TeamResource{
Id: resourceID,
PermissionLevel: TeamPermissionLevel_TEAM_READ,
})
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
// RemoveResourceFromTeam removes a resource from the given team
func (s *Store) RemoveResourceFromTeam(ctx context.Context, organizationName string, teamName string, resourceID string) error {
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Get team
team := organization.getTeam(teamName)
if team == nil {
return nil, TeamNotFound
}
// Check authorization
if !s.IsAuthorized(ctx, team.Owner, UpdateAction, TeamRN, teamName) {
return nil, NotAuthorized
}
// Check if resource is already present
resourceIndex := team.getResourceIndex(resourceID)
if resourceIndex == -1 {
return nil, ResourceNotFound
}
// Remove the resource from team resources. For details, check http://stackoverflow.com/questions/25025409/delete-element-in-a-slice
team.Resources = append(team.Resources[:resourceIndex], team.Resources[resourceIndex+1:]...)
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
// ChangeTeamResourcePermissionLevel changes the permission level over the given resource in the given team
func (s *Store) ChangeTeamResourcePermissionLevel(ctx context.Context, organizationName string, teamName string, resourceID string, permissionLevel TeamPermissionLevel) (err error) {
// Update organization
uf := func(current proto.Message) (proto.Message, error) {
organization, ok := current.(*Organization)
if !ok {
return nil, fmt.Errorf("value is not the right type (expected Organization): %T", organization)
}
// Get team
team := organization.getTeam(teamName)
if team == nil {
return nil, TeamNotFound
}
// Check authorization
if !s.IsAuthorized(ctx, team.Owner, UpdateAction, TeamRN, teamName) {
return nil, NotAuthorized
}
// Check if resource is associated to the team
resource := team.getResourceById(resourceID)
if resource == nil {
return nil, ResourceNotFound
}
// Change the permission level over the given resource
resource.PermissionLevel = permissionLevel
// Validate update
if err := organization.Validate(); err != nil {
return nil, err
}
return organization, nil
}
if err := s.storage.Update(ctx, path.Join(organizationsRootKey, organizationName), uf, &Organization{}); err != nil {
if err == storage.NotFound {
return OrganizationNotFound
}
return err
}
return nil
}
// ChangeTeamName changes the name of given team
func (s *Store) ChangeTeamName(ctx context.Context, organizationName string, teamName, newName string) (err error) {
// Update organization
uf := func(current proto.Message) (proto.Message, error) {