Search code examples
permissionsumbracomemberumbraco8

Umbraco: How to check if a member is allowed to access a page programmatically


I'm setting up a Umbraco 8 site for creating a prototype.
As I'm playing around with the default code of the Starter Kit, I wanted to change the behaviour of the top navigation.
Currently you can only hide pages for all visitors, but I want to only hide pages based on the members (group) permissions.

I see, that you can check, if a member is in a role with Role.IsUserInRole, but I cannot see a way to get the allowed roles for a page.

Do I need to get the roles and loop through them?
If yes, how do I get them?
If no, what is the right way to do this?


Solution

  • I got it working this way:

    IContent content = base.Services.ContentService.GetById(item.Id);
    PublicAccessEntry entry = base.Services.PublicAccessService.GetEntryForContent(content);
    if (entry != null)
    {
        foreach (var r in entry.Rules)
        {
            if (Roles.IsUserInRole(r.RuleValue))
            {
                <a class="nav-link @(item.IsAncestorOrSelf(Model) ? "nav-link--active" : null)" href="@item.Url">@item.Name</a>
            }
        }
    }
    else
    {
        <a class="nav-link @(item.IsAncestorOrSelf(Model) ? "nav-link--active" : null)" href="@item.Url">@item.Name</a>
    }
    

    Maybe this needs some more work, as I guess the performance is not that good.