/// <summary>
        /// Evaluate if we have a specific owner variation permission to at least one content type
        /// </summary>
        public static async Task <bool> AuthorizeContentTypeDefinitionsAsync(this IAuthorizationService service, ClaimsPrincipal user, Permission requiredPermission, IEnumerable <ContentTypeDefinition> contentTypeDefinitions, IContentManager contentManager)
        {
            ArgumentNullException.ThrowIfNull(user);
            ArgumentNullException.ThrowIfNull(requiredPermission);
            ArgumentNullException.ThrowIfNull(contentManager);

            var permission = GetOwnerVariation(requiredPermission);

            var contentTypePermission = ContentTypePermissionsHelper.ConvertToDynamicPermission(permission);

            foreach (var contentTypeDefinition in contentTypeDefinitions)
            {
                var dynamicPermission = ContentTypePermissionsHelper.CreateDynamicPermission(contentTypePermission, contentTypeDefinition);

                var contentItem = await contentManager.NewAsync(contentTypeDefinition.Name);

                contentItem.Owner = user.FindFirstValue(ClaimTypes.NameIdentifier);

                if (await service.AuthorizeAsync(user, dynamicPermission, contentItem))
                {
                    return(true);
                }
            }

            return(await service.AuthorizeAsync(user, permission));
        }
Пример #2
0
        public async Task BuildNavigationAsync(string name, NavigationBuilder builder)
        {
            var context = _httpContextAccessor.HttpContext;

            if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var contentTypeDefinitions = _contentDefinitionManager.ListTypeDefinitions().OrderBy(d => d.Name);
            var contentTypes           = contentTypeDefinitions.Where(ctd => ctd.GetSettings <ContentTypeSettings>().Creatable).OrderBy(ctd => ctd.DisplayName);
            await builder.AddAsync(S["Content"], NavigationConstants.AdminMenuContentPosition, async content =>
            {
                content.AddClass("content").Id("content");
                await content.AddAsync(S["Content Items"], S["Content Items"].PrefixPosition(), async contentItems =>
                {
                    if (!await _authorizationService.AuthorizeContentTypeDefinitionsAsync(context.User, CommonPermissions.EditContent, contentTypes, _contentManager))
                    {
                        contentItems.Permission(Permissions.EditContent);
                    }

                    contentItems.Action(nameof(AdminController.List), typeof(AdminController).ControllerName(), new { area = "OrchardCore.Contents", contentTypeId = "" });
                    contentItems.LocalNav();
                });
            });

            var adminSettings = (await _siteService.GetSiteSettingsAsync()).As <AdminSettings>();

            if (adminSettings.DisplayNewMenu && contentTypes.Any())
            {
                await builder.AddAsync(S["New"], "-1", async newMenu =>
                {
                    newMenu.LinkToFirstChild(false).AddClass("new").Id("new");
                    foreach (var contentTypeDefinition in contentTypes)
                    {
                        var ci  = await _contentManager.NewAsync(contentTypeDefinition.Name);
                        var cim = await _contentManager.PopulateAspectAsync <ContentItemMetadata>(ci);
                        var createRouteValues = cim.CreateRouteValues;
                        createRouteValues.Add("returnUrl", _linkGenerator.GetPathByRouteValues(context, "", new
                        {
                            area       = "OrchardCore.Contents",
                            controller = "Admin",
                            action     = "List"
                        }));

                        if (createRouteValues.Any())
                        {
                            newMenu.Add(new LocalizedString(contentTypeDefinition.DisplayName, contentTypeDefinition.DisplayName), "5", item => item
                                        .Action(cim.CreateRouteValues["Action"] as string, cim.CreateRouteValues["Controller"] as string, cim.CreateRouteValues)
                                        .Permission(ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditOwnContent.Name], contentTypeDefinition))
                                        );
                        }
                    }
                });
            }
        }
        public async Task BuildNavigationAsync(MenuItem menuItem, NavigationBuilder builder, IEnumerable <IAdminNodeNavigationBuilder> treeNodeBuilders)
        {
            var node = menuItem as ContentTypesAdminNode;

            if ((node == null) || (!node.Enabled))
            {
                return;
            }

            // Add ContentTypes specific children
            var typesToShow = GetContentTypesToShow(node);

            foreach (var ctd in typesToShow)
            {
                builder.Add(new LocalizedString(ctd.DisplayName, ctd.DisplayName), cTypeMenu =>
                {
                    cTypeMenu.Url(_linkGenerator.GetPathByRouteValues(_httpContextAccessor.HttpContext, "", new
                    {
                        area          = "OrchardCore.Contents",
                        controller    = "Admin",
                        action        = "List",
                        contentTypeId = ctd.Name
                    }));

                    cTypeMenu.Priority(node.Priority);
                    cTypeMenu.Position(node.Position);
                    cTypeMenu.Permission(
                        ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.PublishOwnContent.Name], ctd));

                    GetIconClasses(ctd, node).ToList().ForEach(c => cTypeMenu.AddClass(c));

                    cTypeMenu.AdminNodeProvider(nameof(ContentTypesAdminNode));
                });
            }

            // Add external children
            foreach (var childNode in node.Items)
            {
                try
                {
                    var treeBuilder = treeNodeBuilders.Where(x => x.Name == childNode.GetType().Name).FirstOrDefault();
                    await treeBuilder.BuildNavigationAsync(childNode, builder, treeNodeBuilders);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "An exception occurred while building the '{MenuItem}' child Menu Item.", childNode.GetType().Name);
                }
            }
        }
