Assign role on login with Google SSO for specific domain

hi,

I am trying to create an action that will assign a role the first time a user logs in using google sso using a specific domain. I believe when users do this the first time, it creates an account for them. I tried the instructions here: Adding role to new user with email domain IF email is verified but have not been able to get it to work. My code is below. Should this work with google sso?

/**
* Handler that will be called during the execution of a PostUserRegistration flow.
*
* @param {Event} event - Details about the context and user that has registered.
* @param {PostUserRegistrationAPI} api - Methods and utilities to help change the behavior after a signup.
*/
exports.onExecutePostUserRegistration = async (event, api) => {
  if (!event.user.email.endsWith("@example.org")) {
    return;
  }
  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" : ["rol_LCLMxxxx20BC4990"]};

  try {
    const res = await management.assignRolestoUser(params, data)
  } catch (e) {
    console.log(e)
    return; // Handle error
  }
};

Hi @dolphin512

The code below won’t trigger as the Post User Registration will trigger only for Database and passwordless connection types. You will need to use Post-Login action and activate it conditionally.

https://auth0.com/docs/customize/actions/flows-and-triggers/login-flow

Can you share details of what wasn’t working while implementing this with Post-Login flow?

Thanks
Dawid

I tried and just re-tried adding this code to the login flow. It doesn’t assign the role when I login with google sso using an email with this domain.

exports.onExecutePostLogin = async (event, api) => {
  if (event.user.email.endsWith("@mydomain.org")){
    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" : ["rol_LCLMmQbXXX"]};
    
    try {
        const res = await management.assignRolestoUser(params, data)
        api.user.setUserMetadata("assignedRole", true)
    } catch (e) {
        console.log(e)
        // Handle error
    }
   }
};

I also tried testing it in the “create actions” section and when I remove the check for the email domain i.e. would presumably assign role to every user with any email address when logging in, I get this error:

“TypeError: management.assignRolestoUser is not a function”

Am sure I am doing something stupid. Any help appreciated!