Enforce Email Verification by Sending the Email Verification after Each Denied Access

Overview

This article details how email verification can be implemented to prevent users from going further after registration and from signing in. Can a user-friendly message be displayed to explain the reason, and an email verification be sent right at that moment to avoid asking the user to scroll down in his emails to find it?

Applies To

  • Enforce Email Verification
  • Denied Access

Solution

There is no out-of-the-box way to prevent the creation of a user profile until an email is verified, but a custom action that forces users to verify their email when logging in can be implemented. This will provide a way to block bot-like activity on the platform and add another layer of security.

Attached, we can find a way to implement this action, as well as a community post explaining how to use the correct parameters. Ensure that the domain, clientId, and clientSecret variables in the Action come from a Machine-to-Machine (M2M) application with sufficient scopes. > update:users scope

The action below will send a verification email to those who have not verified their email address after each login attempt, block unauthorized ones who have not verified their email address, and have no impact on those who have verified their email address already.

exports.onExecutePostLogin = async (event, api) => {
  const ManagementClient = require('auth0').ManagementClient;
  const management = new ManagementClient({
    domain: event.secrets.domain,
    clientId: event.secrets.clientId,
    clientSecret: event.secrets.clientSecret
  });

  const verified = event.user.email_verified;

  // I am slicing off the 'auth0|' prefix of the user_id here
  const userIdWithoutAuth0 = event.user.user_id.slice(6);

  const params = {
    client_id: event.client.client_id,
    user_id: event.user.user_id,
    identity: {
      // Passing the corrected user_id here
      user_id: userIdWithoutAuth0,
      provider: 'auth0'
    }
  };

  if (!verified) {
    management.jobs.verifyEmail(params, function (err) {
      if (err) {
        console.log(err)
      }
    });
    api.access.deny("Access deny until email verification")
  }
};

As another layer of security, we could add a time parameter indicating when the last email was sent and modify the Action so it will only send an email once every X hours to prevent bad actors from spamming the rate limit.

Related References