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

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.

2 Likes