Add tests for isInRole and getRoles

This commit is contained in:
Raymond Feng 2013-11-12 10:47:59 -08:00
parent c3a1a85159
commit 0430cd2ae3
2 changed files with 56 additions and 4 deletions

View File

@ -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);
});
});
};

View File

@ -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);
});
});
});
});
});
});