动态将用户添加到回送角色 [英] Dynamically adding user to a loopback Role

查看:46
本文介绍了动态将用户添加到回送角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究回送/Strongloop文档,但我不清楚是否可以动态地向角色添加新用户(即,通过角色映射向角色添加用户),也就是说,无需需要重新启动API.

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).

非常感谢.

推荐答案

您可以使用以下方法为Strongloop中的用户创建角色映射-

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 + ')');

        }):

      });

现在,您必须在after save操作挂钩中执行此代码,或者如果您已定义了用于创建用户的任何远程方法,则您将必须查找之后的远程挂钩,并执行此操作,因为您需要仅在用户保存在数据库中后才能使用

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

这篇关于动态将用户添加到回送角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