Umbraco 7 hide navigation nodes user has no access to

razor, umbraco7

Solution

I check user access to pages like this:

var node = [the page you want to verify access to ie. "CurrentPage"];
var isProtected = umbraco.library.IsProtected(node.id, node.path);
var hasAccess = umbraco.library.HasAccess(item.id, item.path);

My top menu code:

   var homePage = CurrentPage.AncestorsOrSelf(1).First();
    var menuItems = homePage.Children.Where("UmbracoNaviHide == false");
    @foreach (var item in menuItems)
    {
        var loginAcces = umbraco.library.IsProtected(item.id, item.path) && umbraco.library.HasAccess(item.id, item.path);
        var cssClass = loginAcces ? "loginAcces ":"";
        cssClass += CurrentPage.IsDescendantOrSelf(item) ? "current_page_item" :"";                           

        if(!umbraco.library.IsProtected(item.id, item.path) || loginAcces){
            [render your item here]
        }
}

This will hide items that are protected, unless user is logged in and has access.

Problem

I've seen some examples in previous versions of Umbraco (namely 5) where this seemed to be relatively straightforward. See this stackoverflow question for example. The theory is that I can use a property `HasAccess` or `IsProtected` on a node, or the method `WhereHasAccess` when selecting which nodes to use. The code I have so far is: ``` var nodes = @CurrentPage.AncestorsOrSelf(1).First().Children; ``` This gets me the list of pages, no problem. However, I am struggling to filter the list of pages so that a logged in user only sees what they have access to and a public visitor sees no protected pages. The V5 code suggests this is possible: `var nodes = @CurrentPage.AncestorsOrSelf(1).First().Children.WhereCanAccess();` But this results in the error: `'Umbraco.Web.Models.DynamicPublishedContentList' does not contain a definition for 'WhereCanAccess'` The latest published version of the Razor cheatsheet for Umbraco indicates that `HasAccess()` and `IsProtected()` are two methods that are both available, but when using either of these I get null values, e.g.: ``` @foreach(var node in nodes.WhereCanAccess()) { <li>@node.Name / @node.IsProtected / @node.IsProtected() / @node.HasAccess() / @node.HasAccess </li> } ``` Returns null for all the test values (e.g. `@node.IsProtected`). It seems that what I am trying to achieve is simple, but I am approaching it the wrong way. Someone please point out the error of my ways!

Original source