Ed_
Ed_

Reputation: 378

Loopback 3 create user and assign a role

I created a model that extends User, and overriding the create method because I need extra logic (in server/models/person.js). I am creating the users without issues, and already registered two roles through the API (named 'user' and 'admin'). What I need is to assign the new users to one of the roles ('user'). How can I do it?

Person.upsert(obj, function(err, u1) {
  if (err != null) {
    console.log('Error: ', err);
    callback({code: 401, message: err});
  } else {
    obj.createAccessToken(2629746000, function(err, token) {
      if (err) {
        callback(err, null);
      } else {
        obj.token = token;
        callback(null, obj);
      }
    });
  }
});

Thanks

Upvotes: 0

Views: 800

Answers (2)

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

Fetch Role instance and assign role to person like this :

role.principals.create({
                    principalType: RoleMapping.ACCOUNT,
                    principalId: person.id
                });

Upvotes: 1

Ed_
Ed_

Reputation: 378

I found a way, I created the relation between Person and RoleMapping:

"relations": {
"roles": {
  "type": "hasMany",
  "model": "RoleMapping",
  "foreignKey": "principalId",
  "options": {
    "disableInclude": true
  }
}

Now I can call the RoleMapping model through the relation:

Person.upsert(obj, function(err, u1) {
  if (err != null) {
    console.log('Error: ', err);
    callback({code: 401, message: err});
  } else {
    obj.roles.create({principalType: obj.roles.ROLE, roleId: 'admin'},
      function() {
        obj.createAccessToken(2629746000, function(err, token) {
          if (err) {
            callback(err, null);
          } else {
            obj.token = token;
            callback(null, obj);
          }
        });
      });
  }
});

Is this ok?

Upvotes: 0

Related Questions