public async Task <IActionResult> Delete(string id)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
            {
                return(Unauthorized());
            }

            var user = await _userManager.FindByIdAsync(id) as User;

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

            var result = await _userManager.DeleteAsync(user);

            if (result.Succeeded)
            {
                _notifier.Success(TH["User deleted successfully"]);
            }
            else
            {
                _session.Cancel();

                _notifier.Error(TH["Could not delete the user"]);

                foreach (var error in result.Errors)
                {
                    _notifier.Error(TH[error.Description]);
                }
            }

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #2
0
        public async Task <IActionResult> Purge()
        {
            if (!await _authorizationService.AuthorizeAsync(User, MediaCachePermissions.ManageAssetCache))
            {
                return(Forbid());
            }

            if (_mediaFileStoreCache == null)
            {
                _notifier.Error(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)
            {
                _notifier.Error(H["Asset cache purged, with errors."]);
            }
            else
            {
                _notifier.Information(H["Asset cache purged."]);
            }

            return(RedirectToAction(nameof(Index)));
        }
        public override IEnumerable <TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel)
        {
            // working on GDPRPart
            if (builder.Name != "GDPRPart")
            {
                yield break;
            }

            var vm = new GDPRPartTypeSchedulingSettingsViewModel();

            if (updateModel.TryUpdateModel(vm, "GDPRPartTypeSchedulingSettingsViewModel", null, null))
            {
                var ok = true;
                if (vm.Settings.ScheduleAnonymization && vm.Settings.AnonymizationDaysToWait <= 0)
                {
                    // days must be positive
                    _notifier.Error(T("Days to wait before anonymization must be greater than zero. Scheduler configuration failed."));
                    ok = false;
                }
                if (vm.Settings.ScheduleErasure && vm.Settings.ErasureDaysToWait <= 0)
                {
                    // days must be positive
                    _notifier.Error(T("Days to wait before erasure must be greater than zero. Scheduler configuration failed."));
                    ok = false;
                }
                if (ok)
                {
                    var settings = vm.Settings;
                    GDPRPartTypeSchedulingSettings.SetValues(builder, settings);
                    // update scheduled tasks
                    _GDPRScheduleManager.UpdateSchedule(builder.TypeName, settings);
                }
            }
        }
Beispiel #4
0
        public async Task <IActionResult> Disable(string id)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants))
            {
                return(Unauthorized());
            }

            if (!IsDefaultShell())
            {
                return(Unauthorized());
            }

            var shellContext = GetShells()
                               .Where(x => String.Equals(x.Settings.Name, id, StringComparison.OrdinalIgnoreCase))
                               .FirstOrDefault();

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

            var shellSettings = shellContext.Settings;

            if (shellSettings.State != TenantState.Running)
            {
                _notifier.Error(H["You can only disable a Running shell."]);
            }

            shellSettings.State = TenantState.Disabled;
            _orchardHost.UpdateShellSettings(shellSettings);

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #5
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)
            {
                _notifier.Success(H["Role deleted successfully"]);
            }
            else
            {
                _session.Cancel();

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

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

            return(RedirectToAction(nameof(Index)));
        }
        public async Task <ActionResult> Create([Bind(Include = "Id,EmployeeId,FirstName,LastName,PrimaryEmail,PhoneNumber,IsActive")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new System.Uri(EmployeePortalApiurl);

                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpRequestMessage request = CreateRequest(HttpMethod.Post, new System.Uri(EmployeePortalApiurl + "api/Employee/AddEmployee"), employee);
                    string             content = JsonConvert.SerializeObject(employee);
                    request.Content = new StringContent(content);
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    HttpResponseMessage Response = await client.SendAsync(request);

                    if (Response.IsSuccessStatusCode)
                    {
                        var ResultSet = Response.Content.ReadAsStringAsync().Result;
                        employee = JsonConvert.DeserializeObject <Employee>(ResultSet);
                        notifier.Success("Employee Saved Sucessfully..");
                    }
                    else
                    {
                        notifier.Error("There was a problem while Employee Saving..");
                    }
                    return(View(employee));
                }
            }
            return(RedirectToAction("Index"));
        }
        public bool CreateLoyalzooAccountFromPart(int partId)
        {
            try
            {
                ContentItem part = _contentManager.Get(partId);

                IUser            userPart     = part.As <IUser>();
                LoyalzooUserPart loyalzooPart = part.As <LoyalzooUserPart>();

                if (userPart != null && loyalzooPart != null)
                {
                    APIResult createResult = _fidelityService.CreateLoyalzooAccount(loyalzooPart, userPart.UserName, userPart.Email);

                    if (createResult.success)
                    {
                        return(true);
                    }
                    else
                    {
                        _notifier.Error(T("Registration failed: {0}", createResult.message));
                    }
                }
                else
                {
                    _notifier.Error(T("The provided part cannot be used for registration."));
                }

                return(false);
            }
            catch (Exception e)
            {
                _notifier.Error(T("Unable to register: {0}", e.Message));
                return(false);
            }
        }
        public ActionResult Create(int id, string returnUrl)
        {
            var model = Services.ContentManager.Create <ContactPart>("Contact");
            var form  = Services.ContentManager.Get(id);

            if (InvalidForm(form))
            {
                _notifier.Error(T("Form submission was not from a valid source"));
                return(this.RedirectLocal(returnUrl, "~/"));
            }

            var contactForm = form.Parts.FirstOrDefault(p => p is ContactFormPart);

            TryUpdateModel(model, new[] { "Company", "CurrentWebsite", "Email", "Message", "Name", "Phone", "Topic" });

            if (ModelState.IsValid)
            {
                var contact = _contactService.MakeContact(model.Record);
                _messenger.Send(contactForm.ContentItem.Record, MessageTypes.ContactRequest, "email", mapProperties(contact));
                _notifier.Information(T("Thanks for your inquiry, someone will respond to you shortly.")); // TODO: great place for a setting
            }
            else
            {
                notifyUserOfErrors(ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage));
                populateTempDataWithViewModelValues(model);
            }

            return(this.RedirectLocal(returnUrl, "~/"));
        }
