diff --git a/lib/models/role.js b/lib/models/role.js index 4e1d7aa7..c9a7be37 100644 --- a/lib/models/role.js +++ b/lib/models/role.js @@ -140,18 +140,29 @@ Role.EVERYONE = "$everyone"; // everyone /** * Check if a given principal is in the role * + * @param role * @param principalType * @param principalId - * @param role * @param callback */ -Role.isInRole = function (principalType, principalId, role, callback) { - Role.findOne({where: {name: role}}, function (err, role) { +Role.isInRole = function (role, principalType, principalId, callback) { + Role.findOne({where: {name: role}}, function (err, result) { if (err) { callback && callback(err); return; } - RoleMapping.exists({where: {roleId: role.id, principalType: principalType, principalId: principalId}}, callback); + if(!result) { + callback && callback(null, false); + return; + } + RoleMapping.findOne({where: {roleId: result.id, principalType: principalType, principalId: principalId}}, + function (err, result) { + if (err) { + callback && callback(err); + return; + } + callback && callback(null, !!result); + }); }); }; diff --git a/test/role.test.js b/test/role.test.js index f94c0cce..acd561d9 100644 --- a/test/role.test.js +++ b/test/role.test.js @@ -74,6 +74,47 @@ describe('role model', function () { }); + it("should support getRoles() and isInRole()", function () { + var ds = loopback.createDataSource({connector: 'memory'}); + User.attachTo(ds); + Role.attachTo(ds); + RoleMapping.attachTo(ds); + + User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function (err, user) { + // console.log('User: ', user.id); + Role.create({name: 'userRole'}, function (err, role) { + role.principals.create({principalType: RoleMapping.USER, principalId: user.id}, function (err, p) { + // Role.find(console.log); + // role.principals(console.log); + Role.isInRole('userRole', RoleMapping.USER, user.id, function(err, exists) { + assert(!err && exists === true); + }); + + Role.isInRole('userRole', RoleMapping.APP, user.id, function(err, exists) { + assert(!err && exists === false); + }); + + Role.isInRole('userRole', RoleMapping.USER, 100, function(err, exists) { + assert(!err && exists === false); + }); + + Role.getRoles(RoleMapping.USER, user.id, function(err, roles) { + assert.equal(roles.length, 1); + assert.equal(roles[0], role.id); + }); + Role.getRoles(RoleMapping.APP, user.id, function(err, roles) { + assert.equal(roles.length, 0); + }); + Role.getRoles(RoleMapping.USER, 100, function(err, roles) { + assert.equal(roles.length, 0); + }); + + }); + }); + }); + + }); + });