Example #1
0
        public async Task <IActionResult> Purge()
        {
            if (!await _authorizationService.AuthorizeAsync(User, MediaCachePermissions.ManageAssetCache))
            {
                return(Forbid());
            }

            if (_mediaFileStoreCache == null)
            {
                await _notifier.ErrorAsync(H["The asset cache feature is enabled, but a remote media store feature is not enabled, or not configured with appsettings.json."]);

                RedirectToAction(nameof(Index));
            }

            var hasErrors = await _mediaFileStoreCache.PurgeAsync();

            if (hasErrors)
            {
                await _notifier.ErrorAsync(H["Asset cache purged, with errors."]);
            }
            else
            {
                await _notifier.InformationAsync(H["Asset cache purged."]);
            }

            return(RedirectToAction(nameof(Index)));
        }
Example #2
0
        public async Task <IActionResult> Delete(string id)
        {
            var user = await _userManager.FindByIdAsync(id) as User;

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

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers, user))
            {
                return(Forbid());
            }

            var result = await _userManager.DeleteAsync(user);

            if (result.Succeeded)
            {
                await _notifier.SuccessAsync(H["User deleted successfully."]);
            }
            else
            {
                await _session.CancelAsync();

                await _notifier.ErrorAsync(H["Could not delete the user."]);

                foreach (var error in result.Errors)
                {
                    await _notifier.ErrorAsync(H[error.Description]);
                }
            }

            return(RedirectToAction(nameof(Index)));
        }
Example #3
0
        public async Task <IActionResult> Delete(string id)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRoles))
            {
                return(Forbid());
            }

            var currentRole = await _roleManager.FindByIdAsync(id);

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

            var result = await _roleManager.DeleteAsync(currentRole);

            if (result.Succeeded)
            {
                await _notifier.SuccessAsync(H["Role deleted successfully."]);
            }
            else
            {
                await _documentStore.CancelAsync();

                await _notifier.ErrorAsync(H["Could not delete this role."]);

                foreach (var error in result.Errors)
                {
                    await _notifier.ErrorAsync(H[error.Description]);
                }
            }

            return(RedirectToAction(nameof(Index)));
        }
Example #4
0
        public async Task <IActionResult> Import(IFormFile importedPackage)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.Import))
            {
                return(Forbid());
            }

            if (importedPackage != null)
            {
                var tempArchiveName   = Path.GetTempFileName() + Path.GetExtension(importedPackage.FileName);
                var tempArchiveFolder = PathExtensions.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                try
                {
                    using (var stream = new FileStream(tempArchiveName, FileMode.Create))
                    {
                        await importedPackage.CopyToAsync(stream);
                    }

                    if (importedPackage.FileName.EndsWith(".zip"))
                    {
                        ZipFile.ExtractToDirectory(tempArchiveName, tempArchiveFolder);
                    }
                    else if (importedPackage.FileName.EndsWith(".json"))
                    {
                        Directory.CreateDirectory(tempArchiveFolder);
                        System.IO.File.Move(tempArchiveName, Path.Combine(tempArchiveFolder, "Recipe.json"));
                    }
                    else
                    {
                        await _notifier.ErrorAsync(H["Only zip or json files are supported."]);

                        return(RedirectToAction(nameof(Index)));
                    }

                    await _deploymentManager.ImportDeploymentPackageAsync(new PhysicalFileProvider(tempArchiveFolder));

                    await _notifier.SuccessAsync(H["Deployment package imported."]);
                }
                finally
                {
                    if (System.IO.File.Exists(tempArchiveName))
                    {
                        System.IO.File.Delete(tempArchiveName);
                    }

                    if (Directory.Exists(tempArchiveFolder))
                    {
                        Directory.Delete(tempArchiveFolder, true);
                    }
                }
            }
            else
            {
                await _notifier.ErrorAsync(H["Please add a file to import."]);
            }

            return(RedirectToAction(nameof(Index)));
        }
