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

Problem statement

You might need users to be created with a specific role.

Solution

Check out our vide related to that topic:

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 count = context.stats && context.stats.loginsCount ? context.stats.loginsCount : 0;
    if (count > 1) {
        return callback(null, user, context);
    }

    const ManagementClient = require('auth0@2.27.0').ManagementClient;
    const management = new ManagementClient({
      token: auth0.accessToken,
      domain: auth0.domain
    });

    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);
     }
    callback(null, user, context);
    });
    
}
1 Like