I have been studying the loopback / Strongloop documentation and it is not clear to me that it is possible to dynamically add a new user to a role (i.e. add a user to role via r
You can create rolemappings for users in strongloop with something like this -
Role.find({where: {name: roleName}}, function(err, role) {
if (err) {return console.log(err);}
RoleMapping.create({
principalType: "USER",
principalId: userId,
roleId: role.id
}, function(err, roleMapping) {
if (err) {return console.log(err);}
console.log('User assigned RoleID ' + role.id + ' (' + ctx.instance.type + ')');
}):
});
Now you have to execute this code either in the after save
operation hook or if you have defined any remote method for creating a user you will have to look for a after remote hook and do this because you would need the id
of the user which would be available only after user is saved in database
If you are using some operation hooks then it would be something like this -
user.observe('after save', function function_name(ctx, next) {
if (ctx.instance) {
if(ctx.isNewInstance) {
// look up role based on type
//
Role.find({where: {name: 'role-name'}}, function(err, role) {
if (err) {return console.log(err);}
RoleMapping.create({
principalType: "USER",
principalId: ctx.instance.id,
roleId: role.id
}, function(err, roleMapping) {
if (err) {return console.log(err);}
console.log('User assigned RoleID ' + role.id + ' (' + ctx.instance.type + ')');
}):
});
}
}
next();
});