Dynamically adding user to a loopback Role

拥有回忆 提交于 2019-12-09 07:14:25

问题


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 role-mapping), that is, without the need to restart the API.

Can anyone confirm one way or the other? (ideally, but not necessarily, pointing me to some documentation or example to confirm or not that this is doable).

Thanks much.


回答1:


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


来源:https://stackoverflow.com/questions/34845480/dynamically-adding-user-to-a-loopback-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!