User post-registration script
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.
-
Configure the user groups or profiles required during the pre-registration process.
-
Create a user group called Google.
-
Ensure schema properties align with the script logic for pre-registration workflows.
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
First, the script includes the libraries that it needs.
using System.Linq;
Then, it checks the external user provider. If the provider is not Google
, the script exits.
if (Context.ExternalUserInfo?.Provider != "Google") return;
Afterwards, it creates a query that gets the Google user group.
var query = Query.CreateQuery(entities =>
from e in entities
where e.DefinitionName == "Usergroup" && e.Property("GroupName") == "Google"
select e);
After this, the script executes the query to get the Google group ID.
var googleGroupId = await MClient.Querying.SingleIdAsync(query);
If the user group cannot be found, the script throw an InvalidOperationException
.
if (!googleGroupId.HasValue) throw new InvalidOperationException("Google usergroup not found.");
Then, the script gets the user's user group relation.
var relation = await Context.User.GetRelationAsync<IChildToManyParentsRelation>("UserGroupToUser");
It then adds the Google group to the user's object via the user group relation.
relation.Parents.Add(googleGroupId.Value);
Lastly, the script saves the user entity.
await MClient.Entities.SaveAsync(Context.User);
Setup
-
Create, publish, and enable the User post-registration script.