Пример #4
0
        public async Task BuildNavigationAsync(MenuItem menuItem, NavigationBuilder builder, IEnumerable <IAdminNodeNavigationBuilder> treeNodeBuilders)
        {
            _node = menuItem as ListsAdminNode;

            if (_node == null || !_node.Enabled || String.IsNullOrEmpty(_node.ContentType))
            {
                return;
            }

            _contentType = _contentDefinitionManager.GetTypeDefinition(_node.ContentType);

            if (_node.AddContentTypeAsParent)
            {
                if (_contentType == null)
                {
                    _logger.LogError("Can't find The content type '{ContentType}' for list admin node.", _node.ContentType);
                }

                await builder.AddAsync(new LocalizedString(_contentType.DisplayName, _contentType.DisplayName), async listTypeMenu =>
                {
                    AddPrefixToClasses(_node.IconForParentLink).ForEach(c => listTypeMenu.AddClass(c));
                    listTypeMenu.Permission(ContentTypePermissionsHelper.CreateDynamicPermission(
                                                ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType));
                    await AddContentItemsAsync(listTypeMenu, _node.LinkMode);
                });
            }
            else
            {
                await AddContentItemsAsync(builder, _node.LinkMode);
            }

            // Add external children
            foreach (var childNode in _node.Items)
            {
                try
                {
                    var treeBuilder = treeNodeBuilders.Where(x => x.Name == childNode.GetType().Name).FirstOrDefault();
                    await treeBuilder.BuildNavigationAsync(childNode, builder, treeNodeBuilders);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "An exception occurred while building the '{MenuItem}' child Menu Item.", childNode.GetType().Name);
                }
            }
        }
