Adding role to new user with email domain IF email is verified

Hi folks,

I’d like to add a default employee role to users with a given email domain whenever they register in my Auth0 tenant via my SPA. I believe I’d want to only grant the role once the email has been verified on the account however.

I’m familiar with and have seen various posts articles on both how to check for email verification when a user is logging in, and granting a role to a user post-registration based on their email.

The issue I see with this is that presumably I cannot check for email verification before adding the user role in the post-registration action - because the user would not have had time to receive and click on the verification link.

With that in mind, where (if anywhere) within the Auth0 flows would I be able to add a user role while being able to sensibly check for email verification in this way? I thought there might be a hook/flow/etc. that occurred post-email-verification, but haven’t seen anything.

Thanks,
EML

Hi @EML,

Welcome to the Auth0 Community!

I understand that you would like to add a role to a new user with a specific email domain provided that their email has been verified.

In this situation, I recommend using a Post-Login Action script to add a role to the user only if their email has been verified and matches a specific domain.

Because we are using a Post-Login Action script and would like to only assign the user role once, we should include a user_metdata check for a single execution. Here is an example:

exports.onExecutePostLogin = async (event, api) => {
  if (!event.user.email_verified || !event.user.email.endsWith("@example.com")){
      api.access.deny(`Access to ${event.client.name} is not allowed.`);
   }
  
  if(!event.user.user_metadata.assignedRole){
    const ManagementClient = require('auth0').ManagementClient;

    const management = new ManagementClient({
        domain: event.secrets.domain,
        clientId: event.secrets.clientId,
        clientSecret: event.secrets.clientSecret,
    });

    const params =  { id : event.user.user_id};
    const data = { "roles" : ["ROLE_ID"]};
    
    try {
        const res = await management.assignRolestoUser(params, data)
        api.user.setUserMetadata("assignedRole", true)
    } catch (e) {
        console.log(e)
        // Handle error
    }
  }
};

Here are some helpful resources you may find relevant:

I hope this helps!

Please let me know how this works for you or if you have any additional questions.

Thank you.

1 Like

Thanks very much @rueben.tiow - good idea, I believe that should work for us :+1:

1 Like