logo
logo

User pre-registration script example

This is an example of a User pre-registration script to be executed before a new user is registered to Sitecore Content Hub™. It only allows a certain email address type if the external provider is Google.

Use case

  1. A new user is to be registered.
  2. The script checks if the provider is Google. In that case, only e-mail addresses ending with @Stylelabs.com are allowed.

Script

if (Context.ExternalUserInfo?.Provider == "Google")
{
    var info = Context.ExternalUserInfo;
    if (string.IsNullOrEmpty(info.Email))
    {
        throw new InvalidOperationException("Provider was 'Google' but email was 'null'.");
    }

    if (!info.Email.EndsWith("@stylelabs.com"))
    {
        throw new ForbiddenException("You are not allowed to access the system. Please contact the administrator.");
    }
}

Script explanation

  1. Check the external user provider. Only the 'Google' provider is of interest.

    if (Context.ExternalUserInfo?.Provider == "Google")
  2. Get the external user information.

    var info = Context.ExternalUserInfo;
    Tip

    For more information about the ExternalUserInfo, please refer to the API reference notes.

  3. If the user email is null or empty, throw an InvalidOperationException.

    if (string.IsNullOrEmpty(info.Email))
    {
        throw new InvalidOperationException("Provider was 'Google' but email was 'null'.");
    }
  4. If the email does not end with '@stylelabs.com', throw a ForbiddenException.

    if (!info.Email.EndsWith("@stylelabs.com"))
    {
        throw new ForbiddenException("You are not allowed to access the system. Please contact the administrator.");
    }

Setup

  • Create, publish and enable the User pre-registration script with the source code above.

Can we improve this article ? Provide feedback