My rule only give a role on the second login

Every user that I add should get default role, but with the rule that I use the role get added after the first login.

    function (user, context, callback) {

  var count = context.stats && context.stats.loginsCount ? context.stats.loginsCount : 0;
  if (count > 1) {
    return callback(null, user, context);

  var ManagementClient = require('auth0@2.17.0').ManagementClient;
  var management = new ManagementClient({
    token: auth0.accessToken,
    domain: auth0.domain

    { id : user.user_id}, 
    { "roles" :["rol_Vo2nS9uui32JbQ66"]},  // sample role ID of "Standard API Enduser"
    function (err) {
      if (err) {
        console.log('Error assigning role: ' + err);
      callback(null, user, context);

Is there a rule that adds user roles on creation rather than on first login?

Hi @AbdurrahmanDundar and welcome to the Auth0 Community!
I’m spotting two callbacks in your rule and both are conditional–thus, it only happens on certain conditions. I suggest putting callbacks outside conditional sentences–a better context understanding is required to make sure but that’s probably why you get the rule effectively executed in the second login attempt.
Best regards,

Jorge Nicolau

1 Like

Hello @AbdurrahmanDundar,

Just to clarify as well, are you manually adding users, or are users signing up on your app themselves? Rules run after successful authentication, so I was wondering if the role is not being assigned because users are being added manually and have not logged in yet.

If you are manually adding users to a database connection, then you may want to use a Post User Registration Hook. This hook runs after users are created for a database connection (so it will not run after someone logs in with a social connection, but it will run if a user is manually created). Let me know if you’d like more details about how to set that up if that is the case!

I changed it so that I don’t use a rule, but just use the management api to add a role to the newly added user.

Thanks for reply!


This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.