Implementing Auth0 Post User Registration Action for Multinational Sitecore Websites

Dear friends!

Summer is almost here, and it’s a wonderful time! ☀️

Today’s post continues our journey in the Auth0 universe.

Recently, we faced the challenge of creating an Auth0 Action for Post User Registration that sends a notification email to administrators whenever a new user signs up.
This email guides them on how to assign a specific role to the newly created user, granting them access to the site.
The tricky part was selecting the correct role, as we have different roles for each country/market.

So, how did we tackle this?

We have multiple websites for different countries/markets, and we need to determine which website the user is signing up for to assign the appropriate role. The solution involves making each website “country/market aware” by using an environment variable.
*And yes, we could of course have done this in Sitecore

SITE_REGION=sv-SE

This environment variable helps us identify the country/market associated with each website.

Next, we needed a way to pass this information to Auth0 so that our action can determine the correct email template and recipients. This is accomplished by adding the site region information to the /api/auth/signup endpoint in our Next.js app, as covered in my previous blog post, Add Authentication to Your Sitecore Site Using Auth0 with NextJs – Register New User.

Here’s the updated handler for the /api/auth/signup endpoint:

export default async function handler(req, res) {
  const domain = process.env.DOMAIN;
  const connection = process.env.CONNECTION;
  const client_id = process.env.CLIENT_ID;
 
  // Set CORS headers
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
 
  // Handle OPTIONS method (preflight request)
  if (req.method === 'OPTIONS') {
    return res.status(200).end();
  }

 
  if (req.method === 'POST') {
    const {
      email,
      password,
      username,
      name,
      siteRegion = process.env.SITE_REGION
    } = req.body;
 
    try {
      const auth0Res = await fetch(`https://${domain}.auth0.com/dbconnections/signup`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          client_id,
          email,
          password,
          connection,
          username,
          name,
          user_metadata: {
              // Pass additional data in the user_metadata field
              siteRegion
            },
        }),
      });
 
      if (!auth0Res.ok) {
        throw new Error(`Auth0 signup failed: ${await auth0Res.text()}`);
      }
 
      const auth0Data = await auth0Res.json();
      res.status(200).json({ success: true, data: auth0Data });
    } catch (error) {
      console.error(error);
      res.status(500).json({ success: false, error: error.message });
    }
  } else {
    // Respond to any methods other than POST and OPTIONS
    res.setHeader('Allow', ['POST', 'OPTIONS']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

*Notice how we set the user_metadata field. This ensures that the user now has a custom field (user_metadata) indicating the site region.

Wonderful!

With the siteRegion metadata in place, our Auth0 Action can select the appropriate email template and recipients based on this information. We use SendGrid for sending emails.

In my previous blog post, Add Authentication to Your Sitecore Site Using Auth0 with NextJs – Flows (Actions), I covered how to set up Auth0 Actions. Let’s build on that knowledge and see how the Post User Registration action is implemented.

/**
 * 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) => {
  const axios = require("axios");

  // Extract the siteRegion from user metadata
  const siteRegion = event.user.user_metadata?.siteRegion || 'sv-SE';

  // Define email recipients and template IDs for different regions
  const norwegianEmailsArray = [
    { email: "some.administrator@sandbox.no" },
    { email: "some.administrator@sandbox.no" }
  ];
  const swedishEmailsArray = [
    { email: "some.administrator@sandbox.se" },
    { email: "some.administrator@sandbox.se" }
  ];

  const swedishEmailTemplateId = event.secrets.SWEDISH_EMAIL_TEMPLATE;
  const norwegianEmailTemplateId = event.secrets.NORWEGIAN_EMAIL_TEMPLATE;

  let emailsArray;
  let emailTemplateId;

  // Use switch to determine the email recipients and template ID based on siteRegion
  switch (siteRegion.toLowerCase()) {
    case 'sv-se':
      emailsArray = swedishEmailsArray;
      emailTemplateId = swedishEmailTemplateId;
      break;
    case 'nb-no':
      emailsArray = norwegianEmailsArray;
      emailTemplateId = norwegianEmailTemplateId;
      break;
    default:
      // If siteRegion is not specified or does not match any case, use Swedish defaults
      emailsArray = swedishEmailsArray;
      emailTemplateId = swedishEmailTemplateId;
      console.log(`Unknown or missing site region: ${siteRegion}. Defaulting to Swedish configuration.`);
      break;
  }

  try {
    // Send email using SendGrid
    await axios.post('https://api.sendgrid.com/v3/mail/send',
      {
        personalizations: [{
          to: emailsArray,
          "dynamic_template_data": {
            "email": event.user.email,
            "phoneNumber": event.user.phone_number
          }
        }],
        template_id: emailTemplateId,
        from: { email: 'info@sandbox.com' },
      },
      {
        headers: {
          'Authorization': 'Bearer ' + event.secrets.SENDGRID_API_KEY,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log(`User ${event.user.email} is signed up`);
  } catch (err) {
    console.log(`Error signing up user  ${event.user.email}:`, err.message);
  }
};

The Post User Registration action is a crucial component in our user management system, activated immediately after a user completes the registration process. This action’s primary function is to notify administrators about new sign-ups and provide guidance on assigning appropriate roles to the new users, ensuring they gain the necessary access to the site.

Let’s go through the action code to understand its functionality:

Extracting Site Region

The action begins by extracting the siteRegion from the user’s metadata. This siteRegion is a custom attribute that indicates the country or market the website is associated with. If the siteRegion is not provided during registration, it defaults to 'sv-SE', representing Sweden.

Defining Email Recipients and Templates

For different regions, the action defines specific email recipients and corresponding email template IDs. This setup allows the system to tailor notification emails based on the user’s location. For instance, administrators in Norway receive notifications different from those sent to administrators in Sweden.

Determining Email Configuration

Using the extracted siteRegion, the action determines the appropriate recipients and email template. This is achieved through a switch statement that matches the siteRegion value to predefined cases for Sweden and Norway. If the siteRegion does not match any known values, the action defaults to the configuration for Sweden.

Sending Notification Email

The action sends out the notification email via the SendGrid API. It includes essential information about the new user, such as their email and phone number. The SendGrid API key, along with other sensitive data like email template IDs, is securely stored as secrets in Auth0. This ensures that sensitive information is not exposed in the code.

Summary

By integrating this action, we automate the notification process for new user registrations, enhancing efficiency and ensuring that administrators are promptly informed. This approach simplifies role assignment and helps maintain a streamlined user management system, especially when dealing with multiple websites across different regions.

Implementing the Post User Registration action with Auth0 has really made our user onboarding process a breeze. We use environment variables to pass site-specific info and team up with SendGrid for email notifications, so new users get a warm welcome and we can manage them based on their location.

This not only makes it easier to assign roles, but also helps us effectively handle users across different websites and markets. Thanks to Auth0 Actions, we can quickly adapt to different situations and keep our user management system strong.

Feel free to reach out if you have any questions or if you’d like to share how you’ve tackled similar challenges. Enjoy the sunny days ahead, and happy coding!

That’s all for now folks 🙂


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.