Skip to content

Commit b0d6c4a

Browse files
ebaraultbajtos
authored andcommitted
Add "returnOnlyRoleNames" option to Role.getRoles
Currently the return type of Role.getRoles() method is inconsistent: role names are returned for smart roles and role ids are returned for static roles (configured through user-role mapping). This commit adds a new option to Role.getRoles() allowing the caller to request role names to be returned for all types of roles.
1 parent 3ecb5e1 commit b0d6c4a

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

common/models/role.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,12 @@ module.exports = function(Role) {
368368
* @param {Error} err Error object.
369369
* @param {String[]} roles An array of role IDs
370370
*/
371-
Role.getRoles = function(context, callback) {
371+
Role.getRoles = function(context, options, callback) {
372+
if (!callback && typeof options === 'function') {
373+
callback = options;
374+
options = {};
375+
}
376+
372377
if (!(context instanceof AccessContext)) {
373378
context = new AccessContext(context);
374379
}
@@ -418,15 +423,24 @@ module.exports = function(Role) {
418423
if (principalType && principalId) {
419424
// Please find() treat undefined matches all values
420425
inRoleTasks.push(function(done) {
421-
roleMappingModel.find({where: {principalType: principalType,
422-
principalId: principalId}}, function(err, mappings) {
426+
var filter = {where: {principalType: principalType, principalId: principalId}};
427+
if (options.returnOnlyRoleNames === true) {
428+
filter.include = ['role'];
429+
}
430+
roleMappingModel.find(filter, function(err, mappings) {
423431
debug('Role mappings found: %s %j', err, mappings);
424432
if (err) {
425433
if (done) done(err);
426434
return;
427435
}
428436
mappings.forEach(function(m) {
429-
addRole(m.roleId);
437+
var role;
438+
if (options.returnOnlyRoleNames === true) {
439+
role = m.toJSON().role.name;
440+
} else {
441+
role = m.roleId;
442+
}
443+
addRole(role);
430444
});
431445
if (done) done();
432446
});

test/role.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,20 @@ describe('role model', function() {
252252
next();
253253
});
254254
},
255+
function(next) {
256+
Role.getRoles(
257+
{principalType: RoleMapping.USER, principalId: user.id},
258+
{returnOnlyRoleNames: true},
259+
function(err, roles) {
260+
if (err) return next(err);
261+
expect(roles).to.eql([
262+
Role.AUTHENTICATED,
263+
Role.EVERYONE,
264+
role.name,
265+
]);
266+
next();
267+
});
268+
},
255269
function(next) {
256270
Role.getRoles(
257271
{principalType: RoleMapping.APP, principalId: user.id},

0 commit comments

Comments
 (0)