Skip to content

Commit

Permalink
Merge pull request #294 from Meteor-Community-Packages/setUserRoles-a…
Browse files Browse the repository at this point in the history
…nyScope

Allow setUserRoles() to replace the roles of all scopes
  • Loading branch information
SimonSimCity authored Nov 14, 2019
2 parents d916aeb + ad88577 commit 1f17f56
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
11 changes: 9 additions & 2 deletions roles/roles_common.js
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@ Object.assign(Roles, {
* @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.
Expand All @@ -421,7 +422,8 @@ Object.assign(Roles, {
Roles._checkScopeName(options.scope)

options = Object.assign({
ifExists: false
ifExists: false,
anyScope: false
}, options)

users.forEach(function (user) {
Expand All @@ -431,7 +433,12 @@ Object.assign(Roles, {
id = user
}
// we first clear all roles for the user
Meteor.roleAssignment.remove({ 'user._id': id, scope: options.scope })
const selector = { 'user._id': id }
if (!options.anyScope) {
selector.scope = options.scope
}

Meteor.roleAssignment.remove(selector)

// and then add all
roles.forEach(function (role) {
Expand Down
27 changes: 27 additions & 0 deletions roles/tests/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,33 @@ describe('roles', function () {
testUser('eve', ['editor'])
})

it('can set user roles by scope and anyScope', function () {
Roles.createRole('admin')
Roles.createRole('editor')

var eve = Meteor.users.findOne({ _id: users.eve })

assert.sameDeepMembers(Roles.getRolesForUser(users.eve, { anyScope: true, fullObjects: true }).map(obj => { delete obj._id; return obj }), [])

Roles.addUsersToRoles(eve, 'admin')

assert.sameDeepMembers(Roles.getRolesForUser(users.eve, { anyScope: true, fullObjects: true }).map(obj => { delete obj._id; return obj }), [{
role: { _id: 'admin' },
scope: null,
user: { _id: users.eve },
inheritedRoles: [{ _id: 'admin' }]
}])

Roles.setUserRoles(eve, 'editor', { anyScope: true, scope: 'scope2' })

assert.sameDeepMembers(Roles.getRolesForUser(users.eve, { anyScope: true, fullObjects: true }).map(obj => { delete obj._id; return obj }), [{
role: { _id: 'editor' },
scope: 'scope2',
user: { _id: users.eve },
inheritedRoles: [{ _id: 'editor' }]
}])
})

it('can get all roles', function () {
roles.forEach(function (role) {
Roles.createRole(role)
Expand Down

0 comments on commit 1f17f56

Please sign in to comment.