-
-
Notifications
You must be signed in to change notification settings - Fork 169
/
roles_common.js
1121 lines (947 loc) · 30.8 KB
/
roles_common.js
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
/* global Meteor, Roles, Mongo */
/**
* Provides functions related to user authorization. Compatible with built-in Meteor accounts packages.
*
* Roles are accessible throgh `Meteor.roles` collection and documents consist of:
* - `_id`: role name
* - `children`: list of subdocuments:
* - `_id`
*
* Children list elements are subdocuments so that they can be easier extended in the future or by plugins.
*
* Roles can have multiple parents and can be children (subroles) of multiple roles.
*
* Example: `{_id: 'admin', children: [{_id: 'editor'}]}`
*
* The assignment of a role to a user is stored in a collection, accessible through `Meteor.roleAssignment`.
* It's documents consist of
* - `_id`: Internal MongoDB id
* - `role`: A role object which got assigned. Usually only contains the `_id` property
* - `user`: A user object, usually only contains the `_id` property
* - `scope`: scope name
* - `inheritedRoles`: A list of all the roles objects inherited by the assigned role.
*
* @module Roles
*/
if (!Meteor.roles) {
Meteor.roles = new Mongo.Collection('roles')
}
if (!Meteor.roleAssignment) {
Meteor.roleAssignment = new Mongo.Collection('role-assignment')
}
/**
* @class Roles
*/
if (typeof Roles === 'undefined') {
Roles = {} // eslint-disable-line no-global-assign
}
var getGroupsForUserDeprecationWarning = false
Object.assign(Roles, {
/**
* Used as a global group (now scope) name. Not used anymore.
*
* @property GLOBAL_GROUP
* @static
* @deprecated
*/
GLOBAL_GROUP: null,
/**
* Create a new role.
*
* @method createRole
* @param {String} roleName Name of role.
* @param {Object} [options] Options:
* - `unlessExists`: if `true`, exception will not be thrown in the role already exists
* @return {String} ID of the new role or null.
* @static
*/
createRole: function (roleName, options) {
Roles._checkRoleName(roleName)
options = Object.assign({
unlessExists: false
}, options)
var result = Meteor.roles.upsert({ _id: roleName }, { $setOnInsert: { children: [] } })
if (!result.insertedId) {
if (options.unlessExists) return null
throw new Error('Role \'' + roleName + '\' already exists.')
}
return result.insertedId
},
/**
* Delete an existing role.
*
* If the role is set for any user, it is automatically unset.
*
* @method deleteRole
* @param {String} roleName Name of role.
* @static
*/
deleteRole: function (roleName) {
var roles
var inheritedRoles
Roles._checkRoleName(roleName)
// Remove all assignments
Meteor.roleAssignment.remove({
'role._id': roleName
})
do {
// For all roles who have it as a dependency ...
roles = Roles._getParentRoleNames(Meteor.roles.findOne({ _id: roleName }))
Meteor.roles.find({ _id: { $in: roles } }).fetch().forEach(r => {
Meteor.roles.update({
_id: r._id
}, {
$pull: {
children: {
_id: roleName
}
}
})
inheritedRoles = Roles._getInheritedRoleNames(Meteor.roles.findOne({ _id: r._id }))
Meteor.roleAssignment.update({
'role._id': r._id
}, {
$set: {
inheritedRoles: [r._id, ...inheritedRoles].map(r2 => ({ _id: r2 }))
}
}, { multi: true })
})
} while (roles.length > 0)
// And finally remove the role itself
Meteor.roles.remove({ _id: roleName })
},
/**
* Rename an existing role.
*
* @method renameRole
* @param {String} oldName Old name of a role.
* @param {String} newName New name of a role.
* @static
*/
renameRole: function (oldName, newName) {
var role
var count
Roles._checkRoleName(oldName)
Roles._checkRoleName(newName)
if (oldName === newName) return
role = Meteor.roles.findOne({ _id: oldName })
if (!role) {
throw new Error('Role \'' + oldName + '\' does not exist.')
}
role._id = newName
Meteor.roles.insert(role)
do {
count = Meteor.roleAssignment.update({
'role._id': oldName
}, {
$set: {
'role._id': newName
}
}, { multi: true })
} while (count > 0)
do {
count = Meteor.roleAssignment.update({
'inheritedRoles._id': oldName
}, {
$set: {
'inheritedRoles.$._id': newName
}
}, { multi: true })
} while (count > 0)
do {
count = Meteor.roles.update({
'children._id': oldName
}, {
$set: {
'children.$._id': newName
}
}, { multi: true })
} while (count > 0)
Meteor.roles.remove({ _id: oldName })
},
/**
* Add role parent to roles.
*
* Previous parents are kept (role can have multiple parents). For users which have the
* parent role set, new subroles are added automatically.
*
* @method addRolesToParent
* @param {Array|String} rolesNames Name(s) of role(s).
* @param {String} parentName Name of parent role.
* @static
*/
addRolesToParent: function (rolesNames, parentName) {
// ensure arrays
if (!Array.isArray(rolesNames)) rolesNames = [rolesNames]
rolesNames.forEach(function (roleName) {
Roles._addRoleToParent(roleName, parentName)
})
},
/**
* @method _addRoleToParent
* @param {String} roleName Name of role.
* @param {String} parentName Name of parent role.
* @private
* @static
*/
_addRoleToParent: function (roleName, parentName) {
var role
var count
Roles._checkRoleName(roleName)
Roles._checkRoleName(parentName)
// query to get role's children
role = Meteor.roles.findOne({ _id: roleName })
if (!role) {
throw new Error('Role \'' + roleName + '\' does not exist.')
}
// detect cycles
if (Roles._getInheritedRoleNames(role).includes(parentName)) {
throw new Error('Roles \'' + roleName + '\' and \'' + parentName + '\' would form a cycle.')
}
count = Meteor.roles.update({
_id: parentName,
'children._id': {
$ne: role._id
}
}, {
$push: {
children: {
_id: role._id
}
}
})
// if there was no change, parent role might not exist, or role is
// already a subrole; in any case we do not have anything more to do
if (!count) return
Meteor.roleAssignment.update({
'inheritedRoles._id': parentName
}, {
$push: {
inheritedRoles: { $each: [role._id, ...Roles._getInheritedRoleNames(role)].map(r => ({ _id: r })) }
}
}, { multi: true })
},
/**
* Remove role parent from roles.
*
* Other parents are kept (role can have multiple parents). For users which have the
* parent role set, removed subrole is removed automatically.
*
* @method removeRolesFromParent
* @param {Array|String} rolesNames Name(s) of role(s).
* @param {String} parentName Name of parent role.
* @static
*/
removeRolesFromParent: function (rolesNames, parentName) {
// ensure arrays
if (!Array.isArray(rolesNames)) rolesNames = [rolesNames]
rolesNames.forEach(function (roleName) {
Roles._removeRoleFromParent(roleName, parentName)
})
},
/**
* @method _removeRoleFromParent
* @param {String} roleName Name of role.
* @param {String} parentName Name of parent role.
* @private
* @static
*/
_removeRoleFromParent: function (roleName, parentName) {
Roles._checkRoleName(roleName)
Roles._checkRoleName(parentName)
// check for role existence
// this would not really be needed, but we are trying to match addRolesToParent
let role = Meteor.roles.findOne({ _id: roleName }, { fields: { _id: 1 } })
if (!role) {
throw new Error('Role \'' + roleName + '\' does not exist.')
}
const count = Meteor.roles.update({
_id: parentName
}, {
$pull: {
children: {
_id: role._id
}
}
})
// if there was no change, parent role might not exist, or role was
// already not a subrole; in any case we do not have anything more to do
if (!count) return
// For all roles who have had it as a dependency ...
const roles = [...Roles._getParentRoleNames(Meteor.roles.findOne({ _id: parentName })), parentName]
Meteor.roles.find({ _id: { $in: roles } }).fetch().forEach(r => {
const inheritedRoles = Roles._getInheritedRoleNames(Meteor.roles.findOne({ _id: r._id }))
Meteor.roleAssignment.update({
'role._id': r._id,
'inheritedRoles._id': role._id
}, {
$set: {
inheritedRoles: [r._id, ...inheritedRoles].map(r2 => ({ _id: r2 }))
}
}, { multi: true })
})
},
/**
* Add users to roles.
*
* Adds roles to existing roles for each user.
*
* @example
* Roles.addUsersToRoles(userId, 'admin')
* Roles.addUsersToRoles(userId, ['view-secrets'], 'example.com')
* Roles.addUsersToRoles([user1, user2], ['user','editor'])
* Roles.addUsersToRoles([user1, user2], ['glorious-admin', 'perform-action'], 'example.org')
*
* @method addUsersToRoles
* @param {Array|String} users User ID(s) or object(s) with an `_id` field.
* @param {Array|String} roles Name(s) of roles to add users to. Roles have to exist.
* @param {Object|String} [options] Options:
* - `scope`: name of the scope, or `null` for the global role
* - `ifExists`: if `true`, do not throw an exception if the role does not exist
*
* Alternatively, it can be a scope name string.
* @static
*/
addUsersToRoles: function (users, roles, options) {
var id
if (!users) throw new Error('Missing \'users\' param.')
if (!roles) throw new Error('Missing \'roles\' param.')
options = Roles._normalizeOptions(options)
// ensure arrays
if (!Array.isArray(users)) users = [users]
if (!Array.isArray(roles)) roles = [roles]
Roles._checkScopeName(options.scope)
options = Object.assign({
ifExists: false
}, options)
users.forEach(function (user) {
if (typeof user === 'object') {
id = user._id
} else {
id = user
}
roles.forEach(function (role) {
Roles._addUserToRole(id, role, options)
})
})
},
/**
* Set users' roles.
*
* Replaces all existing roles with a new set of roles.
*
* @example
* Roles.setUserRoles(userId, 'admin')
* Roles.setUserRoles(userId, ['view-secrets'], 'example.com')
* Roles.setUserRoles([user1, user2], ['user','editor'])
* Roles.setUserRoles([user1, user2], ['glorious-admin', 'perform-action'], 'example.org')
*
* @method setUserRoles
* @param {Array|String} users User ID(s) or object(s) with an `_id` field.
* @param {Array|String} roles Name(s) of roles to add users to. Roles have to exist.
* @param {Object|String} [options] Options:
* - `scope`: name of the scope, or `null` for the global role
* - `anyScope`: if `true`, remove all roles the user has, of any scope, if `false`, only the one in the same scope
* - `ifExists`: if `true`, do not throw an exception if the role does not exist
*
* Alternatively, it can be a scope name string.
* @static
*/
setUserRoles: function (users, roles, options) {
var id
if (!users) throw new Error('Missing \'users\' param.')
if (!roles) throw new Error('Missing \'roles\' param.')
options = Roles._normalizeOptions(options)
// ensure arrays
if (!Array.isArray(users)) users = [users]
if (!Array.isArray(roles)) roles = [roles]
Roles._checkScopeName(options.scope)
options = Object.assign({
ifExists: false,
anyScope: false
}, options)
users.forEach(function (user) {
if (typeof user === 'object') {
id = user._id
} else {
id = user
}
// we first clear all roles for the user
const selector = { 'user._id': id }
if (!options.anyScope) {
selector.scope = options.scope
}
Meteor.roleAssignment.remove(selector)
// and then add all
roles.forEach(function (role) {
Roles._addUserToRole(id, role, options)
})
})
},
/**
* Add one user to one role.
*
* @method _addUserToRole
* @param {String} userId The user ID.
* @param {String} roleName Name of the role to add the user to. The role have to exist.
* @param {Object} options Options:
* - `scope`: name of the scope, or `null` for the global role
* - `ifExists`: if `true`, do not throw an exception if the role does not exist
* @private
* @static
*/
_addUserToRole: function (userId, roleName, options) {
Roles._checkRoleName(roleName)
Roles._checkScopeName(options.scope)
if (!userId) {
return
}
const role = Meteor.roles.findOne({ _id: roleName }, { fields: { children: 1 } })
if (!role) {
if (options.ifExists) {
return []
} else {
throw new Error('Role \'' + roleName + '\' does not exist.')
}
}
// This might create duplicates, because we don't have a unique index, but that's all right. In case there are two, withdrawing the role will effectively kill them both.
const res = Meteor.roleAssignment.upsert({
'user._id': userId,
'role._id': roleName,
scope: options.scope
}, {
$setOnInsert: {
user: { _id: userId },
role: { _id: roleName },
scope: options.scope
}
})
if (res.insertedId) {
Meteor.roleAssignment.update({ _id: res.insertedId }, {
$set: {
inheritedRoles: [roleName, ...Roles._getInheritedRoleNames(role)].map(r => ({ _id: r }))
}
})
}
return res
},
/**
* Returns an array of role names the given role name is a child of.
*
* @example
* Roles._getParentRoleNames({ _id: 'admin', children; [] })
*
* @method _getParentRoleNames
* @param {object} role The role object
* @private
* @static
*/
_getParentRoleNames: function (role) {
var parentRoles
if (!role) {
return []
}
parentRoles = new Set([role._id])
parentRoles.forEach(roleName => {
Meteor.roles.find({ 'children._id': roleName }).fetch().forEach(parentRole => {
parentRoles.add(parentRole._id)
})
})
parentRoles.delete(role._id)
return [...parentRoles]
},
/**
* Returns an array of role names the given role name is a parent of.
*
* @example
* Roles._getInheritedRoleNames({ _id: 'admin', children; [] })
*
* @method _getInheritedRoleNames
* @param {object} role The role object
* @private
* @static
*/
_getInheritedRoleNames: function (role) {
const inheritedRoles = new Set()
const nestedRoles = new Set([role])
nestedRoles.forEach(r => {
const roles = Meteor.roles.find({ _id: { $in: r.children.map(r => r._id) } }, { fields: { children: 1 } }).fetch()
roles.forEach(r2 => {
inheritedRoles.add(r2._id)
nestedRoles.add(r2)
})
})
return [...inheritedRoles]
},
/**
* Remove users from assigned roles.
*
* @example
* Roles.removeUsersFromRoles(userId, 'admin')
* Roles.removeUsersFromRoles([userId, user2], ['editor'])
* Roles.removeUsersFromRoles(userId, ['user'], 'group1')
*
* @method removeUsersFromRoles
* @param {Array|String} users User ID(s) or object(s) with an `_id` field.
* @param {Array|String} roles Name(s) of roles to add users to. Roles have to exist.
* @param {Object|String} [options] Options:
* - `scope`: name of the scope, or `null` for the global role
* - `anyScope`: if set, role can be in any scope (`scope` option is ignored)
*
* Alternatively, it can be a scope name string.
* @static
*/
removeUsersFromRoles: function (users, roles, options) {
if (!users) throw new Error('Missing \'users\' param.')
if (!roles) throw new Error('Missing \'roles\' param.')
options = Roles._normalizeOptions(options)
// ensure arrays
if (!Array.isArray(users)) users = [users]
if (!Array.isArray(roles)) roles = [roles]
Roles._checkScopeName(options.scope)
users.forEach(function (user) {
if (!user) return
roles.forEach(function (role) {
let id
if (typeof user === 'object') {
id = user._id
} else {
id = user
}
Roles._removeUserFromRole(id, role, options)
})
})
},
/**
* Remove one user from one role.
*
* @method _removeUserFromRole
* @param {String} userId The user ID.
* @param {String} roleName Name of the role to add the user to. The role have to exist.
* @param {Object} options Options:
* - `scope`: name of the scope, or `null` for the global role
* - `anyScope`: if set, role can be in any scope (`scope` option is ignored)
* @private
* @static
*/
_removeUserFromRole: function (userId, roleName, options) {
Roles._checkRoleName(roleName)
Roles._checkScopeName(options.scope)
if (!userId) return
const selector = {
'user._id': userId,
'role._id': roleName
}
if (!options.anyScope) {
selector.scope = options.scope
}
Meteor.roleAssignment.remove(selector)
},
/**
* Check if user has specified roles.
*
* @example
* // global roles
* Roles.userIsInRole(user, 'admin')
* Roles.userIsInRole(user, ['admin','editor'])
* Roles.userIsInRole(userId, 'admin')
* Roles.userIsInRole(userId, ['admin','editor'])
*
* // scope roles (global roles are still checked)
* Roles.userIsInRole(user, 'admin', 'group1')
* Roles.userIsInRole(userId, ['admin','editor'], 'group1')
* Roles.userIsInRole(userId, ['admin','editor'], {scope: 'group1'})
*
* @method userIsInRole
* @param {String|Object} user User ID or an actual user object.
* @param {Array|String} roles Name of role or an array of roles to check against. If array,
* will return `true` if user is in _any_ role.
* Roles do not have to exist.
* @param {Object|String} [options] Options:
* - `scope`: name of the scope; if supplied, limits check to just that scope
* the user's global roles will always be checked whether scope is specified or not
* - `anyScope`: if set, role can be in any scope (`scope` option is ignored)
*
* Alternatively, it can be a scope name string.
* @return {Boolean} `true` if user is in _any_ of the target roles
* @static
*/
userIsInRole: function (user, roles, options) {
var id
var selector
options = Roles._normalizeOptions(options)
// ensure array to simplify code
if (!Array.isArray(roles)) roles = [roles]
roles = roles.filter(r => r != null)
if (!roles.length) return false
Roles._checkScopeName(options.scope)
options = Object.assign({
anyScope: false
}, options)
if (user && typeof user === 'object') {
id = user._id
} else {
id = user
}
if (!id) return false
selector = {
'user._id': id
}
if (!options.anyScope) {
selector.scope = { $in: [options.scope, null] }
}
return roles.some((roleName) => {
selector['inheritedRoles._id'] = roleName
return Meteor.roleAssignment.find(selector, { limit: 1 }).count() > 0
})
},
/**
* Retrieve user's roles.
*
* @method getRolesForUser
* @param {String|Object} user User ID or an actual user object.
* @param {Object|String} [options] Options:
* - `scope`: name of scope to provide roles for; if not specified, global roles are returned
* - `anyScope`: if set, role can be in any scope (`scope` and `onlyAssigned` options are ignored)
* - `onlyScoped`: if set, only roles in the specified scope are returned
* - `onlyAssigned`: return only assigned roles and not automatically inferred (like subroles)
* - `fullObjects`: return full roles objects (`true`) or just names (`false`) (`onlyAssigned` option is ignored) (default `false`)
* If you have a use-case for this option, please file a feature-request. You shouldn't need to use it as it's
* result strongly dependant on the internal data structure of this plugin.
*
* Alternatively, it can be a scope name string.
* @return {Array} Array of user's roles, unsorted.
* @static
*/
getRolesForUser: function (user, options) {
var id
var selector
var filter
var roles
options = Roles._normalizeOptions(options)
Roles._checkScopeName(options.scope)
options = Object.assign({
fullObjects: false,
onlyAssigned: false,
anyScope: false,
onlyScoped: false
}, options)
if (user && typeof user === 'object') {
id = user._id
} else {
id = user
}
if (!id) return []
selector = {
'user._id': id
}
filter = {
fields: { 'inheritedRoles._id': 1 }
}
if (!options.anyScope) {
selector.scope = { $in: [options.scope] }
if (!options.onlyScoped) {
selector.scope.$in.push(null)
}
}
if (options.onlyAssigned) {
delete filter.fields['inheritedRoles._id']
filter.fields['role._id'] = 1
}
if (options.fullObjects) {
delete filter.fields
}
roles = Meteor.roleAssignment.find(selector, filter).fetch()
if (options.fullObjects) {
return roles
}
return [...new Set(roles.map(r => r.inheritedRoles || [r.role]).reduce((rev, current) => rev.concat(current), []).map(r => r._id))]
},
/**
* Retrieve cursor of all existing roles.
*
* @method getAllRoles
* @param {Object} [queryOptions] Options which are passed directly
* through to `Meteor.roles.find(query, options)`.
* @return {Cursor} Cursor of existing roles.
* @static
*/
getAllRoles: function (queryOptions) {
queryOptions = queryOptions || { sort: { _id: 1 } }
return Meteor.roles.find({}, queryOptions)
},
/**
* Retrieve all users who are in target role.
*
* Options:
*
* @method getUsersInRole
* @param {Array|String} roles Name of role or an array of roles. If array, users
* returned will have at least one of the roles
* specified but need not have _all_ roles.
* Roles do not have to exist.
* @param {Object|String} [options] Options:
* - `scope`: name of the scope to restrict roles to; user's global
* roles will also be checked
* - `anyScope`: if set, role can be in any scope (`scope` option is ignored)
* - `onlyScoped`: if set, only roles in the specified scope are returned
* - `queryOptions`: options which are passed directly
* through to `Meteor.users.find(query, options)`
*
* Alternatively, it can be a scope name string.
* @param {Object} [queryOptions] Options which are passed directly
* through to `Meteor.users.find(query, options)`
* @return {Cursor} Cursor of users in roles.
* @static
*/
getUsersInRole: function (roles, options, queryOptions) {
var ids
ids = Roles.getUserAssignmentsForRole(roles, options).fetch().map(a => a.user._id)
return Meteor.users.find({ _id: { $in: ids } }, ((options && options.queryOptions) || queryOptions) || {})
},
/**
* Retrieve all assignments of a user which are for the target role.
*
* Options:
*
* @method getUserAssignmentsForRole
* @param {Array|String} roles Name of role or an array of roles. If array, users
* returned will have at least one of the roles
* specified but need not have _all_ roles.
* Roles do not have to exist.
* @param {Object|String} [options] Options:
* - `scope`: name of the scope to restrict roles to; user's global
* roles will also be checked
* - `anyScope`: if set, role can be in any scope (`scope` option is ignored)
* - `queryOptions`: options which are passed directly
* through to `Meteor.roleAssignment.find(query, options)`
* Alternatively, it can be a scope name string.
* @return {Cursor} Cursor of user assignments for roles.
* @static
*/
getUserAssignmentsForRole: function (roles, options) {
options = Roles._normalizeOptions(options)
options = Object.assign({
anyScope: false,
queryOptions: {}
}, options)
return Roles._getUsersInRoleCursor(roles, options, options.queryOptions)
},
/**
* @method _getUsersInRoleCursor
* @param {Array|String} roles Name of role or an array of roles. If array, ids of users are
* returned which have at least one of the roles
* assigned but need not have _all_ roles.
* Roles do not have to exist.
* @param {Object|String} [options] Options:
* - `scope`: name of the scope to restrict roles to; user's global
* roles will also be checked
* - `anyScope`: if set, role can be in any scope (`scope` option is ignored)
*
* Alternatively, it can be a scope name string.
* @param {Object} [filter] Options which are passed directly
* through to `Meteor.roleAssignment.find(query, options)`
* @return {Object} Cursor to the assignment documents
* @private
* @static
*/
_getUsersInRoleCursor: function (roles, options, filter) {
var selector
options = Roles._normalizeOptions(options)
options = Object.assign({
anyScope: false,
onlyScoped: false
}, options)
// ensure array to simplify code
if (!Array.isArray(roles)) roles = [roles]
Roles._checkScopeName(options.scope)
filter = Object.assign({
fields: { 'user._id': 1 }
}, filter)
selector = {
'inheritedRoles._id': { $in: roles }
}
if (!options.anyScope) {
selector.scope = { $in: [options.scope] }
if (!options.onlyScoped) {
selector.scope.$in.push(null)
}
}
return Meteor.roleAssignment.find(selector, filter)
},
/**
* Deprecated. Use `getScopesForUser` instead.
*
* @method getGroupsForUser
* @static
* @deprecated
*/
getGroupsForUser: function (...args) {
if (!getGroupsForUserDeprecationWarning) {
getGroupsForUserDeprecationWarning = true
console && console.warn('getGroupsForUser has been deprecated. Use getScopesForUser instead.')
}
return Roles.getScopesForUser(...args)
},
/**
* Retrieve users scopes, if any.
*
* @method getScopesForUser
* @param {String|Object} user User ID or an actual user object.
* @param {Array|String} [roles] Name of roles to restrict scopes to.
*
* @return {Array} Array of user's scopes, unsorted.
* @static
*/
getScopesForUser: function (user, roles) {
var scopes
var id
if (roles && !Array.isArray(roles)) roles = [roles]
if (user && typeof user === 'object') {
id = user._id
} else {
id = user
}
if (!id) return []
const selector = {
'user._id': id,
scope: { $ne: null }
}
if (roles) {
selector['inheritedRoles._id'] = { $in: roles }
}
scopes = Meteor.roleAssignment.find(selector, { fields: { scope: 1 } }).fetch().map(obi => obi.scope)
return [...new Set(scopes)]
},
/**
* Rename a scope.
*
* Roles assigned with a given scope are changed to be under the new scope.
*
* @method renameScope
* @param {String} oldName Old name of a scope.
* @param {String} newName New name of a scope.
* @static
*/
renameScope: function (oldName, newName) {
var count
Roles._checkScopeName(oldName)
Roles._checkScopeName(newName)
if (oldName === newName) return
do {
count = Meteor.roleAssignment.update({
scope: oldName
}, {
$set: {
scope: newName
}
}, { multi: true })
} while (count > 0)
},
/**
* Remove a scope.
*
* Roles assigned with a given scope are removed.