How do I add a default role to a new user on first login?

Question: How do I assign a default role to a new user on first login?

Answer:
If you are using the Authorization Core, you can leverage the Management API in a rule to assign a role based on login count.

Example Rule:

function (user, context, callback) {
  	const ManagementClient = require('auth0@2.27.0').ManagementClient;

    const management = new ManagementClient({
      token: auth0.accessToken,
      domain: auth0.domain
    });
  
  	console.log(auth0.accessToken);
    const count = context.stats && context.stats.loginsCount ? context.stats.loginsCount : 0;
    if (count > 1) {
        return callback(null, user, context);
    }

    const params =  { id : user.user_id};
    const data = { "roles" : ["ROLE_ID_1","ROLE_ID_2"]};

    management.users.assignRoles(params, data, function (err, user) {
      if (err) {
        // Handle error.
        console.log(err);
      }
		console.log("success");
    callback(null, user, context);
    });
    
}

Note: We are using node-auth0 2.27.0, the latest version available in rules. Make sure to check what Node.js modules are available in rules.

Supporting Documentation:


https://auth0.com/docs/api/management/v2#!/Users/post_user_roles
3 Likes