Пример #5
0
        public async Task BuildNavigationAsync(string name, NavigationBuilder builder)
        {
            if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var contentTypeDefinitions = _contentDefinitionManager.ListTypeDefinitions().OrderBy(d => d.Name);

            builder.Add(S["Content"], NavigationConstants.AdminMenuContentPosition, content => content
                        .AddClass("content").Id("content")
                        .Add(S["Content Items"], S["Content Items"].PrefixPosition(), contentItems => contentItems
                             .Permission(Permissions.EditOwnContent)
                             .Action(nameof(AdminController.List), typeof(AdminController).ControllerName(), new { area = "OrchardCore.Contents" })
                             .LocalNav())
                        );
            var contentTypes = contentTypeDefinitions.Where(ctd => ctd.GetSettings <ContentTypeSettings>().Creatable).OrderBy(ctd => ctd.DisplayName);

            if (contentTypes.Any())
            {
                await builder.AddAsync(S["New"], "-1", async newMenu =>
                {
                    newMenu.LinkToFirstChild(false).AddClass("new").Id("new");
                    foreach (var contentTypeDefinition in contentTypes)
                    {
                        var ci  = await _contentManager.NewAsync(contentTypeDefinition.Name);
                        var cim = await _contentManager.PopulateAspectAsync <ContentItemMetadata>(ci);
                        var createRouteValues = cim.CreateRouteValues;
                        if (createRouteValues.Any())
                        {
                            newMenu.Add(new LocalizedString(contentTypeDefinition.DisplayName, contentTypeDefinition.DisplayName), "5", item => item
                                        .Action(cim.CreateRouteValues["Action"] as string, cim.CreateRouteValues["Controller"] as string, cim.CreateRouteValues)
                                        .Permission(ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[Permissions.PublishOwnContent.Name], contentTypeDefinition))
                                        );
                        }
                    }
                });
            }
        }
        private async Task AddContentItemsAsync(NavigationBuilder listTypeMenu)
        {
            foreach (var ci in await getContentItemsAsync())
            {
                var cim = await _contentManager.PopulateAspectAsync <ContentItemMetadata>(ci);

                if (cim.AdminRouteValues.Any() && ci.DisplayText != null)
                {
                    listTypeMenu.Add(new LocalizedString(ci.DisplayText, ci.DisplayText), m =>
                    {
                        m.Action(cim.AdminRouteValues["Action"] as string, cim.AdminRouteValues["Controller"] as string, cim.AdminRouteValues);
                        m.Resource(ci);
                        m.Priority(_node.Priority);
                        m.Position(_node.Position);
                        m.LocalNav();
                        AddPrefixToClasses(_node.IconForContentItems).ToList().ForEach(c => m.AddClass(c));

                        m.Permission(ContentTypePermissionsHelper.CreateDynamicPermission(
                                         ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType));
                    });
                }
            }
        }
Пример #7
0
        public Task BuildNavigationAsync(string name, NavigationBuilder builder)
        {
            if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase))
            {
                return(Task.CompletedTask);
            }

            var rvd = new RouteValueDictionary
            {
                { "contentTypeId", "VueForm" },
                { "Area", "OrchardCore.Contents" },
                { "Options.SelectedContentType", "VueForm" },
                { "Options.CanCreateSelectedContentType", true }
            };

            builder.Add(S["Content"], design => design
                        .Add(S["Vue Forms"], S["Vue Forms"], menus => menus
                             .Permission(ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditOwnContent.Name], "VueForm"))
                             .Action("List", "Admin", rvd)
                             .LocalNav()
                             ));

            return(Task.CompletedTask);
        }