Beispiel #9
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
                    {
                        _notifier.Error(H["Only zip or json files are supported."]);

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

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

                    _notifier.Success(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
            {
                _notifier.Error(H["Please add a file to import."]);
            }

            return(RedirectToAction(nameof(Index)));
        }
        public ActionResult Index()
        {
            _notifier.Information(T("Test information"));
            _notifier.Information(T("Test information 2"));
            _notifier.Error(T("Test error"));
            _notifier.Warning(T("Test warning"));
            _notifier.Error(T("Test error"));
            _notifier.Information(T("Test information"));

            return(Redirect("~/"));
        }
        protected override DriverResult Editor(ReCaptchaPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var workContext = _workContextAccessor.GetContext();
            var settings    = workContext.CurrentSite.As <ReCaptchaSettingsPart>();

            // don't display the part in the admin
            if (AdminFilter.IsApplied(workContext.HttpContext.Request.RequestContext))
            {
                return(null);
            }

            if (settings.TrustAuthenticatedUsers && workContext.CurrentUser != null)
            {
                return(null);
            }

            var context = workContext.HttpContext;

            try {
                var result = ExecuteValidateRequest(
                    settings.PrivateKey,
                    context.Request.ServerVariables["REMOTE_ADDR"],
                    context.Request.Form["g-recaptcha-response"]
                    );

                ReCaptchaPartResponseModel responseModel = _jsonConverter.Deserialize <ReCaptchaPartResponseModel>(result);

                if (!responseModel.Success)
                {
                    foreach (var errorCode in responseModel.ErrorCodes)
                    {
                        if (errorCode == "missing-input-response")
                        {
                            updater.AddModelError("", T("Please prove that you are not a bot."));
                            _notifier.Error(T("Please prove that you are not a bot."));
                        }
                        else
                        {
                            Logger.Information("An error occurred while submitting a reCaptcha: " + errorCode);
                            updater.AddModelError("", T("An error occurred while submitting a reCaptcha."));
                            _notifier.Error(T("An error occurred while submitting a reCaptcha."));
                        }
                    }
                }
            }
            catch (Exception e) {
                Logger.Error(e, "An unexcepted error occurred while submitting a reCaptcha.");
                updater.AddModelError("", T("There was an error while validating the Captcha."));
                _notifier.Error(T("There was an error while validating the Captcha."));
            }

            return(Editor(part, shapeHelper));
        }
        public static void Error(this Controller controller,
            Exception exception,
            LocalizedString localizedString,
            ILogger logger,
            INotifier notifier) {

            logger.Error(exception, localizedString.ToString());
            notifier.Error(localizedString);

            for (Exception innerException = exception; innerException != null ; innerException = innerException.InnerException) {
                notifier.Error(new LocalizedString(innerException.Message));
            }
        }
        public CategoryViewModel Category(CategoryInputModel inputModel)
        {
            CategoryViewModel viewModel = new CategoryViewModel();

            //initialize the dropdownlist values
            string ex;
            var    performanceCounterCategories = _performanceMonitorService.CategoryNames(out ex).ToList();

            if (ex == string.Empty)
            {
                var categoryList = performanceCounterCategories.Select(c => new SelectListItem
                {
                    Text  = c.ToString(),
                    Value = c.ToString()
                });

                viewModel.Accessible   = true;
                viewModel.CategoryList = new SelectList(categoryList, "Value", "Text", inputModel.CategoryName);
                return(viewModel);
            }
            else
            {
                _notifier.Error(T("Error: Not able to load the categories. Exception: {0} ", ex));
                viewModel.Accessible = false;
                return(viewModel);
            }
        }
Beispiel #14
0
 private void RaiseNotification(Exception exception)
 {
     if (_notifier == null || _authorizer.Value == null)
     {
         return;
     }
     if (exception is CoeveryException)
     {
         _notifier.Error((exception as CoeveryException).LocalizedMessage);
     }
     else if (_authorizer.Value.Authorize(StandardPermissions.SiteOwner))
     {
         _notifier.Error(T(exception.Message));
     }
 }
Beispiel #15
0
        public ActionResult Search(string q = "")
        {
            q = q.Trim();

            if (string.IsNullOrEmpty(q))
            {
                return(Redirect(Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : Url.Content("~/")));
            }

            PagedList <ISearchHit> searchHits;

            try
            {
                searchHits = searchService.Query(q, WorkContext.CurrentCultureCode, 0, 20);
            }
            catch (Exception x)
            {
                string message = string.Format(
                    T(KoreWebLocalizableStrings.Indexing.InvalidSearchQuery),
                    x.GetBaseException().Message);

                Logger.Error(message);
                notifier.Error(message);
                searchHits = new PagedList <ISearchHit>(new ISearchHit[] { });
            }

            ViewBag.Title = T(KoreWebLocalizableStrings.General.Search);
            ViewBag.Query = q;
            return(View("Kore.Web.Areas.Admin.Indexing.Views.Search.Results", searchHits));
        }
        public async Task <IActionResult> Export(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var workflowType = await _session.GetAsync <WorkflowType>(id.Value);

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

            var query = _session.Query <Workflow, WorkflowIndex>(x => x.WorkflowTypeId == workflowType.WorkflowTypeId)
                        .OrderByDescending(x => x.CreatedUtc);

            var instances = await query.ListAsync();

            try
            {
                return(File(
                           await _exportService.GetExportFileAsStreamAsync(instances),
                           "text/csv",
                           $"{workflowType.Name}-Export-{DateTime.UtcNow:dd-MM-yyyy-HHmm}.csv"
                           ));
            }
            catch (Exception e)
            {
                _notifier.Error(TH["Error creating export file, please try again."]);
                _logger.LogError(e, "Error creating file for Workflow Export");
                return(RedirectToAction("Preview", new { id }));
            }
        }
Beispiel #17
0
        public override IEnumerable <TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel)
        {
            // we have to do stuff only if the type has a GDPRPart, and we are not processing
            // the GDPRPart right now
            if (builder.Name == "GDPRPart")
            {
                yield break;
            }

            var typeDefinition = _contentDefinitionManager.GetTypeDefinition(builder.TypeName);

            if (!typeDefinition.Parts.Any(ctpd =>
                                          ctpd.PartDefinition.Name == "GDPRPart"))
            {
                yield break;
            }

            // If the update fails for any part, it will be marked as failed for all of them, because the
            // UpdateModel will contain errors. The issue is of course with the dictionaries that contain
            // the Property-Value pairs for the handlers that use reflection.
            var vm = new GDPRPartPartSettingsViewModel();

            if (updateModel.TryUpdateModel(vm, "GDPRPartPartSettingsViewModel", null, null))
            {
                var settings = vm.Settings;
                GDPRPartPartSettings.SetValues(builder, settings);
            }
            else
            {
                _notifier.Error(T("There was an issue updating the GDPR configuration for {0}.", builder.Name));
                yield break;
            }
        }
