Ejemplo n.º 1
0
        private static IEnumerable <NavigationTreeNode> GetParentChainForNode(NavigationTreeNode node)
        {
            if (node == null || node.IsRootNode)
            {
                // The node is the root node, we don't need to calculate anything
                return(Array.Empty <NavigationTreeNode>());
            }

            // Calculate the parent chain until the root node
            var parentChain = new List <NavigationTreeNode>();
            var parent      = node.Parent;

            while (parent != null)
            {
                parentChain.Add(parent);
                parent = parent.Parent;
            }

            // Done
            parentChain.Reverse();
            return(parentChain.ToArray());
        }
Ejemplo n.º 2
0
        public string ClassNames([NotNull] NavigationTreeNode node, params string[] classes)
        {
            Check.NotNull(node, nameof(node));

            // Create a list containing a union of the classes defined by the node and the classes
            // given by the caller
            var classNames = new List <string>();

            if (!string.IsNullOrEmpty(node.Value.ClassName))
            {
                var nodeClasses = node.Value.ClassName.Split(' ', StringSplitOptions.RemoveEmptyEntries);
                classNames.AddRange(nodeClasses.Distinct());
            }

            if (classes != null && classes.Length > 0)
            {
                classNames.AddRange(classes.Where(c => !string.IsNullOrEmpty(c)));
            }

            // Done
            return(string.Join(" ", classNames.Distinct()));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Retrieves the link url for the given <paramref name="node"/>.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <returns>
        /// The link url.
        /// </returns>
        public string ResolveUrl([NotNull] NavigationTreeNode node)
        {
            var resolvedUrl = string.Empty;

            if (!string.IsNullOrEmpty(node.Value.Url))
            {
                // We got an actual URL for the node
                resolvedUrl = node.Value.Url;
                if (resolvedUrl.StartsWith("~"))
                {
                    // We got a tilde at the start of the URL, try to resolve it to a content
                    resolvedUrl = _urlHelper.Content(resolvedUrl);
                }
            }
            else if (!string.IsNullOrEmpty(node.Value.RouteName))
            {
                //
                resolvedUrl = _urlHelper.RouteUrl(node.Value.RouteName, GetRouteParameters(node));
            }
            else if (!string.IsNullOrEmpty(node.Value.Controller))
            {
                //
                var action = string.IsNullOrEmpty(node.Value.Action) ? "Index" : node.Value.Action;

                var parameters = GetRouteParameters(node);
                if (!string.IsNullOrEmpty(node.Value.Area))
                {
                    parameters.TryAdd("area", node.Value.Area);
                }

                resolvedUrl = _urlHelper.Action(action, node.Value.Controller, parameters);
            }

            // Done
            return(resolvedUrl);
        }
Ejemplo n.º 4
0
 private bool Equals(NavigationTreeNode other) =>
 Equals(_children, other._children) &&
 Equals(Value, other.Value) &&
 Equals(Parent, other.Parent);
Ejemplo n.º 5
0
 private static IEnumerable <NavigationTreeNode> GetSelfAndChildren(NavigationTreeNode node) =>
 new[] { node }.Concat(node.Children.SelectMany(GetSelfAndChildren));
Ejemplo n.º 6
0
        private bool CurrentNodeMatcher(NavigationTreeNode node)
        {
            if (node == null)
            {
                return(false);
            }

            //
            if (!string.IsNullOrEmpty(node.Value.Url))
            {
                //
                var url = node.Value.Url;
                if (url.StartsWith("~"))
                {
                    url = _urlHelper.Content(url);
                }

                return(_httpContext.Request.Path.Equals(url));
            }

            //
            if (string.IsNullOrEmpty(node.Value.RouteName) && string.IsNullOrEmpty(node.Value.Controller))
            {
                //
                return(false);
            }

            var routeData = _urlHelper.ActionContext.RouteData;
            var action    = !string.IsNullOrEmpty(node.Value.RouteName)
                ? routeData.Values["action"] as string ?? "Index"
                : string.IsNullOrEmpty(node.Value.Action)
                    ? "Index"
                    : node.Value.Action;
            var controller = !string.IsNullOrEmpty(node.Value.RouteName)
                ? routeData.Values["controller"] as string ?? string.Empty
                : node.Value.Controller;

            if (!routeData.Values.TryGetValue("controller", out var currentController) ||
                !string.Equals(currentController as string, controller, StringComparison.OrdinalIgnoreCase) ||
                !routeData.Values.TryGetValue("action", out var currentAction) ||
                !string.Equals(currentAction as string, action, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            // Determine if the area matches
            if (!string.IsNullOrEmpty(node.Value.Area) &&
                (!routeData.Values.TryGetValue("area", out var currentArea) ||
                 !string.Equals(currentArea as string, node.Value.Area, StringComparison.OrdinalIgnoreCase)))
            {
                // The area doesn't match
                return(false);
            }

            // The controller, action and area of the route matches the controller and action of the node,
            // determine if the other parameters match too
            foreach (var param in GetRouteParameters(node))
            {
                if (!routeData.Values.TryGetValue(param.Key, out var value) ||
                    value is string str && !string.Equals(str, param.Value, StringComparison.OrdinalIgnoreCase) ||
                    !Equals(value, param.Value))
                {
                    // The route parameter does not match the expected value
                    return(false);
                }
            }

            // The parameters match
            return(true);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Asynchronously determines whether the given <paramref name="node"/> can be displayed based on
        /// the current request.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken" /> to observe while waiting for the
        /// task to complete.</param>
        /// <returns>
        /// The <see cref="Task"/> object representing the asynchronous operation.
        /// </returns>
        public async Task <bool> ShouldDisplayAsync([NotNull] NavigationTreeNode node,
                                                    CancellationToken cancellationToken = default)
        {
            Check.NotNull(node, nameof(node));

            // Determine if the node should be hidden for the current user
            var hideFrom = node.Value.HideNodeFrom;

            if (hideFrom != HideNodeFrom.None)
            {
                if ((hideFrom & HideNodeFrom.All) == HideNodeFrom.All)
                {
                    // The node is hidden from all users, no other validation needed
                    return(false);
                }

                // Determine if the node should be hidden for the current user
                var isAuthenticated = _httpContext.User?.Identity?.IsAuthenticated == true;
                if ((hideFrom & HideNodeFrom.Anonymous) == HideNodeFrom.Anonymous && !isAuthenticated)
                {
                    // The node should be hidden from anonymous users, and there is no authenticated user
                    return(false);
                }

                if ((hideFrom & HideNodeFrom.Authenticated) == HideNodeFrom.Authenticated && isAuthenticated)
                {
                    // The node should be hidden from authenticated users, and there is an authenticated user
                    return(false);
                }
            }

            // Determine if the node has an authorization policy
            if (!string.IsNullOrEmpty(node.Value.AuthorizationPolicyName))
            {
                // The node has an authorization policy
                try
                {
                    var authorizationResult = await _authorizationService
                                              .AuthorizeAsync(_httpContext.User, node.Value.AuthorizationPolicyName);

                    return(authorizationResult.Succeeded);
                }
                catch (Exception e)
                {
                    _logger.LogError(e,
                                     "There was an unexpected exception while trying to authorize the navigation node " +
                                     $"with key '{node.Value.Key}' which has an authorization policy named " +
                                     $"'{node.Value.AuthorizationPolicyName}'");

                    return(false);
                }
            }

            // The node doesn't have an authorization policy, lets try with the roles
            if (string.IsNullOrEmpty(node.Value.Roles) || node.Value.Roles == "*")
            {
                // The node doesn't specify any required role or is allowing all the users
                return(true);
            }

            // Done
            var user = _httpContext.User;

            return(user != null && user.IsInRole(node.Value.Roles));
        }