Auth0 Home Blog Docs

How to add user role to a user during their login

rules
app_metadata
metadata
roles

#1

I want to separate my customers depending on user role and so far I have been using “Rules” feature of Auth0 to set roles to a user. And it worked fine. However this requires me to add user emails manually in to this rule every time someone signs up as shown below:

function (user, context, callback) {
  user.app_metadata = user.app_metadata || {};
  // You can add a Role based on what you want
  // In this case I check domain
  var addRolesToUser = function(user, cb) {
    if (user.email.indexOf('some_email@hotmail.com') > -1 || user.email.indexOf('some_other_email@gmail.com') > -1) {
      cb(null, 'teacher']);
    } else {
      cb(null, 'student']);
    }
  };

  addRolesToUser(user, function(err, roles) {
    if (err) {
      callback(err);
    } else {
      user.app_metadata.roles = roles;
      auth0.users.updateAppMetadata(user.user_id, user.app_metadata)
        .then(function(){
          callback(null, user, context);
        })
        .catch(function(err){
          callback(err);
        });
    }
  });
}

As you can see for every user I am changing the rule manually to add them to a specific role.

I am looking for a way to send/assign this value during the call I make to Auth0 when customer logs in. I will check the user type in my database and depending on that check I want to send app_metadata to assign their role without needing the “Rules” feature.

Any help is appreciated. Thanks!


How to send http request from Rules sections
#2

The recommended way would be for you to maintain the role assignment in a rule, but update the rule to dynamically query this information from your database so that you don’t have to update the rule for each new user.

Instead of checking the user email, the rule would make an external request to your own system passing the user information of the user that is logging in. Your system would return the role information and the remaining rule logic would associate that role to the user.

The overall idea would be to implement something very similar to the following rule template: https://github.com/auth0/rules/blob/master/rules/add-roles-from-sqlserver.md


#3