Beispiel #18
0
        public ActionResult PromoteVersion(int id, int versionId)
        {
            var versionToPromote = _contentManager.Get(id, VersionOptions.Number(versionId));

            if (versionToPromote == null)
            {
                return(HttpNotFound());
            }

            if (!_authorizer.Authorize(Orchard.Core.Contents.Permissions.EditContent, versionToPromote))
            {
                return(new HttpUnauthorizedResult());
            }

            var newVersionNumber = _versionManager.BuildNewContentItemVersion(versionToPromote);

            if (newVersionNumber == 0)
            {
                _notifier.Error(T("Version {0} of this content CANNOT be promoted to latest, as this content is in a Read Only state", versionId));
            }
            else
            {
                _notifier.Information(T("Version {0} of this content has been promoted to latest (draft) as version {1}", versionId, newVersionNumber));
            }

            return(RedirectToAction("Edit", "Admin", new { area = "", id = id }));
        }
Beispiel #19
0
        private void UpdateGroup(ExtendedUsersGroupsRecord singleRecord)
        {
            var record        = _extendedUsersGroupsRepository.Get(o => o.Id.Equals(singleRecord.Id));
            var inErrorGroups = new List <string>();

            if (record != null)
            {
                _extendedUsersGroupsRepository.Update(singleRecord);
            }
            else
            {
                if (!string.IsNullOrEmpty(singleRecord.GroupName))
                {
                    var groupsToCreate = singleRecord.GroupName.Split(new string[] { "||" }, System.StringSplitOptions.RemoveEmptyEntries);
                    foreach (var groupToCreate in groupsToCreate)
                    {
                        var groupRecordToCreate = new ExtendedUsersGroupsRecord {
                            GroupName = groupToCreate,
                        };
                        try {
                            _extendedUsersGroupsRepository.Create(groupRecordToCreate);
                            _extendedUsersGroupsRepository.Flush();
                        } catch {
                            inErrorGroups.Add(groupRecordToCreate.GroupName);
                        }
                    }
                }
            }

            if (inErrorGroups.Count() > 0)
            {
                _notifier.Error(T("Some groups cannot be inserted. {0}", String.Join(",", inErrorGroups)));
            }
        }
 public async Task RunApiInternal(Task task, Action onSuccessCallback)
 {
     try
     {
         await task;
         onSuccessCallback?.Invoke();
     }
     catch (ApiException e)
     {
         notifier.Error(JObject.Parse(e.Content).Value <string>("status"));
     }
     catch (HttpRequestException httpRequestException)
     {
         notifier.Error(httpRequestException.InnerException?.Message);
     }
 }
