Dynamically adding user to a loopback Role

前端 未结 1 1903
[愿得一人]
[愿得一人] 2021-02-11 07:43

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

相关标签:
1条回答
  • 2021-02-11 07:58

    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();
    });
    
    0 讨论(0)
提交回复
热议问题