logo
logo

User sign-in script example

This is an example of a User sign-in script to be executed when a user logs into Sitecore Content Hub™. It adds the user's last login provider to the user's object.

Warning
  • The User sign-in script might lock users out when there are inconsistent user validations in the script or any other runtime errors. This includes superusers and administrators.
  • This lock-out can be resolved by de-activating the script using the REST API or SDK. To de-activate a script using the REST API, a PUT request should be sent to change the boolean value "M.Script.Enabled".

Use case

  1. A user logs into Sitecore Content Hub™.
  2. The script adds the user's login provider to the user's object (if the login provider is external).

Script

if(Context.AuthenticationSource != AuthenticationSource.External){
    return;
}

var provider = Context.ExternalUserInfo.Provider ?? "None";

var prop = await Context.User.GetPropertyAsync<ICultureInsensitiveProperty>("LastLoginProvider");
prop.SetValue(provider);

await MClient.Entities.SaveAsync(Context.User);

Script explanation

  1. Only handle external logins.

    if(Context.AuthenticationSource != AuthenticationSource.External){
        return;
    }
  2. Get the user's provider from the context.

    var provider = Context.ExternalUserInfo.Provider ?? "None";
  3. Get the 'LastLoginProvider' property of the user's object.

    var prop = await Context.User.GetPropertyAsync<ICultureInsensitiveProperty>("LastLoginProvider");
  4. Set the 'LastLoginProvider' property to the external provider ('None' if internal).

    prop.SetValue(provider);
  5. Save the user entity.

    await MClient.Entities.SaveAsync(Context.User);

Setup

  1. Create a string property called LastLoginProvider on the User definition.

  2. Create, publish and enable the User sign-in script with the source code above.

Disable a script

Use the following example snippet to disable a script using the web SDK:

var loadConfig = new EntityLoadConfiguration(
                CultureLoadOption.None,
                new PropertyLoadOption(
                    ScriptingConstants.Scripting.Properties.Enabled),
                RelationLoadOption.None);

var script = await MClient.Entities.GetAsync(<your script id>, loadConfig).ConfigureAwait(false);
script?.SetPropertyValue("M.Script.Enabled", false);

await MClient.Entities.SaveAsync(script).ConfigureAwait(false);

Can we improve this article ? Provide feedback