Beispiel #21
0
        public int Create()
        {
            try {
                ContentDefinitionManager.StoreTypeDefinition(
                    new ContentTypeDefinition(Common.PipelineConfigurationName, "Pipeline")
                    );

                ContentDefinitionManager.AlterTypeDefinition(Common.PipelineConfigurationName, cfg => cfg
                                                             .Creatable()
                                                             .WithSetting("Description", "Transformalize Pipeline")
                                                             .WithPart(Common.PipelineConfigurationName + "Part")
                                                             .WithPart("CommonPart")
                                                             .WithPart("TitlePart")
                                                             .WithPart("IdentityPart")
                                                             .WithPart("ContentPermissionsPart", builder => builder
                                                                       .WithSetting("ContentPermissionsPartSettings.View", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.Publish", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.Edit", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.Delete", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.Preview", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.ViewOwn", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.PublishOwn", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.EditOwn", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.DeleteOwn", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.PreviewOwn", "Administrator")
                                                                       .WithSetting("ContentPermissionsPartSettings.DisplayedRoles", "Authenticated,Anonymous")
                                                                       )
                                                             );
                return(1);
            } catch (Exception e) {
                Logger.Error(e.Message);
                _notifier.Error(T(e.Message));
            }
            return(0);
        }
        public ActionResult RepopulateFeedSyncProfileItems(int id, string returnUrl)
        {
            var feedSyncProfile = _contentManager.Get(id);

            if (!_authorizer.Authorize(Permissions.EditContent, feedSyncProfile))
            {
                return(new HttpUnauthorizedResult(T("You are not allowed to repopulate feed sync profiles.").Text));
            }

            if (feedSyncProfile == null || feedSyncProfile.ContentType != ContentTypes.FeedSyncProfile)
            {
                _notifier.Error(T("Scheduling the repopulation failed."));
            }
            else
            {
                var feedSyncProfilePart = feedSyncProfile.As <FeedSyncProfilePart>();
                feedSyncProfilePart.SuccesfulInit = false;
                feedSyncProfilePart.LatestCreatedItemModificationDate = default(DateTime);

                _notifier.Information(T("Repopulation was successfully scheduled."));
            }

            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = "~/";
            }

            return(this.RedirectLocal(returnUrl));
        }
        protected override DriverResult Editor(ShareBarSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (!_authorizationService.TryCheckAccess(Permissions.EditSettings, _authenticationService.GetAuthenticatedUser(), part))
            {
                return(null);
            }

            // Verifico di provenire dalla pagina dei settings
            var request = _services.WorkContext.HttpContext.Request.RequestContext.RouteData;
            var fullAreaControllerAction = string.Format("{0}/{1}/{2}/{3}", request.Values["area"].ToString(), request.Values["controller"], request.Values["action"], request.Values["groupInfoId"]);

            if (!fullAreaControllerAction.Equals("settings/admin/index/", System.StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }

            if (updater.TryUpdateModel(part, Prefix, null, null))
            {
                _notifier.Information(T("Content sharing settings updated successfully"));
            }
            else
            {
                _notifier.Error(T("Error during content sharing settings update!"));
            }
            return(Editor(part, shapeHelper));
        }
        public ActionResult Create(string returnUrl)
        {
            if (!Services.Authorizer.Authorize(Permissions.AddComment, T("Couldn't add comment")))
            {
                return(this.RedirectLocal(returnUrl, "~/"));
            }

            var viewModel = new CommentsCreateViewModel();

            TryUpdateModel(viewModel);

            var context = new CreateCommentContext {
                Author      = viewModel.Name,
                CommentText = viewModel.CommentText,
                Email       = viewModel.Email,
                SiteName    = viewModel.SiteName,
                CommentedOn = viewModel.CommentedOn
            };


            if (ModelState.IsValid)
            {
                if (!String.IsNullOrEmpty(context.SiteName) && !context.SiteName.StartsWith("http://") && !context.SiteName.StartsWith("https://"))
                {
                    context.SiteName = "http://" + context.SiteName;
                }

                CommentPart commentPart = _commentService.CreateComment(context, Services.WorkContext.CurrentSite.As <CommentSettingsPart>().Record.ModerateComments);

                if (commentPart.Record.Status == CommentStatus.Pending)
                {
                    // if the user who submitted the comment has the right to moderate, don't make this comment moderated
                    if (Services.Authorizer.Authorize(Permissions.ManageComments))
                    {
                        commentPart.Record.Status = CommentStatus.Approved;
                    }
                    else
                    {
                        Services.Notifier.Information(T("Your comment will appear after the site administrator approves it."));
                    }
                }
            }
            else
            {
                foreach (var error in ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage))
                {
                    _notifier.Error(T(error));
                }
            }

            if (!ModelState.IsValid)
            {
                TempData["CreateCommentContext.Name"]        = context.Author;
                TempData["CreateCommentContext.CommentText"] = context.CommentText;
                TempData["CreateCommentContext.Email"]       = context.Email;
                TempData["CreateCommentContext.SiteName"]    = context.SiteName;
            }

            return(this.RedirectLocal(returnUrl, "~/"));
        }
        public ActionResult DeleteTerritoryInternal(int id)
        {
            if (!_authorizer.Authorize(TerritoriesPermissions.ManageInternalTerritories))
            {
                return(new HttpUnauthorizedResult());
            }

            var tir = _territoryRepositoryService.GetTerritoryInternal(id);

            if (tir == null)
            {
                return(HttpNotFound());
            }

            var territoryName = tir.Name;

            if (tir.TerritoryParts.Any())
            {
                // There are connected TerritoryParts. Don't delete the TerritoryInternalRecord
                _notifier.Error(
                    T("\"{0}\" cannot be deleted because it still has {1} connected parts (you can find them in its editor).",
                      territoryName, tir.TerritoryParts.Count));

                return(RedirectToAction("TerritoriesIndex"));
            }

            _territoryRepositoryService.Delete(id);

            _notifier.Information(T("\"{0}\" has been deleted.", territoryName));

            return(RedirectToAction("TerritoriesIndex"));
        }
