How to add access to a new section for the administrator user group from code?

Hello!

I’m working on my custom package. I managed to create a section. However, this section is not visible by default.

I know that I can add access to a user group on the UI, inside the user group with “Sections Add sections to give users access”.

However, I didn’t figure out how to do that from code, from my package, so the Administrator role automatically has that access.

How could I do that?

To automatically grant access to the Administrator group from your package code, you can use the IUserGroupService like this:

private readonly IUserGroupService _userGroupService;

var groups = await _userGroupService.GetAllAsync(0,50);

var adminGroup = groups.Items.FirstOrDefault(group => group.Alias == "admin"); //admin alias
if (adminGroup != null)
{
  adminGroup.AddAllowedSection("test"); //section alias
  _userGroupService.UpdateAsync(adminGroup, "adminkey"); //admin guid
}
3 Likes

Thank you! And what’s the recommended way to call this code?

In an StartupFilter, then add it to a Composer?

I would say a Notification handler seems to be right
INotificationHandler<UmbracoApplicationStartingNotification>

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.