Check if User has Exiting Roles

I need to check if a user has existing roles.

My Current Rule adds a role “new” if the users login count < 2. I need to extend this to check if the user has been assigned any roles that where created with the management API.

function (user, context, callback) {
user.app_metadata = user.app_metadata || {};
      if (context.stats.loginsCount < 2)
    {
  // You can add a Role based on what you want
  // In this case I check domain
  var addRolesToUser = function(user, cb) {

       cb(null, 'new']);
    };
  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(){
          context.idToken'https://syntrack.net/roles'] = user.app_metadata.roles;
          callback(null, user, context);
        })
        .catch(function(err){
          callback(err);
        });
    }
  });
}
   callback(null, user, context);
    }

So would something like this work?

  if (context.stats.loginsCount < 2)
    { 
        if(user.app_metadata.roles === undefined)
       {
             //add the [new] role
       }
   }
callback(null, user, context);

It depends; the recommended implementation would require knowing all the exact details.

For example, assuming that:

  • an end-user may or may not have roles defined in app_metadata.roles and if they have then it’s an array of roles.
  • you want to augment those roles in rules with other roles, but these other roles don’t need to be persisted to metadata as they are only relevant in responses that go through rules.

Then the following simplified rule could do the trick:

function (user, context, callback) {
  var roles = user.app_metadata.roles || ];

  if (context.stats.loginsCount < 2) { roles.push("new"); }

  // do other stuf that can add roles

  // add roles to the response (ID token or access token; assuming OIDC/OAuth2)
  
  callback(null, user, context);
}

@jmangelo How would I go about checking if the user does not have existing roles and Login count < 2?

if (context.stats.loginsCount < 2 && roles.length === 0) { roles.push("new"); }

Would that work?

Assuming the sample rule in the answer with the roles = user.app_metadata.roles || ] logic then your suggested change should work, because complete lack of roles (never assigned) or empty roles would always result in an empty array which would satisfy the roles.length === 0 check you added.

@jmangelo You SIR are a scholar and a gentleman!