Beispiel #26
0
 private void NotifyOfException(Exception qex)
 {
     if (qex.InnerException != null)
     {
         _notifier.Error(T("{0}<br/><br/>{1}<br/><br/>{2}",
                           qex.Message,
                           qex.InnerException.Message,
                           qex.StackTrace.Replace(Environment.NewLine, "<br/>")));
     }
     else
     {
         _notifier.Error(T("{0}<br/><br/>{1}",
                           qex.Message,
                           qex.StackTrace.Replace(Environment.NewLine, "<br/>")));
     }
 }
Beispiel #27
0
        public bool Authorize(Permission permission, IContent content, LocalizedString message)
        {
            // gets the current active directory user.
            var user = new ActiveDirectoryUser();

            // attempts to authorize the active directory user based on their roles
            // and the permissions that their associated roles have.
            if (_authorizationService.TryCheckAccess(permission, user, content))
            {
                // if the user is attempting to access the admin area then they must have
                // a UserPartRecord associated to their username.
                if (permission.Name == AdminPanelAccess)
                {
                    CreateUserForActiveDirectoryUserIfNotExists(user);
                }

                return(true);
            }

            if (message != null)
            {
                _notifier.Error(T("{0}. Current user, {2}, does not have {1} permission.",
                                  message, permission.Name, user.UserName));
            }

            return(false);
        }
        public async Task <IActionResult> Delete(string name)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers))
            {
                return(Unauthorized());
            }

            var layers = await _layerService.GetLayersAsync();

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

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

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

            if (!widgets.Any(x => String.Equals(x.Layer, name, StringComparison.OrdinalIgnoreCase)))
            {
                layers.Layers.Remove(layer);
                _notifier.Success(H["Layer deleted successfully."]);
            }
            else
            {
                _notifier.Error(H["The layer couldn't be deleted: you must remove any associated widgets first."]);
            }

            return(RedirectToAction("Index"));
        }