Example #5
0
        public async Task <IActionResult> Delete(string name)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers))
            {
                return(Forbid());
            }

            var layers = await _layerService.LoadLayersAsync();

            var layer = layers.Layers.FirstOrDefault(x => String.Equals(x.Name, name));

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

            var widgets = await _layerService.GetLayerWidgetsMetadataAsync(c => c.Latest == true);

            if (!widgets.Any(x => String.Equals(x.Layer, name, StringComparison.OrdinalIgnoreCase)))
            {
                layers.Layers.Remove(layer);
                await _layerService.UpdateAsync(layers);

                await _notifier.SuccessAsync(H["Layer deleted successfully."]);
            }
            else
            {
                await _notifier.ErrorAsync(H["The layer couldn't be deleted: you must remove any associated widgets first."]);
            }

            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> PurgeAll()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps))
            {
                return(Forbid());
            }

            var hasErrors = await _sitemapCacheProvider.PurgeAllAsync();

            if (hasErrors)
            {
                await _notifier.ErrorAsync(H["Sitemap cache purged, with errors."]);
            }
            else
            {
                await _notifier.InformationAsync(H["Sitemap cache purged."]);
            }

            return(RedirectToAction(nameof(List)));
        }
        public async Task <IActionResult> Disable(string id)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants))
            {
                return(Forbid());
            }

            if (!_currentShellSettings.IsDefaultShell())
            {
                return(Forbid());
            }

            var shellSettings = _shellHost.GetAllSettings()
                                .Where(s => String.Equals(s.Name, id, StringComparison.OrdinalIgnoreCase))
                                .FirstOrDefault();

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

            if (String.Equals(shellSettings.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase))
            {
                await _notifier.ErrorAsync(H["You cannot disable the default tenant."]);

                return(RedirectToAction(nameof(Index)));
            }

            if (shellSettings.State != TenantState.Running)
            {
                await _notifier.ErrorAsync(H["You can only disable an Enabled tenant."]);

                return(RedirectToAction(nameof(Index)));
            }

            shellSettings.State = TenantState.Disabled;
            await _shellHost.UpdateShellSettingsAsync(shellSettings);

            return(RedirectToAction(nameof(Index)));
        }
Example #8
0
        public async Task <ActionResult> Execute(string basePath, string fileName)
        {
            if (!await _authorizationService.AuthorizeAsync(User, StandardPermissions.SiteOwner))
            {
                return(Forbid());
            }

            var features = await _shellFeaturesManager.GetAvailableFeaturesAsync();

            var recipes = await GetRecipesAsync(features);

            var recipe = recipes.FirstOrDefault(c => c.RecipeFileInfo.Name == fileName && c.BasePath == basePath);

            if (recipe == null)
            {
                await _notifier.ErrorAsync(H["Recipe was not found."]);

                return(RedirectToAction(nameof(Index)));
            }

            var environment = new Dictionary <string, object>();
            await _environmentProviders.OrderBy(x => x.Order).InvokeAsync((provider, env) => provider.PopulateEnvironmentAsync(env), environment, _logger);

            var executionId = Guid.NewGuid().ToString("n");

            // Set shell state to "Initializing" so that subsequent HTTP requests
            // are responded to with "Service Unavailable" while running the recipe.
            _shellSettings.State = TenantState.Initializing;

            try
            {
                await _recipeExecutor.ExecuteAsync(executionId, recipe, environment, CancellationToken.None);
            }
            finally
            {
                // Don't lock the tenant if the recipe fails.
                _shellSettings.State = TenantState.Running;
            }

            await _shellHost.ReleaseShellContextAsync(_shellSettings);

            await _notifier.SuccessAsync(H["The recipe '{0}' has been run successfully.", recipe.DisplayName]);

            return(RedirectToAction(nameof(Index)));
        }
