I have a Problem in login process: I have implemented a rule which assignes a default role to all users which sign up, like the following rule:
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
});
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’);
}
But this creates the problem, that when i create new users in the auth0 dashboard and already assign them a role, they will also be assigned the default role, because the login count is 0.
Can anyone help me to rewrite the role, that if the user has already an assigend role, but login counts 0, the user will not be assigned the default role?
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’);
}
}
Thank you so much for adressing my problem so fast, the part where the user gets no role assigend if i already assinged one in the dashboard seems to be working fine, but if the user does a selfregistration, he will not get assigend a role.
How can i implement it all in the same rule?
Thanks for looking into in again