forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.go
855 lines (791 loc) · 25.9 KB
/
rest.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
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package rest
import (
"context"
"fmt"
"io"
"strings"
"github.com/emicklei/go-restful"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/micro/go-micro/errors"
"github.com/pborman/uuid"
"go.uber.org/zap"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/config"
"github.com/pydio/cells/common/log"
defaults "github.com/pydio/cells/common/micro"
"github.com/pydio/cells/common/proto/idm"
"github.com/pydio/cells/common/proto/jobs"
"github.com/pydio/cells/common/proto/mailer"
"github.com/pydio/cells/common/proto/rest"
"github.com/pydio/cells/common/registry"
"github.com/pydio/cells/common/service"
"github.com/pydio/cells/common/service/frontend"
service2 "github.com/pydio/cells/common/service/proto"
"github.com/pydio/cells/common/service/resources"
"github.com/pydio/cells/common/utils/permissions"
"github.com/pydio/cells/idm/user/grpc"
)
var profilesLevel = map[string]int{
common.PYDIO_PROFILE_ANON: 0,
common.PYDIO_PROFILE_SHARED: 1,
common.PYDIO_PROFILE_STANDARD: 2,
common.PYDIO_PROFILE_ADMIN: 3,
}
type UserHandler struct {
resources.ResourceProviderHandler
}
func NewUserHandler() *UserHandler {
h := &UserHandler{}
h.PoliciesLoader = h.PoliciesForUserId
h.ServiceName = common.SERVICE_USER
h.ResourceName = "user"
return h
}
// SwaggerTags list the names of the service tags declared in the swagger json implemented by this service.
func (s *UserHandler) SwaggerTags() []string {
return []string{"UserService"}
}
// Filter returns a function to filter the swagger path.
func (s *UserHandler) Filter() func(string) string {
return func(s string) string {
return strings.Replace(s, "{Login}", "{Login:*}", 1)
}
}
// GetUser finds a user by her login, answering to rest endpoint GET:/a/user/{Login}.
func (s *UserHandler) GetUser(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
login := req.PathParameter("Login")
if login == "" {
service.RestError500(req, rsp, errors.BadRequest("user.missing.login", "please provide a login"))
return
}
qLogin, _ := ptypes.MarshalAny(&idm.UserSingleQuery{Login: login})
query := &service2.Query{
Limit: 1,
Offset: 0,
SubQueries: []*any.Any{qLogin},
}
query.ResourcePolicyQuery, _ = s.RestToServiceResourcePolicy(ctx, nil)
var result *idm.User
cli := idm.NewUserServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_USER, defaults.NewClient())
streamer, err := cli.SearchUser(ctx, &idm.SearchUserRequest{
Query: query,
})
if err != nil {
// Handle error
service.RestError500(req, rsp, err)
return
}
defer streamer.Close()
for {
resp, e := streamer.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
u := resp.User
u.Roles = permissions.GetRolesForUser(ctx, u, false)
result = u.WithPublicData(ctx, s.IsContextEditable(ctx, u.Uuid, u.Policies))
}
if result != nil {
rsp.WriteEntity(result)
} else {
service.RestError404(req, rsp, errors.NotFound("user.notfound", "cannot find user with login %s", login))
}
}
// SearchUsers performs a paginated query to the user repository.
// Warning: in the returned result, users and groups are stored in two distinct arrays.
func (s *UserHandler) SearchUsers(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
var userReq rest.SearchUserRequest
err := req.ReadEntity(&userReq)
log.Logger(ctx).Debug("Received User.Get API request", zap.Any("q", userReq), zap.Error(err))
// Ignore empty body
if err != nil && err != io.EOF {
service.RestError500(req, rsp, err)
return
}
// Transform to standard query
query := &service2.Query{
Limit: userReq.Limit,
Offset: userReq.Offset,
GroupBy: userReq.GroupBy,
Operation: userReq.Operation,
}
var er error
if query.ResourcePolicyQuery, er = s.RestToServiceResourcePolicy(ctx, userReq.ResourcePolicyQuery); er != nil {
log.Logger(ctx).Error("403", zap.Error(er))
service.RestError403(req, rsp, er)
return
}
for _, q := range userReq.Queries {
anyfied, _ := ptypes.MarshalAny(q)
if q.Login != "" && strings.HasSuffix(q.Login, "*") {
// This is a wildcard on line, transform this query to a search on login OR displayName
attQuery, _ := ptypes.MarshalAny(&idm.UserSingleQuery{
AttributeName: "displayName",
AttributeValue: q.Login,
})
wildQuery, _ := ptypes.MarshalAny(&service2.Query{
Operation: service2.OperationType_OR,
SubQueries: []*any.Any{anyfied, attQuery},
})
query.SubQueries = append(query.SubQueries, wildQuery)
} else {
query.SubQueries = append(query.SubQueries, anyfied)
}
}
cli := idm.NewUserServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_USER, defaults.NewClient())
resp, err := cli.CountUser(ctx, &idm.SearchUserRequest{
Query: query,
})
if err != nil {
// Handle error
service.RestError500(req, rsp, err)
return
}
response := &rest.UsersCollection{
Total: resp.Count,
}
if !userReq.CountOnly {
streamer, err := cli.SearchUser(ctx, &idm.SearchUserRequest{
Query: query,
})
if err != nil {
// Handle error
service.RestError500(req, rsp, err)
return
}
defer streamer.Close()
for {
resp, e := streamer.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
u := resp.User
if resp.User.IsGroup {
u.Roles = append(u.Roles, &idm.Role{Uuid: u.Uuid, GroupRole: true})
u.Roles = permissions.GetRolesForUser(ctx, u, true)
response.Groups = append(response.Groups, u)
} else {
u.Roles = permissions.GetRolesForUser(ctx, u, false)
response.Users = append(response.Users, u.WithPublicData(ctx, s.IsContextEditable(ctx, u.Uuid, u.Policies)))
}
}
}
if len(response.Users) > 0 {
paramsAclsToAttributes(ctx, response.Users)
}
rsp.WriteEntity(response)
}
// DeleteUser removes a user or group from the repository.
func (s *UserHandler) DeleteUser(req *restful.Request, rsp *restful.Response) {
login := req.PathParameter("Login")
ctx := req.Request.Context()
singleQ := &idm.UserSingleQuery{}
uName, claims := permissions.FindUserNameInContext(ctx)
if strings.HasSuffix(req.Request.RequestURI, "%2F") || strings.HasSuffix(req.Request.RequestURI, "/") {
log.Logger(req.Request.Context()).Info("Received User.Delete API request (GROUP)", zap.String("login", login), zap.String("crtGroup", claims.GroupPath), zap.String("request", req.Request.RequestURI))
if strings.HasPrefix(claims.GroupPath, "/"+login) {
service.RestError403(req, rsp, errors.Forbidden(common.SERVICE_USER, "You are about to delete your own group!"))
return
}
singleQ.GroupPath = login
singleQ.Recursive = true
} else {
if uName == login {
service.RestError403(req, rsp, errors.Forbidden(common.SERVICE_USER, "Please make sure not to delete yourself!"))
return
}
log.Logger(req.Request.Context()).Debug("Received User.Delete API request (LOGIN)", zap.String("login", login), zap.String("request", req.Request.RequestURI))
singleQ.Login = login
}
query, _ := ptypes.MarshalAny(singleQ)
mainQuery := &service2.Query{SubQueries: []*any.Any{query}}
cli := idm.NewUserServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_USER, defaults.NewClient())
// Search first to check policies
stream, err := cli.SearchUser(ctx, &idm.SearchUserRequest{Query: mainQuery})
if err != nil {
service.RestError500(req, rsp, err)
return
}
defer stream.Close()
for {
response, e := stream.Recv()
if e != nil {
break
}
if response == nil {
continue
}
if !s.MatchPolicies(ctx, response.User.Uuid, response.User.Policies, service2.ResourcePolicyAction_WRITE) {
log.Auditer(ctx).Error(
fmt.Sprintf("Forbidden action: could not delete user [%s]", response.User.Login),
log.GetAuditId(common.AUDIT_USER_DELETE),
response.User.ZapUuid(),
)
service.RestError403(req, rsp, errors.Forbidden(common.SERVICE_USER, "You are not allowed to edit this resource"))
return
}
break
}
if singleQ.GroupPath != "" {
uName, _ := permissions.FindUserNameInContext(ctx)
// This is a group deletion - send it in background
jobUuid := uuid.New()
job := &jobs.Job{
ID: "delete-group-" + jobUuid,
Owner: uName,
Label: "Delete groups in background",
MaxConcurrency: 1,
AutoStart: true,
AutoClean: true,
Actions: []*jobs.Action{
{
ID: grpc.DeleteUsersActionName,
Parameters: map[string]string{
"groupPath": singleQ.GroupPath,
},
},
},
}
cli := jobs.NewJobServiceClient(registry.GetClient(common.SERVICE_JOBS))
_, er := cli.PutJob(ctx, &jobs.PutJobRequest{Job: job})
if er != nil {
service.RestError500(req, rsp, er)
} else {
rsp.WriteEntity(&rest.DeleteResponse{Success: true, NumRows: 0})
}
} else {
// Now delete user or group
n, e := cli.DeleteUser(req.Request.Context(), &idm.DeleteUserRequest{Query: mainQuery})
if e != nil {
service.RestError500(req, rsp, e)
} else {
msg := fmt.Sprintf("Deleted user [%s]", login)
if n.RowsDeleted > 1 {
msg = fmt.Sprintf("Deleted %d users", n.RowsDeleted)
}
log.Auditer(ctx).Info(msg,
log.GetAuditId(common.AUDIT_USER_DELETE),
)
rsp.WriteEntity(&rest.DeleteResponse{Success: true, NumRows: n.RowsDeleted})
}
}
}
// PutUser creates or updates a User if calling client has sufficient permissions.
func (s *UserHandler) PutUser(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
var inputUser idm.User
err := req.ReadEntity(&inputUser)
if err != nil {
log.Logger(ctx).Error("cannot fetch idm.User from request", zap.Error(err))
service.RestError500(req, rsp, err)
return
}
cli := idm.NewUserServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_USER, defaults.NewClient())
log.Logger(req.Request.Context()).Debug("Received User.Put API request", inputUser.ZapLogin())
var update *idm.User
if inputUser.Uuid != "" {
if existing, exists := s.userById(ctx, inputUser.Uuid, cli); exists {
update = existing
}
} else {
if _, err := permissions.SearchUniqueUser(ctx, inputUser.Login, ""); err == nil {
service.RestError403(req, rsp, fmt.Errorf("User with the same login already exists!"))
return
}
}
var existingAcls []*idm.ACL
ctxLogin, ctxClaims := permissions.FindUserNameInContext(ctx)
if update != nil {
// Check User Policies
if !s.MatchPolicies(ctx, update.Uuid, update.Policies, service2.ResourcePolicyAction_WRITE) {
log.Auditer(ctx).Error(
fmt.Sprintf("Forbidden action: could not edit user [%s]", update.GetLogin()),
log.GetAuditId(common.AUDIT_USER_UPDATE),
update.ZapUuid(),
)
service.RestError403(req, rsp, errors.Forbidden(common.SERVICE_USER, "You are not allowed to edit this user!"))
return
}
// Check ADD/REMOVE Roles Policies
roleCli := idm.NewRoleServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ROLE, defaults.NewClient())
rolesToCheck := s.diffRoles(inputUser.Roles, update.Roles)
removes := s.diffRoles(update.Roles, inputUser.Roles)
log.Logger(ctx).Debug("ADD/REMOVE ROLES", zap.Any("add", rolesToCheck), zap.Any("remove", removes), zap.Any("new", inputUser.Roles), zap.Any("existings", update.Roles))
rolesToCheck = append(rolesToCheck, removes...)
if err := s.checkCanAssignRoles(ctx, rolesToCheck, roleCli); err != nil {
log.Auditer(ctx).Error(
fmt.Sprintf("Forbidden action: could not assign roles on [%s]", update.GetLogin()),
log.GetAuditId(common.AUDIT_USER_UPDATE),
update.ZapUuid(),
)
service.RestError403(req, rsp, err)
return
}
// Check user own password change
if inputUser.Password != "" && ctxLogin == inputUser.Login {
if _, err := cli.BindUser(ctx, &idm.BindUserRequest{UserName: inputUser.Login, Password: inputUser.OldPassword}); err != nil {
service.RestError401(req, rsp, err)
return
}
}
// Load current ACLs for personal role
for _, r := range update.Roles {
if r.UserRole {
existingAcls = permissions.GetACLsForRoles(ctx, []*idm.Role{r}, &idm.ACLAction{Name: "parameter:*"})
}
}
// Put back the pydio: attributes
if update.Attributes != nil {
for k, v := range update.Attributes {
if strings.HasPrefix(k, idm.UserAttrPrivatePrefix) {
if inputUser.Attributes == nil {
inputUser.Attributes = map[string]string{}
}
inputUser.Attributes[k] = v
}
}
}
}
// Check specific frontend USER_CREATE_USERS permission
var isHidden bool
if h, o := inputUser.Attributes["hidden"]; o && h == "true" {
isHidden = true
}
if update == nil && !config.Get("frontend", "plugin", "core.auth", "USER_CREATE_USERS").Bool(true) && ctxClaims.Profile != common.PYDIO_PROFILE_ADMIN && !isHidden {
service.RestError403(req, rsp, fmt.Errorf("you are not allowed to create users"))
return
}
if inputUser.IsGroup {
if ctxClaims.Profile != common.PYDIO_PROFILE_ADMIN {
service.RestError403(req, rsp, fmt.Errorf("you are not allowed to create groups"))
return
}
inputUser.GroupPath = strings.TrimSuffix(inputUser.GroupPath, "/") + "/" + inputUser.GroupLabel
} else {
// Add a default profile
if _, ok := inputUser.Attributes[idm.UserAttrProfile]; !ok {
inputUser.Attributes[idm.UserAttrProfile] = common.PYDIO_PROFILE_SHARED
}
// Check profile is not higher than current user profile
if profilesLevel[inputUser.Attributes[idm.UserAttrProfile]] > profilesLevel[ctxClaims.Profile] {
service.RestError403(req, rsp, fmt.Errorf("you are not allowed to set a profile (%s) higher than your current profile (%s)", inputUser.Attributes[idm.UserAttrProfile], ctxClaims.Profile))
return
}
if _, ok := inputUser.Attributes[idm.UserAttrPassHashed]; ok {
service.RestError403(req, rsp, fmt.Errorf("you are not allowed to use this attribute"))
return
}
}
var acls []*idm.ACL
var deleteAclActions []string
var sendEmail bool
cleanAttributes := map[string]string{}
for k, v := range inputUser.Attributes {
if k == "send_email" {
sendEmail = v == "true"
continue
}
if strings.HasPrefix(k, "parameter:") {
if !allowedAclKey(k, true) {
continue
}
var acl = &idm.ACL{
Action: &idm.ACLAction{Name: k, Value: v},
WorkspaceID: "PYDIO_REPO_SCOPE_ALL",
}
for _, existing := range existingAcls {
if existing.Action != nil && existing.Action.Name == k {
deleteAclActions = append(deleteAclActions, existing.Action.Name)
}
}
acls = append(acls, acl)
continue
}
cleanAttributes[k] = v
}
inputUser.Attributes = cleanAttributes
response, er := cli.CreateUser(ctx, &idm.CreateUserRequest{
User: &inputUser,
})
if er != nil {
service.RestError500(req, rsp, er)
return
}
if update == nil {
var newRole *idm.Role
if inputUser.IsGroup {
newRole = &idm.Role{
Uuid: response.User.Uuid,
GroupRole: true,
Label: "Group " + response.User.GroupLabel,
}
} else {
newRole = &idm.Role{
Uuid: response.User.Uuid,
UserRole: true,
Label: "User " + response.User.Login,
Policies: []*service2.ResourcePolicy{
{Subject: "profile:standard", Action: service2.ResourcePolicyAction_READ, Effect: service2.ResourcePolicy_allow},
{Subject: "user:" + response.User.Login, Action: service2.ResourcePolicyAction_WRITE, Effect: service2.ResourcePolicy_allow},
{Subject: "profile:admin", Action: service2.ResourcePolicyAction_WRITE, Effect: service2.ResourcePolicy_allow},
},
}
}
roleCli := idm.NewRoleServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ROLE, defaults.NewClient())
_, er := roleCli.CreateRole(ctx, &idm.CreateRoleRequest{Role: newRole})
if er != nil {
service.RestError500(req, rsp, er)
return
}
}
out := response.User
path := "/"
if len(out.GroupPath) > 1 {
path = out.GroupPath + "/"
}
if update != nil {
if out.IsGroup {
log.Auditer(ctx).Info(
fmt.Sprintf("Updated group [%s]", out.GroupPath),
log.GetAuditId(common.AUDIT_GROUP_UPDATE),
out.ZapUuid(),
)
} else {
log.Auditer(ctx).Info(
fmt.Sprintf("Updated user [%s%s]", path, out.Login),
log.GetAuditId(common.AUDIT_USER_UPDATE),
out.ZapUuid(),
)
}
} else {
if out.IsGroup {
log.Auditer(ctx).Info(
fmt.Sprintf("Created group [%s]", out.GroupPath),
log.GetAuditId(common.AUDIT_GROUP_CREATE),
out.ZapUuid(),
)
} else {
log.Auditer(ctx).Info(
fmt.Sprintf("Created user [%s%s]", path, out.Login),
log.GetAuditId(common.AUDIT_USER_CREATE),
out.ZapUuid(),
)
}
}
u := response.User
if len(acls) > 0 {
aclClient := idm.NewACLServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ACL, defaults.NewClient())
if len(deleteAclActions) > 0 {
delQuery := &service2.Query{Operation: service2.OperationType_OR}
for _, action := range deleteAclActions {
q, _ := ptypes.MarshalAny(&idm.ACLSingleQuery{
RoleIDs: []string{u.Uuid},
Actions: []*idm.ACLAction{{Name: action}},
WorkspaceIDs: []string{"PYDIO_REPO_SCOPE_ALL"},
})
delQuery.SubQueries = append(delQuery.SubQueries, q)
}
if _, e := aclClient.DeleteACL(ctx, &idm.DeleteACLRequest{Query: delQuery}); e != nil {
log.Logger(ctx).Error("Could not delete existing ACLs", zap.Error(e))
}
}
for _, acl := range acls {
acl.RoleID = u.Uuid
if _, e := aclClient.CreateACL(ctx, &idm.CreateACLRequest{ACL: acl}); e != nil {
log.Logger(ctx).Error("Could not store ACL", acl.Zap(), zap.Error(e))
}
}
}
if !u.IsGroup {
permissions.ForceClearUserCache(u.Login)
}
// Reload user fully
q, _ := ptypes.MarshalAny(&idm.UserSingleQuery{Uuid: u.Uuid})
streamer, err := cli.SearchUser(ctx, &idm.SearchUserRequest{
Query: &service2.Query{SubQueries: []*any.Any{q}},
})
if err != nil {
// Handle error
service.RestError500(req, rsp, err)
return
}
defer streamer.Close()
for {
resp, e := streamer.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
u = resp.User
if !resp.User.IsGroup {
u.Roles = permissions.GetRolesForUser(ctx, u, false)
u = u.WithPublicData(ctx, s.IsContextEditable(ctx, u.Uuid, u.Policies))
paramsAclsToAttributes(ctx, []*idm.User{u})
} else if len(u.Roles) == 0 {
u.Roles = append(u.Roles, &idm.Role{Uuid: u.Uuid, GroupRole: true})
u.Roles = permissions.GetRolesForUser(ctx, u, true)
}
break
}
rsp.WriteEntity(u)
_, hasEmailAddress := u.Attributes["email"]
if sendEmail && hasEmailAddress {
// Now send email to user in background
mailCli := mailer.NewMailerServiceClient(registry.GetClient(common.SERVICE_MAILER))
email := &mailer.Mail{
To: []*mailer.User{{
Uuid: u.Uuid,
Name: u.Attributes["displayName"],
Address: u.Attributes["email"],
}},
TemplateId: "Welcome",
TemplateData: map[string]string{
"Login": inputUser.Login,
"Password": inputUser.Password,
},
}
c := context.Background()
if u := ctx.Value(common.PYDIO_CONTEXT_USER_KEY); u != nil {
c = context.WithValue(c, common.PYDIO_CONTEXT_USER_KEY, u)
}
go func() {
_, er := mailCli.SendMail(c, &mailer.SendMailRequest{
InQueue: false,
Mail: email,
})
if er != nil {
log.Logger(ctx).Error("Could not send email to new user", zap.Error(er))
}
}()
}
}
// PutRoles updates an existing user with the passed list of roles.
func (s *UserHandler) PutRoles(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
var inputUser idm.User
err := req.ReadEntity(&inputUser)
if err != nil {
log.Logger(ctx).Error("cannot fetch idm.User from rest query", zap.Error(err))
service.RestError500(req, rsp, err)
return
}
log.Logger(ctx).Debug("Received User.PutRoles API request", inputUser.ZapLogin())
if inputUser.Uuid == "" {
service.RestError500(req, rsp, errors.BadRequest(common.SERVICE_USER, "Please provide a user ID"))
return
}
cli := idm.NewUserServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_USER, defaults.NewClient())
var update *idm.User
var exists bool
if update, exists = s.userById(ctx, inputUser.Uuid, cli); !exists {
service.RestError404(req, rsp, errors.NotFound(common.SERVICE_USER, "user not found"))
return
}
// Check ADD/REMOVE Roles Policies
roleCli := idm.NewRoleServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_ROLE, defaults.NewClient())
rolesToCheck := s.diffRoles(inputUser.Roles, update.Roles)
removes := s.diffRoles(update.Roles, inputUser.Roles)
log.Logger(ctx).Debug("ADD/REMOVE ROLES", zap.Any("add", rolesToCheck), zap.Any("remove", removes), zap.Any("new", inputUser.Roles), zap.Any("existings", update.Roles))
rolesToCheck = append(rolesToCheck, removes...)
if err := s.checkCanAssignRoles(ctx, rolesToCheck, roleCli); err != nil {
log.Auditer(ctx).Error(
fmt.Sprintf("Forbidden action: could not assign roles to user [%s]", update.GetLogin()),
log.GetAuditId(common.AUDIT_USER_UPDATE),
zap.Any("rolesToCheck", rolesToCheck),
update.ZapUuid(),
zap.Any("rolesToCheck", rolesToCheck),
)
service.RestError403(req, rsp, err)
return
}
// Save existing user with new set of roles
update.Roles = inputUser.Roles
response, er := cli.CreateUser(ctx, &idm.CreateUserRequest{
User: update,
})
if er != nil {
service.RestError500(req, rsp, er)
} else {
u := response.User
u.Roles = update.Roles
log.Auditer(ctx).Info(
fmt.Sprintf("Updated roles on user [%s]", response.User.GetLogin()),
log.GetAuditId(common.AUDIT_USER_UPDATE),
response.User.ZapUuid(),
zap.Any("Roles", u.Roles),
)
rsp.WriteEntity(u.WithPublicData(ctx, s.IsContextEditable(ctx, u.Uuid, u.Policies)))
permissions.ForceClearUserCache(response.User.GetLogin())
}
}
// PoliciesForUserId retrieves policies for a given UserId.
func (s *UserHandler) PoliciesForUserId(ctx context.Context, resourceId string, resourceClient interface{}) (policies []*service2.ResourcePolicy, e error) {
user, exists := s.userById(ctx, resourceId, resourceClient.(idm.UserServiceClient))
if !exists {
return policies, errors.NotFound(common.SERVICE_USER, "cannot find user with id "+resourceId)
}
policies = user.Policies
return
}
// Load all roles that will be changed and use their Policies to check if they can be
// assigned in the current context.
func (s *UserHandler) checkCanAssignRoles(ctx context.Context, roles []*idm.Role, cli idm.RoleServiceClient) error {
if len(roles) == 0 {
// Ignore
return nil
}
var uuids []string
for _, role := range roles {
uuids = append(uuids, role.Uuid)
}
q, _ := ptypes.MarshalAny(&idm.RoleSingleQuery{Uuid: uuids})
streamer, e := cli.SearchRole(ctx, &idm.SearchRoleRequest{Query: &service2.Query{SubQueries: []*any.Any{q}}})
if e != nil {
return e
}
defer streamer.Close()
for {
rsp, e := streamer.Recv()
if e != nil {
break
}
if rsp == nil {
continue
}
if !s.MatchPolicies(ctx, rsp.Role.Uuid, rsp.Role.Policies, service2.ResourcePolicyAction_WRITE) {
log.Logger(ctx).Error("trying to assign a role that is not writeable in the context", zap.Any("r", rsp.Role))
return errors.Forbidden(common.SERVICE_USER, "You are not allowed to assign this role "+rsp.Role.Uuid)
}
}
return nil
}
// Diff two slices of roles.
func (s *UserHandler) diffRoles(as []*idm.Role, bs []*idm.Role) (diff []*idm.Role) {
for _, a := range as {
if a.UserRole || a.GroupRole {
continue
}
exists := false
for _, b := range bs {
if b.GroupRole || b.UserRole {
continue
}
if a.Uuid == b.Uuid {
exists = true
break
}
}
if !exists {
diff = append(diff, a)
}
}
return
}
// Loads an existing user by her UUID.
func (s *UserHandler) userById(ctx context.Context, userId string, cli idm.UserServiceClient) (user *idm.User, exists bool) {
subQ, _ := ptypes.MarshalAny(&idm.UserSingleQuery{
Uuid: userId,
})
stream, err := cli.SearchUser(ctx, &idm.SearchUserRequest{
Query: &service2.Query{
SubQueries: []*any.Any{subQ},
},
})
if err != nil {
return
}
defer stream.Close()
for {
rsp, e := stream.Recv()
if e != nil {
break
}
if rsp == nil {
continue
}
user = rsp.User
user.Roles = permissions.GetRolesForUser(ctx, user, false)
exists = true
break
}
return
}
// paramsAclsToAttributes adds some acl-based parameters inside user attributes.
func paramsAclsToAttributes(ctx context.Context, users []*idm.User) {
var roles []*idm.Role
for _, user := range users {
var role *idm.Role
for _, r := range user.Roles {
if r.UserRole {
role = r
break
}
}
if role != nil {
if user.Attributes == nil {
user.Attributes = map[string]string{}
}
roles = append(roles, role)
}
}
if len(roles) == 0 {
return
}
for _, acl := range permissions.GetACLsForRoles(ctx, roles, &idm.ACLAction{Name: "parameter:*"}) {
for _, user := range users {
if allowedAclKey(acl.Action.Name, user.PoliciesContextEditable) && user.Uuid == acl.RoleID {
user.Attributes[acl.Action.Name] = acl.Action.Value
}
}
}
}
func allowedAclKey(k string, contextEditable bool) bool {
pool, e := frontend.GetPluginsPool()
if e != nil {
log.Logger(context.Background()).Error("Cannot read plugins pool", zap.Error(e))
}
// Find params that contain user scope but not only that scope
params := pool.ExposedParametersByScope("user", true)
for _, param := range params {
if param.Attrscope == "user" {
continue
}
if !contextEditable && k != "parameter:core.conf:lang" && k != "parameter:core.conf:country" {
continue
}
if k == "parameter:"+param.PluginId+":"+param.Attrname {
return true
}
}
return false
}