Hi @cbafo,
Thanks for reaching out to the Auth0 Community!
I understand that you’ve been stuck with trying to get your Auth0 Rule to assign a role only if the user did not previously log in (login count = 0) and on sign up.
Unfortunately, you will encounter the issue which you observed, where users that have never logged in with assigned Roles, on the first login will trigger your Rule.
To work around this issue, you could implement a logic that looks at whether the user has a role previously assigned. If it’s not true, then you can assign them a default role.
Something like the following:
function (user, context, callback) {
if(context.authorization.roles){
return callback(null, user, context); // Do nothing, pass
}else{
var ManagementClient = require(‘auth0@2.17.0’).ManagementClient;
var management = new ManagementClient({
token: auth0.accessToken,
domain: auth0.domain
});
management.assignRolestoUser(
{ id : user.user_id},
{ “roles” :[“role_id”]}, // sample role ID of “Standard API Enduser”
function (err) {
if (err) {
console.log('Error assigning role: '+ err);
}
callback(null, user, context);
});
let assignedRoles = (context.authorization || {}).roles;
assignedRoles.push(‘role_id’);
context.authorization.roles.push(‘Basis’);
}
}
You may find our Context Object Properties in Rules docs useful.
Please let me know how this works for you.
Thank you.