Beispiel #29
0
        public ActionResult ExternalLogOn(string returnUrl)
        {
            AuthenticationResult result = _orchardOpenAuthWebSecurity.VerifyAuthentication(Url.OpenAuthLogOn(returnUrl));

            if (!result.IsSuccessful)
            {
                _notifier.Error(T("Your authentication request failed."));

                return(new RedirectResult(Url.LogOn(returnUrl)));
            }

            if (_orchardOpenAuthWebSecurity.Login(result.Provider, result.ProviderUserId))
            {
                _notifier.Information(T("You have been logged using your {0} account.", result.Provider));

                return(this.RedirectLocal(returnUrl));
            }

            var authenticatedUser = _authenticationService.GetAuthenticatedUser();

            if (authenticatedUser != null)
            {
                // If the current user is logged in add the new account
                _orchardOpenAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId,
                                                                  authenticatedUser);

                _notifier.Information(T("Your {0} account has been attached to your local account.", result.Provider));

                return(this.RedirectLocal(returnUrl));
            }

            if (_openAuthMembershipServices.CanRegister())
            {
                var newUser =
                    _openAuthMembershipServices.CreateUser(new OpenAuthCreateUserParams(result.UserName,
                                                                                        result.Provider,
                                                                                        result.ProviderUserId,
                                                                                        result.ExtraData));

                _notifier.Information(
                    T("You have been logged in using your {0} account. We have created a local account for you with the name '{1}'", result.Provider, newUser.UserName));

                _orchardOpenAuthWebSecurity.CreateOrUpdateAccount(result.Provider,
                                                                  result.ProviderUserId,
                                                                  newUser);

                _authenticationService.SignIn(newUser, false);

                return(this.RedirectLocal(returnUrl));
            }

            string loginData = _orchardOpenAuthWebSecurity.SerializeProviderUserId(result.Provider,
                                                                                   result.ProviderUserId);

            ViewBag.ProviderDisplayName = _orchardOpenAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;

            return(new RedirectResult(Url.LogOn(returnUrl, result.UserName, HttpUtility.UrlEncode(loginData))));
        }
Beispiel #30
0
 protected override DriverResult Editor(CustomCss part, IUpdateModel updater, dynamic shapeHelper)
 {
     if (!updater.TryUpdateModel(part, Prefix, null, null))
     {
         _notifier.Error(T("Error during CustomCss update."));
     }
     return(Editor(part, shapeHelper));
 }
        private void RestoreContentItems(IEnumerable <int> selectedContentItems)
        {
            var contentItems = _recycleBin.GetMany(selectedContentItems);

            foreach (var contentItem in contentItems)
            {
                var contentItemTitle = _contentManager.GetItemMetadata(contentItem).DisplayText;
                if (!_authorizer.Authorize(Core.Contents.Permissions.EditContent, contentItem))
                {
                    _notifier.Error(T("You need the EditContent permission to restore <strong>{0}</strong>.", contentItemTitle));
                    continue;
                }

                _recycleBin.Restore(contentItem);
                _notifier.Information(T("&quot;{0}&quot; has been restored.", contentItemTitle));
            }
        }