Example #9
0
        public async Task <IActionResult> Edit(AdminNodeEditViewModel model)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
            {
                return(Forbid());
            }

            var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();

            var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, model.AdminMenuId);

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

            var treeNode = adminMenu.GetMenuItemById(model.AdminNodeId);

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

            var editor = await _displayManager.UpdateEditorAsync(treeNode, updater : _updateModelAccessor.ModelUpdater, isNew : false);

            if (ModelState.IsValid)
            {
                treeNode.Priority = model.Priority;
                treeNode.Position = model.Position;

                await _adminMenuService.SaveAsync(adminMenu);

                await _notifier.SuccessAsync(H["Admin node updated successfully."]);

                return(RedirectToAction(nameof(List), new { id = model.AdminMenuId }));
            }

            await _notifier.ErrorAsync(H["The admin node has validation errors."]);

            model.Editor = editor;

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #10
0
        public async Task <IActionResult> Edit(LayerRuleEditViewModel model)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers))
            {
                return(Forbid());
            }

            var layers = await _layerService.LoadLayersAsync();

            var layer = layers.Layers.FirstOrDefault(x => String.Equals(x.Name, model.Name));

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

            var condition = FindCondition(layer.LayerRule, model.ConditionId);

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

            var editor = await _displayManager.UpdateEditorAsync(condition, updater : _updateModelAccessor.ModelUpdater, isNew : false);

            if (ModelState.IsValid)
            {
                await _layerService.UpdateAsync(layers);

                await _notifier.SuccessAsync(H["Condition updated successfully."]);

                return(RedirectToAction(nameof(Edit), "Admin", new { name = model.Name }));
            }

            await _notifier.ErrorAsync(H["The condition has validation errors."]);

            model.Editor = editor;

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #11
0
        public async Task <IActionResult> Edit(EditSourceViewModel model)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageSitemaps))
            {
                return(Forbid());
            }

            var sitemap = await _sitemapManager.LoadSitemapAsync(model.SitemapId);

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

            var source = sitemap.SitemapSources.FirstOrDefault(x => String.Equals(x.Id, model.SitemapSourceId, StringComparison.OrdinalIgnoreCase));

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

            var editor = await _displayManager.UpdateEditorAsync(source, updater : _updateModelAccessor.ModelUpdater, isNew : false);

            if (ModelState.IsValid)
            {
                await _sitemapManager.UpdateSitemapAsync(sitemap);

                await _notifier.SuccessAsync(H["Sitemap source updated successfully."]);

                return(RedirectToAction("Display", "Admin", new { sitemapId = model.SitemapId }));
            }

            await _notifier.ErrorAsync(H["The sitemap source has validation errors."]);

            model.Editor = editor;

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #12
0
        public async Task <IActionResult> Edit(EditDeploymentPlanStepViewModel model)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan))
            {
                return(Forbid());
            }

            var deploymentPlan = await _session.GetAsync <DeploymentPlan>(model.DeploymentPlanId);

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

            var step = deploymentPlan.DeploymentSteps.FirstOrDefault(x => String.Equals(x.Id, model.DeploymentStepId, StringComparison.OrdinalIgnoreCase));

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

            var editor = await _displayManager.UpdateEditorAsync(step, updater : _updateModelAccessor.ModelUpdater, isNew : false);

            if (ModelState.IsValid)
            {
                _session.Save(deploymentPlan);

                await _notifier.SuccessAsync(H["Deployment plan step updated successfully."]);

                return(RedirectToAction("Display", "DeploymentPlan", new { id = model.DeploymentPlanId }));
            }

            await _notifier.ErrorAsync(H["The deployment plan step has validation errors."]);

            model.Editor = editor;

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #13
0
        public override async Task <IDisplayResult> UpdateAsync(ContentItem model, IUpdateModel updater)
        {
            var httpContext = _httpContextAccessor.HttpContext;
            var action      = (string)httpContext.Request.Form["submit.Save"] ?? httpContext.Request.Form["submit.Publish"];

            if (action?.StartsWith("user-task.", StringComparison.Ordinal) == true)
            {
                action = action.Substring("user-task.".Length);

                var availableActions = await GetUserTaskActionsAsync(model.ContentItemId);

                if (!availableActions.Contains(action))
                {
                    await _notifier.ErrorAsync(H["Not authorized to trigger '{0}'.", action]);
                }
                else
                {
                    var contentEvent = new ContentEventContext()
                    {
                        Name          = nameof(UserTaskEvent),
                        ContentType   = model.ContentType,
                        ContentItemId = model.ContentItemId
                    };

                    var input = new Dictionary <string, object>
                    {
                        { ContentEventConstants.UserActionInputKey, action },
                        { ContentEventConstants.ContentItemInputKey, model },
                        { ContentEventConstants.ContentEventInputKey, contentEvent }
                    };

                    await _workflowManager.TriggerEventAsync(nameof(UserTaskEvent), input, correlationId : model.ContentItemId);
                }
            }

            return(Edit(model));
        }
        public async Task <IActionResult> Execute(int id, string remoteInstanceId, string returnUrl)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.Export))
            {
                return(Forbid());
            }

            var deploymentPlan = await _session.GetAsync <DeploymentPlan>(id);

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

            var remoteInstance = await _service.GetRemoteInstanceAsync(remoteInstanceId);

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

            string archiveFileName;
            var    filename = deploymentPlan.Name.ToSafeName() + ".zip";

            using (var fileBuilder = new TemporaryFileBuilder())
            {
                archiveFileName = PathExtensions.Combine(Path.GetTempPath(), filename);

                var deploymentPlanResult = new DeploymentPlanResult(fileBuilder, new RecipeDescriptor());
                await _deploymentManager.ExecuteDeploymentPlanAsync(deploymentPlan, deploymentPlanResult);

                if (System.IO.File.Exists(archiveFileName))
                {
                    System.IO.File.Delete(archiveFileName);
                }

                ZipFile.CreateFromDirectory(fileBuilder.Folder, archiveFileName);
            }

            HttpResponseMessage response;

            try
            {
                using (var requestContent = new MultipartFormDataContent())
                {
                    requestContent.Add(new StreamContent(
                                           new FileStream(archiveFileName,
                                                          FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1, FileOptions.Asynchronous | FileOptions.SequentialScan)
                                           ),
                                       nameof(ImportViewModel.Content), Path.GetFileName(archiveFileName));
                    requestContent.Add(new StringContent(remoteInstance.ClientName), nameof(ImportViewModel.ClientName));
                    requestContent.Add(new StringContent(remoteInstance.ApiKey), nameof(ImportViewModel.ApiKey));

                    response = await _httpClient.PostAsync(remoteInstance.Url, requestContent);
                }

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    await _notifier.SuccessAsync(H["Deployment executed successfully."]);
                }
                else
                {
                    await _notifier.ErrorAsync(H["An error occurred while sending the deployment to the remote instance: \"{0} ({1})\"", response.ReasonPhrase, (int)response.StatusCode]);
                }
            }
            finally
            {
                System.IO.File.Delete(archiveFileName);
            }

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return(this.LocalRedirect(returnUrl, true));
            }

            return(RedirectToAction("Display", "DeploymentPlan", new { area = "OrchardCore.Deployment", id }));
        }
