Invite flow error => User already exists { one connection, one application, multiple organisations }

I came up with a solution that works for us but I’m not 100% sure if this is the best solution.

Please note, this example does NOT send an email.

/**
 * Invite a user to join an organization. Not as simple as it sounds since
 * there are two use cases that must be handled.
 * * user does not belong to tenant, create an invitation asking them to sign up
 * * user belongs to tenant, simply add to organization
 * For security reasons, the organization administrators will not be allowed
 * to see tenant users.
 * @param clientId application client id
 * @param auth0OrganizationId auth0 organization id (eg: org_D0GiHe44ef4AWgC31)
 * @param email user email
 * @param roles array of auth0 roles id (eg: rol_xP45Cd9KJ6D7Ef)
 * @returns an invitation to login to organization or sign up to tenant
 */
const createInvitation = async (clientId, auth0OrganizationId, email, roles) => {
  const organization = await getOrganization(auth0OrganizationId)
  const management = await getManagementAPI()
  const members = await management.getUsersByEmail(email)
  if (members.length) {
    // if user is already signed up to tenant, add member to organization
    const response = await management
      .organizations
      .addMembers({ id: auth0OrganizationId }, { members: members.map(member => member.user_id) })
    console.log('addMembers', response)
    const client = await management.getClient({ client_id: clientId })
    return {
      inviter: {
        name: organization.display_name
      },
      invitee: {
        email: email
      },
      invitation_url: client.web_origins,
      organization_id: auth0OrganizationId
    }
  } else {
    // invite user to sign up to tenant
    const data = {
      client_id: clientId,
      inviter: {
        name: organization.display_name
      },
      invitee: {
        email: email
      },
      roles: roles,
      ttl_sec: 604800,
      send_invitation_email: false
    }
    const response = await management
      .organizations
      .createInvitation({ id: auth0OrganizationId }, data)
    return response
  }
}
1 Like