Skip to content

Commit

Permalink
Merge pull request #2975 from ebarault/getRoles-to-return-only-role-n…
Browse files Browse the repository at this point in the history
…ames

Add "returnOnlyRoleNames" option to Role.getRoles
  • Loading branch information
bajtos authored Nov 30, 2016
2 parents 3ecb5e1 + b0d6c4a commit ca3ec13
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
22 changes: 18 additions & 4 deletions common/models/role.js
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,12 @@ module.exports = function(Role) {
* @param {Error} err Error object.
* @param {String[]} roles An array of role IDs
*/
Role.getRoles = function(context, callback) {
Role.getRoles = function(context, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}

if (!(context instanceof AccessContext)) {
context = new AccessContext(context);
}
Expand Down Expand Up @@ -418,15 +423,24 @@ module.exports = function(Role) {
if (principalType && principalId) {
// Please find() treat undefined matches all values
inRoleTasks.push(function(done) {
roleMappingModel.find({where: {principalType: principalType,
principalId: principalId}}, function(err, mappings) {
var filter = {where: {principalType: principalType, principalId: principalId}};
if (options.returnOnlyRoleNames === true) {
filter.include = ['role'];
}
roleMappingModel.find(filter, function(err, mappings) {
debug('Role mappings found: %s %j', err, mappings);
if (err) {
if (done) done(err);
return;
}
mappings.forEach(function(m) {
addRole(m.roleId);
var role;
if (options.returnOnlyRoleNames === true) {
role = m.toJSON().role.name;
} else {
role = m.roleId;
}
addRole(role);
});
if (done) done();
});
Expand Down
14 changes: 14 additions & 0 deletions test/role.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,20 @@ describe('role model', function() {
next();
});
},
function(next) {
Role.getRoles(
{principalType: RoleMapping.USER, principalId: user.id},
{returnOnlyRoleNames: true},
function(err, roles) {
if (err) return next(err);
expect(roles).to.eql([
Role.AUTHENTICATED,
Role.EVERYONE,
role.name,
]);
next();
});
},
function(next) {
Role.getRoles(
{principalType: RoleMapping.APP, principalId: user.id},
Expand Down

0 comments on commit ca3ec13

Please sign in to comment.