Example #15
0
        public async Task <IActionResult> Edit(EditShapePlacementViewModel viewModel, string submit, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManagePlacements))
            {
                return(Forbid());
            }

            ViewData["ReturnUrl"] = returnUrl;

            if (viewModel.Creating && await _placementsManager.GetShapePlacementsAsync(viewModel.ShapeType) != null)
            {
                // Prevent overriding existing rules on creation
                await _notifier.WarningAsync(H["Placement rules for \"{0}\" already exists. Please edit existing rule.", viewModel.ShapeType]);

                return(View(viewModel));
            }

            try
            {
                IEnumerable <PlacementNode> placementNodes = JsonConvert.DeserializeObject <PlacementNode[]>(viewModel.Nodes) ?? new PlacementNode[0];

                // Remove empty nodes
                placementNodes = placementNodes.Where(node => !IsEmpty(node));

                if (placementNodes.Any())
                {
                    // Save
                    await _placementsManager.UpdateShapePlacementsAsync(viewModel.ShapeType, placementNodes);

                    viewModel.Creating = false;

                    await _notifier.SuccessAsync(H["The \"{0}\" placement have been saved.", viewModel.ShapeType]);
                }
                else if (viewModel.Creating)
                {
                    await _notifier.WarningAsync(H["The \"{0}\" placement is empty.", viewModel.ShapeType]);

                    return(View(viewModel));
                }
                else
                {
                    // Remove if empty
                    await _placementsManager.RemoveShapePlacementsAsync(viewModel.ShapeType);

                    await _notifier.SuccessAsync(H["The \"{0}\" placement has been deleted.", viewModel.ShapeType]);
                }
            }
            catch (JsonReaderException jsonException)
            {
                await _notifier.ErrorAsync(H["An error occurred while parsing the placement<br/>{0}", jsonException.Message]);

                return(View(viewModel));
            }
            catch (Exception e)
            {
                await _notifier.ErrorAsync(H["An error occurred while saving the placement."]);

                _logger.LogError(e, "An error occurred while saving the placement.");
                return(View(viewModel));
            }

            if (submit != "SaveAndContinue")
            {
                return(RedirectToReturnUrlOrIndex(returnUrl));
            }

            return(View(viewModel));
        }