Пример #8
0
        public void Build(QueryEngineBuilder <ContentItem> builder)
        {
            builder
            .WithNamedTerm("status", builder => builder
                           .OneCondition <ContentItem>((val, query, ctx) =>
            {
                var context = (ContentQueryContext)ctx;
                if (Enum.TryParse <ContentsStatus>(val, true, out var contentsStatus))
                {
                    switch (contentsStatus)
                    {
                    case ContentsStatus.Draft:
                        query.With <ContentItemIndex>(x => x.Latest && !x.Published);
                        break;

                    case ContentsStatus.Published:
                        query.With <ContentItemIndex>(x => x.Published);
                        break;

                    case ContentsStatus.Owner:
                        var httpContextAccessor = context.ServiceProvider.GetRequiredService <IHttpContextAccessor>();
                        var userNameIdentifier  = httpContextAccessor.HttpContext.User?.FindFirstValue(ClaimTypes.NameIdentifier);
                        query.With <ContentItemIndex>(x => x.Owner == userNameIdentifier && x.Latest);
                        break;

                    case ContentsStatus.AllVersions:
                        query.With <ContentItemIndex>(x => x.Latest);
                        break;

                    default:
                        query.With <ContentItemIndex>(x => x.Latest);
                        break;
                    }
                }
                else
                {
                    // Draft is the default value.
                    query.With <ContentItemIndex>(x => x.Latest);
                }

                return(new ValueTask <IQuery <ContentItem> >(query));
            })
                           .MapTo <ContentOptionsViewModel>((val, model) =>
            {
                if (Enum.TryParse <ContentsStatus>(val, true, out var contentsStatus))
                {
                    model.ContentsStatus = contentsStatus;
                }
            })
                           .MapFrom <ContentOptionsViewModel>((model) =>
            {
                if (model.ContentsStatus != ContentsStatus.Latest)
                {
                    return(true, model.ContentsStatus.ToString());
                }

                return(false, String.Empty);
            })
                           .AlwaysRun()
                           )
            .WithNamedTerm("sort", builder => builder
                           .OneCondition <ContentItem>((val, query) =>
            {
                if (Enum.TryParse <ContentsOrder>(val, true, out var contentsOrder))
                {
                    switch (contentsOrder)
                    {
                    case ContentsOrder.Modified:
                        query.With <ContentItemIndex>().OrderByDescending(x => x.ModifiedUtc);
                        break;

                    case ContentsOrder.Published:
                        query.With <ContentItemIndex>().OrderByDescending(cr => cr.PublishedUtc);
                        break;

                    case ContentsOrder.Created:
                        query.With <ContentItemIndex>().OrderByDescending(cr => cr.CreatedUtc);
                        break;

                    case ContentsOrder.Title:
                        query.With <ContentItemIndex>().OrderBy(cr => cr.DisplayText);
                        break;
                    }
                    ;
                }
                else
                {
                    // Modified is a default value and applied when there is no filter.
                    query.With <ContentItemIndex>().OrderByDescending(x => x.ModifiedUtc);
                }

                return(query);
            })
                           .MapTo <ContentOptionsViewModel>((val, model) =>
            {
                if (Enum.TryParse <ContentsOrder>(val, true, out var contentsOrder))
                {
                    model.OrderBy = contentsOrder;
                }
            })
                           .MapFrom <ContentOptionsViewModel>((model) =>
            {
                if (model.OrderBy != ContentsOrder.Modified)
                {
                    return(true, model.OrderBy.ToString());
                }

                return(false, String.Empty);
            })
                           .AlwaysRun()
                           )
            .WithNamedTerm("type", builder => builder
                           .OneCondition <ContentItem>(async(contentType, query, ctx) =>
            {
                var context                  = (ContentQueryContext)ctx;
                var httpContextAccessor      = context.ServiceProvider.GetRequiredService <IHttpContextAccessor>();
                var authorizationService     = context.ServiceProvider.GetRequiredService <IAuthorizationService>();
                var contentManager           = context.ServiceProvider.GetRequiredService <IContentManager>();
                var contentDefinitionManager = context.ServiceProvider.GetRequiredService <IContentDefinitionManager>();
                var user = httpContextAccessor.HttpContext.User;
                var userNameIdentifier = user?.FindFirstValue(ClaimTypes.NameIdentifier);

                var canListAllContent = await authorizationService.AuthorizeAsync(user, Permissions.ListContent);

                // Filter for a specific type.
                if (!string.IsNullOrEmpty(contentType))
                {
                    var contentTypeDefinition = contentDefinitionManager.GetTypeDefinition(contentType);
                    if (contentTypeDefinition != null)
                    {
                        // We display a specific type even if it's not listable so that admin pages
                        // can reuse the Content list page for specific types.
                        var contentItem   = await contentManager.NewAsync(contentTypeDefinition.Name);
                        contentItem.Owner = userNameIdentifier;

                        var hasContentListPermission = await authorizationService.AuthorizeAsync(user, ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.ListContent.Name], contentTypeDefinition), contentItem);
                        if (hasContentListPermission)
                        {
                            query.With <ContentItemIndex>(x => x.ContentType == contentType);
                        }
                        else
                        {
                            query.With <ContentItemIndex>(x => x.ContentType == contentType && x.Owner == userNameIdentifier);
                        }
                    }
                }
                else
                {
                    var listableTypes            = new List <ContentTypeDefinition>();
                    var authorizedContentTypes   = new List <ContentTypeDefinition>();
                    var unauthorizedContentTypes = new List <ContentTypeDefinition>();

                    foreach (var ctd in contentDefinitionManager.ListTypeDefinitions())
                    {
                        if (ctd.GetSettings <ContentTypeSettings>().Listable)
                        {
                            // We want to list the content item if the user can edit their own items at least.
                            // It might display content items the user won't be able to edit though.
                            var contentItem   = await contentManager.NewAsync(ctd.Name);
                            contentItem.Owner = userNameIdentifier;

                            var hasEditPermission = await authorizationService.AuthorizeAsync(user, CommonPermissions.EditContent, contentItem);
                            if (hasEditPermission)
                            {
                                listableTypes.Add(ctd);
                            }

                            if (!canListAllContent)
                            {
                                var hasContentListPermission = await authorizationService.AuthorizeAsync(user, ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.ListContent.Name], ctd), contentItem);
                                if (hasContentListPermission)
                                {
                                    authorizedContentTypes.Add(ctd);
                                }
                                else
                                {
                                    unauthorizedContentTypes.Add(ctd);
                                }
                            }
                        }
                    }

                    if (authorizedContentTypes.Any() && !canListAllContent)
                    {
                        query.With <ContentItemIndex>().Where(x => (x.ContentType.IsIn(authorizedContentTypes.Select(t => t.Name).ToArray())) || (x.ContentType.IsIn(unauthorizedContentTypes.Select(t => t.Name).ToArray()) && x.Owner == userNameIdentifier));
                    }
                    else
                    {
                        query.With <ContentItemIndex>(x => x.ContentType.IsIn(listableTypes.Select(t => t.Name).ToArray()));

                        // If we set the ListContent permission
                        // to false we can only view our own content and
                        // we bypass and force the corresponding ContentsStatus by owned content filtering
                        if (!canListAllContent)
                        {
                            query.With <ContentItemIndex>(x => x.Owner == userNameIdentifier);
                        }
                    }
                }

                return(query);
            })
                           .MapTo <ContentOptionsViewModel>((val, model) =>
            {
                if (!String.IsNullOrEmpty(val))
                {
                    model.SelectedContentType = val;
                }
            })
                           .MapFrom <ContentOptionsViewModel>((model) =>
            {
                if (!String.IsNullOrEmpty(model.SelectedContentType))
                {
                    return(true, model.SelectedContentType);
                }

                return(false, String.Empty);
            })
                           .AlwaysRun()
                           )
            .WithDefaultTerm("text", builder => builder
                             .ManyCondition <ContentItem>(
                                 ((val, query) => query.With <ContentItemIndex>(x => x.DisplayText.Contains(val))),
                                 ((val, query) => query.With <ContentItemIndex>(x => x.DisplayText.IsNotIn <ContentItemIndex>(s => s.DisplayText, w => w.DisplayText.Contains(val))))
                                 )
                             );
        }
