Skip to content

Commit a4a96eb

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 c0e96ff commit a4a96eb

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
@@ -383,7 +383,12 @@ module.exports = function(Role) {
383383
* @param {Error} err Error object.
384384
* @param {String[]} roles An array of role IDs
385385
*/
386-
Role.getRoles = function(context, callback) {
386+
Role.getRoles = function(context, options, callback) {
387+
if (!callback && typeof options === 'function') {
388+
callback = options;
389+
options = {};
390+
}
391+
387392
if (!(context instanceof AccessContext)) {
388393
context = new AccessContext(context);
389394
}
@@ -433,15 +438,24 @@ module.exports = function(Role) {
433438
if (principalType && principalId) {
434439
// Please find() treat undefined matches all values
435440
inRoleTasks.push(function(done) {
436-
roleMappingModel.find({where: {principalType: principalType,
437-
principalId: principalId}}, function(err, mappings) {
441+
var filter = {where: {principalType: principalType, principalId: principalId}};
442+
if (options.returnOnlyRoleNames === true) {
443+
filter.include = ['role'];
444+
}
445+
roleMappingModel.find(filter, function(err, mappings) {
438446
debug('Role mappings found: %s %j', err, mappings);
439447
if (err) {
440448
if (done) done(err);
441449
return;
442450
}
443451
mappings.forEach(function(m) {
444-
addRole(m.roleId);
452+
var role;
453+
if (options.returnOnlyRoleNames === true) {
454+
role = m.toJSON().role.name;
455+
} else {
456+
role = m.roleId;
457+
}
458+
addRole(role);
445459
});
446460
if (done) done();
447461
});

test/role.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,20 @@ describe('role model', function() {
249249
next();
250250
});
251251
},
252+
function(next) {
253+
Role.getRoles(
254+
{ principalType: RoleMapping.USER, principalId: user.id },
255+
{ returnOnlyRoleNames: true },
256+
function(err, roles) {
257+
if (err) return next(err);
258+
expect(roles).to.eql([
259+
Role.AUTHENTICATED,
260+
Role.EVERYONE,
261+
role.name,
262+
]);
263+
next();
264+
});
265+
},
252266
function(next) {
253267
Role.getRoles(
254268
{ principalType: RoleMapping.APP, principalId: user.id },

0 commit comments

Comments
 (0)