logo
logo

User post-registration script example

This is an example of a User post-registration script to be executed after a new user is registered to Sitecore Content Hub™. It adds the user to a specific user group if the external provider is Google.

Use case

  1. A new user is registered.
  2. The script checks if the provider is Google. In that case, the user is added to the Google user group.

Script

using System.Linq;

if (Context.ExternalUserInfo?.Provider != "Google") return;

var query = Query.CreateQuery(entities =>
    from e in entities
    where e.DefinitionName == "Usergroup" && e.Property("GroupName") == "Google"
    select e);

var googleGroupId = await MClient.Querying.SingleIdAsync(query);
if (!googleGroupId.HasValue) throw new InvalidOperationException("Google usergroup not found.");

var relation = await Context.User.GetRelationAsync<IChildToManyParentsRelation>("UserGroupToUser");
relation.Parents.Add(googleGroupId.Value);

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

Script explanation

  1. Include the libraries to be used in the script.

    using System.Linq;
  2. Check the external user provider. only the 'Google' provider is of interest.

    if (Context.ExternalUserInfo?.Provider != "Google") return;
  3. Create a query that get the Google user group.

    var query = Query.CreateQuery(entities =>
    from e in entities
    where e.DefinitionName == "Usergroup" && e.Property("GroupName") == "Google"
    select e);
    Tip

    For more information about creating queries, please refer to the Script development section.

  4. Execute the query to get the Google group Id.

    var googleGroupId = await MClient.Querying.SingleIdAsync(query);
  5. If the user group cannot be found, throw an InvalidOperationException.

    if (!googleGroupId.HasValue) throw new InvalidOperationException("Google usergroup not found.");
  6. Get the user's user group relation.

    var relation = await Context.User.GetRelationAsync<IChildToManyParentsRelation>("UserGroupToUser");
  7. Add the Google group to the user's object via the user group relation.

    relation.Parents.Add(googleGroupId.Value);
  8. Save the user entity.

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

Setup

  1. Create a user group called "Google".

  2. Create, publish and enable the User post-registration script with the source code above.

Can we improve this article ? Provide feedback