Пример #9
0
        private async Task AddContentItemsAsync(NavigationBuilder listTypeMenu, LinkMode nodeLinkMode)
        {
            foreach (var ci in await getContentItemsAsync())
            {
                var cim = await _contentManager.PopulateAspectAsync <ContentItemMetadata>(ci);


                switch (nodeLinkMode)
                {
                case LinkMode.Admin:
                    if (cim.AdminRouteValues.Any() && ci.DisplayText != null)
                    {
                        listTypeMenu.Add(new LocalizedString(ci.DisplayText, ci.DisplayText), m =>
                        {
                            m.Action(cim.AdminRouteValues["Action"] as string, cim.AdminRouteValues["Controller"] as string, cim.AdminRouteValues);
                            m.Resource(ci);
                            m.Priority(_node.Priority);
                            m.Position(_node.Position);
                            m.LocalNav();
                            AddPrefixToClasses(_node.IconForContentItems).ToList().ForEach(c => m.AddClass(c));

                            m.Permission(ContentTypePermissionsHelper.CreateDynamicPermission(
                                             ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType));
                        });
                    }
                    break;

                case LinkMode.Display:
                    if (cim.DisplayRouteValues.Any() && ci.DisplayText != null)
                    {
                        listTypeMenu.Add(new LocalizedString(ci.DisplayText, ci.DisplayText), m =>
                        {
                            m.Action(cim.DisplayRouteValues["Action"] as string, cim.DisplayRouteValues["Controller"] as string, cim.DisplayRouteValues);
                            m.Resource(ci);
                            m.Priority(_node.Priority);
                            m.Position(_node.Position);
                            m.LocalNav();
                            AddPrefixToClasses(_node.IconForContentItems).ToList().ForEach(c => m.AddClass(c));

                            m.Permission(ContentTypePermissionsHelper.CreateDynamicPermission(
                                             ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType));
                        });
                    }
                    break;

                case LinkMode.Edit:
                    if (cim.EditorRouteValues.Any() && ci.DisplayText != null)
                    {
                        listTypeMenu.Add(new LocalizedString(ci.DisplayText, ci.DisplayText), m =>
                        {
                            m.Action(cim.EditorRouteValues["Action"] as string, cim.EditorRouteValues["Controller"] as string, cim.EditorRouteValues);
                            m.Resource(ci);
                            m.Priority(_node.Priority);
                            m.Position(_node.Position);
                            m.LocalNav();
                            AddPrefixToClasses(_node.IconForContentItems).ToList().ForEach(c => m.AddClass(c));

                            m.Permission(ContentTypePermissionsHelper.CreateDynamicPermission(
                                             ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType));
                        });
                    }
                    break;

                case LinkMode.Create:
                    if (cim.CreateRouteValues.Any() && ci.DisplayText != null)
                    {
                        listTypeMenu.Add(new LocalizedString(ci.DisplayText, ci.DisplayText), m =>
                        {
                            m.Action(cim.CreateRouteValues["Action"] as string, cim.CreateRouteValues["Controller"] as string, cim.CreateRouteValues);
                            m.Resource(ci);
                            m.Priority(_node.Priority);
                            m.Position(_node.Position);
                            m.LocalNav();
                            AddPrefixToClasses(_node.IconForContentItems).ToList().ForEach(c => m.AddClass(c));

                            m.Permission(ContentTypePermissionsHelper.CreateDynamicPermission(
                                             ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.EditContent.Name], _contentType));
                        });
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(nodeLinkMode), nodeLinkMode, null);
                }
            }
        }
        public async Task <IActionResult> Submit(string formId)
        {
            var canView = ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.ViewContent.Name], "VueForm");

            if (!await _authorizationService.AuthorizeAsync(User, canView))
            {
                return(NotFound());
            }

            var form = await _contentManager.GetAsync(formId, VersionOptions.Published);

            if (form == null)
            {
                return(NotFound());
            }

            var formPart = form.As <VueForm>();

            if (formPart.Disabled.Value)
            {
                return(NotFound());
            }

            if (!_contentPermissionsService.CanAccess(form))
            {
                return(NotFound());
            }

            var scriptingProvider = new VueFormMethodsProvider(form);

            var script = form.As <VueFormScripts>();

            // This object holds the return value of the script
            object serverScriptResult = EvaluateScript(script?.OnValidation?.Text, scriptingProvider, formPart, "OnValidation");

            // Return if any errors are returned in the OnValidation script
            if (ModelState.ErrorCount > 0)
            {
                return(Json(new VueFormSubmitResult(GetErrorDictionary(), serverScriptResult, GetDebugLogs(formPart))));
            }

            serverScriptResult = EvaluateScript(script?.OnSubmitted?.Text, scriptingProvider, formPart, "OnSubmitted");

            // Return if any errors are returned from the OnSubmitted script
            if (ModelState.ErrorCount > 0)
            {
                return(Json(new VueFormSubmitResult(GetErrorDictionary(), serverScriptResult, GetDebugLogs(formPart))));
            }

            // _workflow manager is null if workflow feature is not enabled
            if (_workflowManager != null)
            {
                await _workflowManager.TriggerEventAsync(nameof(VueFormSubmittedEvent),
                                                         input : new { VueForm = form },
                                                         correlationId : form.ContentItemId
                                                         );
            }

            // Return if any errors are returned from the Workflow
            if (ModelState.ErrorCount > 0)
            {
                return(Json(new VueFormSubmitResult(GetErrorDictionary(), serverScriptResult, GetDebugLogs(formPart))));
            }

            // Handle the redirects with ajax requests.
            // 302 are equivalent to 301 in this case. No permanent redirect.
            // This can come from a scripting method or the HttpRedirect Workflow Task
            if (HttpContext.Response.StatusCode == 301 || HttpContext.Response.StatusCode == 302)
            {
                var returnValue = new { redirect = WebUtility.UrlDecode(HttpContext.Response.Headers["Location"]) };
                HttpContext.Response.Clear();
                return(Json(returnValue));
            }

            // This get's set by either the workflow's HttpRedirectTask or HttpResponseTask
            if (HttpContext.Items[WorkflowHttpResult.Instance] != null)
            {
                // Let the HttpResponseTask control the response. This will fail on the client if it's anything other than json
                return(new EmptyResult());
            }

            //try to get the message from the http context as set by the addSuccessMessage() scripting function
            var successMessage = string.Empty;

            if (HttpContext.Items[Constants.VueFormSuccessMessage] != null)
            {
                successMessage = (string)HttpContext.Items[Constants.VueFormSuccessMessage];
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(formPart.SuccessMessage?.Text))
                {
                    var formSuccessMessage = await _liquidTemplateManager.RenderStringAsync(formPart.SuccessMessage.Text, _htmlEncoder);

                    successMessage = await _shortcodeService.ProcessAsync(formSuccessMessage);
                }
            }

            return(Json(new VueFormSubmitResult(successMessage, serverScriptResult, GetDebugLogs(formPart))));
        }
