Prevent user creation (with hook?) if user is not whitelisted with rule

Oh, I see the Google mention now! :upside_down_face:

Yes, only rules will cover all connections.

Usually, you’d just throw an authorization error like you’ve already mentioned. The user would be created, though. Here’s how you could delete the user:

  1. Create a M2M application:

  1. Authorize it to use the Managment API and allow it to use the delete:users scope:

  2. Add the M2M app’s client ID and client Secret as secret values to use in the rule:

  3. Create the rule (this is allowing certain domains, but you can adjust the userHasAccess criteria for emails):

async function emailDomainWhitelist(user, context, callback) {
  const axios = require('axios@0.19.2');

  const whitelist = ['example.com', 'example.org']; //authorized domains
  const userHasAccess = whitelist.some(
      function (domain) {
        const emailSplit = user.email.split('@');
        return emailSplit[emailSplit.length - 1].toLowerCase() === domain;
      }
  );

  if (userHasAccess) {
    return callback(null, user, context);
  }

  const options = {
    method: 'POST',
    url: `https://${auth0.domain}/oauth/token`,
    headers: {
      'content-type': 'application/json'
    },
    data: {
      "client_id": configuration.DELETE_USERS_CLIENT_ID,
      "client_secret": configuration.DELETE_USERS_CLIENT_SECRET,
      "audience": `https://${auth0.domain}/api/v2/`,
      "grant_type":"client_credentials"
    }
  };

  try {
    const tokenResponse = await axios(options);
    const accessToken = tokenResponse.data.access_token;
    const userId = encodeURIComponent(user.user_id);
    const deleteUserOptions = {
      method: 'DELETE',
      url: `https://${auth0.domain}/api/v2/users/${userId}`,
      headers: { Authorization: `Bearer ${accessToken}` }
    };
    await axios(deleteUserOptions);
    return callback(new UnauthorizedError('Access denied.'));
  } catch (err) {
    // handle error
    console.log(err);
    return callback(new UnauthorizedError('Access denied.'));
  }
}