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
- A user logs into Sitecore Content Hub™.
- 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
Only handle external logins.
if(Context.AuthenticationSource != AuthenticationSource.External){ return; }
Get the user's provider from the context.
var provider = Context.ExternalUserInfo.Provider ?? "None";
Get the 'LastLoginProvider' property of the user's object.
var prop = await Context.User.GetPropertyAsync<ICultureInsensitiveProperty>("LastLoginProvider");
Set the 'LastLoginProvider' property to the external provider ('None' if internal).
prop.SetValue(provider);
Save the user entity.
await MClient.Entities.SaveAsync(Context.User);
Setup
Create a
string
property calledLastLoginProvider
on theUser
definition.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