Пример #11
0
        public async Task FilterAsync(ContentOptionsViewModel model, IQuery <ContentItem> query, IUpdateModel updater)
        {
            var user = _httpContextAccessor.HttpContext.User;
            var userNameIdentifier = user.FindFirstValue(ClaimTypes.NameIdentifier);

            if (!String.IsNullOrEmpty(model.DisplayText))
            {
                query.With <ContentItemIndex>(x => x.DisplayText.Contains(model.DisplayText));
            }

            switch (model.ContentsStatus)
            {
            case ContentsStatus.Published:
                query.With <ContentItemIndex>(x => x.Published);
                break;

            case ContentsStatus.Draft:
                query.With <ContentItemIndex>(x => x.Latest && !x.Published);
                break;

            case ContentsStatus.AllVersions:
                query.With <ContentItemIndex>(x => x.Latest);
                break;

            default:
                query.With <ContentItemIndex>(x => x.Latest);
                break;
            }

            var canListAllContent = await _authorizationService.AuthorizeAsync(user, Permissions.ListContent);

            // Filter the creatable types.
            if (!string.IsNullOrEmpty(model.SelectedContentType))
            {
                var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.SelectedContentType);
                if (contentTypeDefinition != null)
                {
                    // We display a specific type even if it's not listable so that admin pages
                    // can reuse the Content list page for specific types.
                    var contentItem = await _contentManager.NewAsync(contentTypeDefinition.Name);

                    contentItem.Owner = userNameIdentifier;

                    var hasContentListPermission = await _authorizationService.AuthorizeAsync(user, ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.ListContent.Name], contentTypeDefinition), contentItem);

                    if (hasContentListPermission)
                    {
                        query.With <ContentItemIndex>(x => x.ContentType == model.SelectedContentType);
                    }
                    else
                    {
                        query.With <ContentItemIndex>(x => x.ContentType == model.SelectedContentType && x.Owner == userNameIdentifier);
                    }
                }
            }
            else
            {
                var listableTypes            = new List <ContentTypeDefinition>();
                var authorizedContentTypes   = new List <ContentTypeDefinition>();
                var unauthorizedContentTypes = new List <ContentTypeDefinition>();

                foreach (var ctd in _contentDefinitionManager.ListTypeDefinitions())
                {
                    if (ctd.GetSettings <ContentTypeSettings>().Listable)
                    {
                        // We want to list the content item if the user can edit their own items at least.
                        // It might display content items the user won't be able to edit though.
                        var contentItem = await _contentManager.NewAsync(ctd.Name);

                        contentItem.Owner = userNameIdentifier;

                        var hasEditPermission = await _authorizationService.AuthorizeAsync(user, CommonPermissions.EditContent, contentItem);

                        if (hasEditPermission)
                        {
                            listableTypes.Add(ctd);
                        }

                        if (!canListAllContent)
                        {
                            var hasContentListPermission = await _authorizationService.AuthorizeAsync(user, ContentTypePermissionsHelper.CreateDynamicPermission(ContentTypePermissionsHelper.PermissionTemplates[CommonPermissions.ListContent.Name], ctd), contentItem);

                            if (hasContentListPermission)
                            {
                                authorizedContentTypes.Add(ctd);
                            }
                            else
                            {
                                unauthorizedContentTypes.Add(ctd);
                            }
                        }
                    }
                }

                if (authorizedContentTypes.Any() && !canListAllContent)
                {
                    query.With <ContentItemIndex>().Where(x => (x.ContentType.IsIn(authorizedContentTypes.Select(t => t.Name).ToArray())) || (x.ContentType.IsIn(unauthorizedContentTypes.Select(t => t.Name).ToArray()) && x.Owner == userNameIdentifier));
                }
                else
                {
                    query.With <ContentItemIndex>(x => x.ContentType.IsIn(listableTypes.Select(t => t.Name).ToArray()));

                    // If we set the ListContent permission
                    // to false we can only view our own content and
                    // we bypass the corresponding ContentsStatus by owned content filtering
                    if (!canListAllContent)
                    {
                        query.With <ContentItemIndex>(x => x.Owner == userNameIdentifier);
                    }
                    else
                    {
                        if (model.ContentsStatus == ContentsStatus.Owner)
                        {
                            query.With <ContentItemIndex>(x => x.Owner == userNameIdentifier);
                        }
                    }
                }
            }

            // Apply OrderBy filters.
            switch (model.OrderBy)
            {
            case ContentsOrder.Modified:
                query.With <ContentItemIndex>().OrderByDescending(x => x.ModifiedUtc);
                break;

            case ContentsOrder.Published:
                query.With <ContentItemIndex>().OrderByDescending(cr => cr.PublishedUtc);
                break;

            case ContentsOrder.Created:
                query.With <ContentItemIndex>().OrderByDescending(cr => cr.CreatedUtc);
                break;

            case ContentsOrder.Title:
                query.With <ContentItemIndex>().OrderBy(cr => cr.DisplayText);
                break;

            default:
                query.With <ContentItemIndex>().OrderByDescending(cr => cr.ModifiedUtc);
                break;
            }
            ;
        }