Example #16
0
        public async Task <ActionResult> EditPost(LuceneIndexSettingsViewModel model, string[] indexedContentTypes)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageIndexes))
            {
                return(Forbid());
            }

            ValidateModel(model);

            if (model.IsCreate)
            {
                if (_luceneIndexManager.Exists(model.IndexName))
                {
                    ModelState.AddModelError(nameof(LuceneIndexSettingsViewModel.IndexName), S["An index named {0} already exists.", model.IndexName]);
                }
            }
            else
            {
                if (!_luceneIndexManager.Exists(model.IndexName))
                {
                    ModelState.AddModelError(nameof(LuceneIndexSettingsViewModel.IndexName), S["An index named {0} doesn't exist.", model.IndexName]);
                }
            }

            if (!ModelState.IsValid)
            {
                model.Cultures = CultureInfo.GetCultures(CultureTypes.AllCultures)
                                 .Select(x => new SelectListItem {
                    Text = x.Name + " (" + x.DisplayName + ")", Value = x.Name
                }).Prepend(new SelectListItem {
                    Text = S["Any culture"], Value = "any"
                });
                model.Analyzers = _luceneAnalyzerManager.GetAnalyzers()
                                  .Select(x => new SelectListItem {
                    Text = x.Name, Value = x.Name
                });
                return(View(model));
            }

            if (model.IsCreate)
            {
                try
                {
                    var settings = new LuceneIndexSettings {
                        IndexName = model.IndexName, AnalyzerName = model.AnalyzerName, IndexLatest = model.IndexLatest, IndexedContentTypes = indexedContentTypes, Culture = model.Culture ?? ""
                    };

                    // We call Rebuild in order to reset the index state cursor too in case the same index
                    // name was also used previously.
                    await _luceneIndexingService.CreateIndexAsync(settings);
                }
                catch (Exception e)
                {
                    await _notifier.ErrorAsync(H["An error occurred while creating the index."]);

                    _logger.LogError(e, "An error occurred while creating an index.");
                    return(View(model));
                }

                await _notifier.SuccessAsync(H["Index <em>{0}</em> created successfully.", model.IndexName]);
            }
            else
            {
                try
                {
                    var settings = new LuceneIndexSettings {
                        IndexName = model.IndexName, AnalyzerName = model.AnalyzerName, IndexLatest = model.IndexLatest, IndexedContentTypes = indexedContentTypes, Culture = model.Culture ?? ""
                    };

                    await _luceneIndexingService.UpdateIndexAsync(settings);
                }
                catch (Exception e)
                {
                    await _notifier.ErrorAsync(H["An error occurred while editing the index."]);

                    _logger.LogError(e, "An error occurred while editing an index.");
                    return(View(model));
                }

                await _notifier.SuccessAsync(H["Index <em>{0}</em> modified successfully, <strong>please consider doing a rebuild on the index.</strong>", model.IndexName]);
            }

            return(RedirectToAction(nameof(Index)));
        }
Example #17
0
        public async Task <IActionResult> List(ContentOptions options, PagerParameters pagerParameters)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
            {
                return(Forbid());
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            var adminMenuList = (await _adminMenuService.GetAdminMenuListAsync()).AdminMenu;

            if (!string.IsNullOrWhiteSpace(options.Search))
            {
                adminMenuList = adminMenuList.Where(x => x.Name.Contains(options.Search, StringComparison.OrdinalIgnoreCase)).ToList();
            }

            var count = adminMenuList.Count();

            var startIndex = pager.GetStartIndex();
            var pageSize   = pager.PageSize;
            IEnumerable <Models.AdminMenu> results = new List <Models.AdminMenu>();

            //todo: handle the case where there is a deserialization exception on some of the presets.
            // load at least the ones without error. Provide a way to delete the ones on error.
            try
            {
                results = adminMenuList
                          .Skip(startIndex)
                          .Take(pageSize)
                          .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error when retrieving the list of admin menus.");
                await _notifier.ErrorAsync(H["Error when retrieving the list of admin menus."]);
            }

            // Maintain previous route data when generating page links
            var routeData = new RouteData();

            routeData.Values.Add("Options.Search", options.Search);

            var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData);

            var model = new AdminMenuListViewModel
            {
                AdminMenu = results.Select(x => new AdminMenuEntry {
                    AdminMenu = x
                }).ToList(),
                Options = options,
                Pager   = pagerShape
            };

            model.Options.ContentsBulkAction = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove)
                }
            };

            return(View(model));
        }