public async Task <IActionResult> EditItem(IFormCollection request) { try { if (string.IsNullOrEmpty(request.Str("navitem"))) { return(BadRequest(new ResponseHelper("Something went wrong, please try again later", "No nav-item data was sent"))); } NavItem updatedItem = JsonConvert.DeserializeObject <NavItem>(request.Str("navitem")); // If ID is zero, this is a new item, use the AddItem method if (updatedItem.Id == 0) { return(await AddItem(request)); } // Check whether an existing navitem has that id NavItem originalItem = await _Db.NavItems.AsNoTracking().FirstOrDefaultAsync((item) => item.Id == updatedItem.Id); if (originalItem == null) { return(NotFound(new ResponseHelper("Something went wrong, please try again later."))); } // Delete any old drop down links for the nav item List <NavItemPage> dropdowns = await _Db.NavItemPages.Where(n => n.NavItemId == updatedItem.Id).ToListAsync(); _Db.RemoveRange(dropdowns); await _Db.SaveChangesAsync(); // Mark item as updated _Db.Update(updatedItem); _Db.Entry(updatedItem).Property(i => i.OrderIndex).IsModified = false; _Db.Entry(updatedItem).Property(i => i.Section).IsModified = false; // Add new dropdowns, if any if (updatedItem.NavItemPages != null) { // Add order index to items before saving for (int i = 0; i < updatedItem.NavItemPages.Count; i++) { updatedItem.NavItemPages[i].OrderIndex = i; } _Db.AddRange(updatedItem.NavItemPages); } // Write changes to database await _Db.SaveChangesAsync(); return(Ok(updatedItem.Id)); } catch (Exception ex) { _Logger.LogError("Error updating navlink", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later.", ex.Message))); } }
public async Task <IActionResult> UpdateAccount(int id, IFormCollection request) { try { //bool sendStatusEmail = false; Account account = await _Db.Accounts.FindAsync(id); // Non Developers cannot alter developer accounts if (account.Developer && !_Db.Accounts.Find(User.AccountId()).Developer) { return(BadRequest("You cannot change the settings of a developer's account")); } account.Name = request.Str("name"); account.Email = request.Str("email"); account.PhoneNumber = request.Str("phoneNumber"); await _Db.SaveChangesAsync(); _Logger.LogInformation("Information updated for account belonging to {0}", account.Name); return(Ok($"{account.Name}'s account has been updated")); } catch (Exception ex) { _Logger.LogError("Error updating account (Id: {0}): {1}", id, ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("Something went wrong, please try again")); } }
public async Task <IActionResult> AddItem(IFormCollection request) { try { if (string.IsNullOrEmpty(request.Str("navitem"))) { return(BadRequest(new ResponseHelper("Something went wrong, please try again later", "No nav-item data was sent"))); } NavItem newItem = JsonConvert.DeserializeObject <NavItem>(request.Str("navitem")); // Give an order index that places this at the end of the list, for its section newItem.OrderIndex = await _Db.NavItems.Where(n => n.Section == newItem.Section).DefaultIfEmpty().MaxAsync(m => m.OrderIndex) + 1; await _Db.AddAsync(newItem); // Add new dropdowns, if any if (newItem.NavItemPages != null) { await _Db.AddRangeAsync(newItem.NavItemPages); } await _Db.SaveChangesAsync(); return(Ok(newItem.Id)); } catch (Exception ex) { _Logger.LogError("Error creating new navlink", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later.", ex.Message))); } }
public async Task <IActionResult> Update(int id, IFormCollection request) { Notice n = await _Database.Notices.FindAsync(id);; try { Enum.TryParse(request.Str("noticeboard"), out Noticeboard noticeboard); n.Title = request.Str("title"); n.Noticeboard = noticeboard; n.LongDesc = request.Str("long_desc"); n.Urgent = request.Bool("urgent") ? 1 : 0; n.Active = request.Bool("active"); await _Database.SaveChangesAsync(); return(Ok($"Notice \"{n.Title}\" updated.")); } catch (Exception ex) { _Logger.LogError("Error updating notice: {0}", ex.Message); _Logger.LogTrace(ex.Message); return(BadRequest(new ResponseHelper($"Error updating \"{n.Title}\".", ex.Message))); } }
public async Task <IActionResult> Create(IFormCollection request) { try { Enum.TryParse(request.Str("noticeboard"), out Noticeboard noticeboard); Notice n = new Notice { Title = request.Str("title"), Noticeboard = noticeboard, LongDesc = request.Str("long_desc"), Urgent = request.Bool("urgent") ? 1 : 0, Active = request.Bool("active"), }; await _Database.AddAsync(n); await _Database.SaveChangesAsync(); return(Ok($"Notice \"{n.Title}\" has been issued.")); } catch (Exception ex) { _Logger.LogError("Error saving notice: {0}", ex.Message); _Logger.LogTrace(ex.StackTrace); return(BadRequest(new ResponseHelper("Error issuing the notice, try again later.", ex.Message))); } }
public async Task <IActionResult> Password(IFormCollection request) { try { Account account = await _Db.Accounts.FindAsync(User.AccountId()); // Old passwords do not match if (_Hasher.VerifyHashedPassword(account, account.Password, request.Str("current")) != PasswordVerificationResult.Success) { return(BadRequest(new ResponseHelper("Your current password was not correct", "<Hidden for Security>"))); } // New passwords do not match if (request.Str("new") != request.Str("confirm")) { return(BadRequest(new ResponseHelper("Your new password and confirmation password do not match", "<Hidden for Security>"))); } // Update Password account.Password = _Hasher.HashPassword(account, request.Str("new")); await _Db.SaveChangesAsync(); _Logger.LogInformation("Password updated for account belonging to {0}", account.Name); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error updating password for account belonging to {0}: {1}", User.AccountName(), ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message))); } }
public async Task <IActionResult> ValidatePageName(IFormCollection request) { try { string name = request.Str("name"); List <Page> pages = await _Db.Pages.ToListAsync(); // Page already exists if (pages.Any(p => p.Name.ToLower() == name.ToLower())) { return(Conflict($"A page already exists with the name: {name}")); } // Reserved names if (reservedNames.Contains(name.ToLower())) { return(Conflict($"{name} is a reserved page name")); } // Illegal Characters if (!new Regex("^[a-zA-Z ]*$").IsMatch(name)) { return(Conflict($"{name} contains an invalid character. Page names can only include latters and spaces.")); } return(Ok()); } catch (Exception ex) { _Logger.LogError("Error validating page name {0}: {1}", request.Str("name"), ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("We were unable to validate your page name, please wait 60 seconds and try again.")); } }
public async Task <IActionResult> ReorderItems(IFormCollection request, string section) { try { if (string.IsNullOrEmpty(request.Str("navitems"))) { return(BadRequest(new ResponseHelper("Something went wrong, please try again later", "No nav-item data was sent"))); } if (!Enum.TryParse(section, true, out Section navSection)) { return(BadRequest(new ResponseHelper("Something went wrong, please try again later", "Must define section as 'main' or 'education'"))); } List <int> idOrder = JsonConvert.DeserializeObject <List <int> >(request.Str("navitems")); for (int orderIndex = 0; orderIndex < idOrder.Count; orderIndex++) { NavItem item = await _Db.NavItems.FindAsync(idOrder[orderIndex]); item.OrderIndex = orderIndex; item.Section = navSection; } await _Db.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error re-ordering navlinks", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later.", ex.Message))); } }
public async Task <IActionResult> AddCategory(IFormCollection form) { try { string categoryName = form.Str("categoryName"); // Check for existing record by this name if (await _Db.FactFileCategories.Where(cat => cat.Name == categoryName).FirstOrDefaultAsync() != null) { return(BadRequest(new ResponseHelper("A category with this name already exists!"))); } // Add new record and save await _Db.FactFileCategories.AddAsync(new FactFileCategory { Name = categoryName, Active = true }); await _Db.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error retrieving fact file categories", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again in a few minutes.", ex.Message))); } }
public async Task <IActionResult> UpdateCategory(int id, IFormCollection form) { try { FactFileCategory category = await _Db.FactFileCategories.FindAsync(id); if (category == null) { return(NotFound(new ResponseHelper("Something went wrong. If the problem persists, please contact the developers."))); } string newName = form.Str("name"); if (string.IsNullOrEmpty(newName)) { return(BadRequest(new ResponseHelper("The category name must not be null"))); } category.Name = newName; await _Db.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error updating entry name", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again in a few minutes.", ex.Message))); } }
public async Task <IActionResult> Index(string token, IFormCollection request) { if (string.IsNullOrEmpty(token)) { _Logger.LogDebug("Password reset attempted ({0}) with no token provided", request.Str("email")); return(BadRequest((new ResponseHelper("Invalid reset token")))); } try { PasswordReset reset = await _Db.PasswordResets.Include(i => i.Account) .Where(c => c.Token == token && c.Account.Email == request.Str("email") && c.ExpiresAt > DateTime.UtcNow) .FirstOrDefaultAsync(); if (reset == null) { _Logger.LogDebug("Password reset attempted ({0}) with expired or invalid token", request.Str("email")); return(BadRequest((new ResponseHelper("Reset token invalid or expired")))); } if (request.Str("password") != request.Str("passswordConfirm")) { _Logger.LogDebug("Password reset attempted ({0}) with mismatching passwords", request.Str("email")); return(BadRequest(new ResponseHelper("Your password and password confirmation do not match"))); } Account account = await _Db.Accounts.FindAsync(reset.Account.Id); account.Password = _Hasher.HashPassword(account, request.Str("password")); account.ForcePasswordReset = false; reset.ExpiresAt = DateTime.UtcNow; await _Db.SaveChangesAsync(); _Logger.LogInformation("Password has been updated for account belonging to {0}", account.Name); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error updating password for account belonging to {0}: {1}", request.Str("email"), ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message))); } }
public async Task <IActionResult> UpdateContactSettings(IFormCollection request) { try { SystemSettings settings = await _Db.SystemSettings.OrderByDescending(o => o.Id).FirstOrDefaultAsync(); // Update the new information settings.EmailBookings = request.Str("emailBookings"); settings.EmailGeneral = request.Str("emailGeneral"); settings.Phone = request.Str("phone"); settings.UrlFacebook = request.Str("urlFacebook"); settings.UrlGooglePlay = request.Str("urlGooglePlay"); settings.UrlGoogleMaps = request.Str("urlGoogleMaps"); settings.FooterText = request.Str("missionStatement"); // Save to database await _Db.SaveChangesAsync(); _Logger.LogInformation($"{User.AccountName()} updated the sites contact settings"); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error updating system contact settings: {0}", ex.Message); _Logger.LogTrace(ex.StackTrace); return(BadRequest(new ResponseHelper("Error updating system contact settings, please try again later", ex.Message))); } }
public async Task <IActionResult> Index(IFormCollection request) { Account account = await _Db.Accounts.Where(c => c.Email == request.Str("email")).FirstOrDefaultAsync(); if (account != null) { _Logger.LogDebug("Unable to create account using {0} as an account already exists for this email address", request.Str("email")); return(BadRequest(new ResponseHelper("An account with that email address already exists"))); } try { account = new Account { Email = request.Str("email"), Name = request.Str("name"), Active = false, }; account.Password = _Hasher.HashPassword(account, RandomString(30)); await _Db.AddAsync(account); PasswordReset reset = new PasswordReset( account, DateTime.UtcNow.AddHours(_Config["LoginSettings:NewAccountResetTokenLength"].ToInt()) ); await _Db.AddAsync(reset); await _Db.SaveChangesAsync(); _Logger.LogInformation("New account created - Name: {0}, Email: {1}", account.Name, account.Email); await _EmailService.SendNewAccountEmailAsync(reset, User, Request.BaseUrl()); return(Ok(Url.Action("Index", "Users", new { area = "admin" }))); } catch (Exception ex) { _Logger.LogError("Error while creating new account: {0}", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message))); } }
public async Task <IActionResult> SendEmail(IFormCollection request) { try { var reCAPTCHA = await _Recaptcha.Validate(request.Str("code")); if (!reCAPTCHA.success) { _Logger.LogWarning($"{request.Str("name")}'s captcha validation failed."); return(Conflict("Please complete the reCAPTCHA")); } var messageArgs = new EmailRecieved(request, this.Request.BaseUrl()); EmailContact Sender = new EmailContact { Name = messageArgs.Name, Address = messageArgs.SendersEmail }; if (request.Bool("SendToBookings")) { // Sends a master email to the "BOOKINGS" email address in system settings, then sends a copy to each person on the mailing list. await _EmailService.SendBookingInquiryAsync(Sender, messageArgs.Subject, messageArgs); } else { // Sends a master email to the "GENERAL" email address in system settings, then sends a copy to each person on the mailing list. await _EmailService.SendGeneralInquiryAsync(Sender, messageArgs.Subject, messageArgs); } _Logger.LogInformation("Sucsefully sent {0}'s email", messageArgs.SendersName); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error sending {0}'s email: {1}", request.Str("name"), ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("Something went wrong and we could not send your email. Please try again later.")); } }
public async Task <IActionResult> Index(IFormCollection request) { try { Account account = await _Db.Accounts.FindAsync(User.AccountId()); account.Name = request.Str("name"); account.Email = request.Str("email"); account.PhoneNumber = request.Str("phoneNumber"); await _Db.SaveChangesAsync(); _Logger.LogInformation("Information updated for account belonging to {0}", account.Name); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error updating account belonging to {0}: {1}", User.AccountName(), ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("We could not update your account, please try again later", ex.Message))); } }
public async Task <IActionResult> UpdateQuickLinks(IFormCollection request, int sectionId) { try { SystemSettings settings = await _Db.SystemSettings.OrderByDescending(o => o.Id).FirstOrDefaultAsync(); // Update changed fields settings.LinkTitleA = (sectionId == (int)QuickLinkSection.A) ? request.Str("title") : settings.LinkTitleA; settings.LinkTitleB = (sectionId == (int)QuickLinkSection.B) ? request.Str("title") : settings.LinkTitleB; // Save to database await _Db.SaveChangesAsync(); _Logger.LogInformation($"{User.AccountName()} updated the quick link settings"); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error updating quick link title: {0}", ex.Message); _Logger.LogTrace(ex.StackTrace); return(BadRequest(new ResponseHelper("Error updating quick link title, please try again later", ex.Message))); } }
public async Task <IActionResult> Update(int id, IFormCollection request) { try { BaseMedia media = await _Db.Media.FindAsync(id); if (media == null) { return(NotFound("The requested media file does not exist.")); } // All types of media have a name, so we can update that media.Name = request.Str("name"); media.Source = request.Str("source"); media.ShowCopyright = request.Bool("showCopyright"); // If file is an image, we can also set the title and alt-text if (media is ImageMedia) { (media as ImageMedia).Title = request.Str("title"); (media as ImageMedia).Alt = request.Str("alt"); } // Save changes await _Db.SaveChangesAsync(); _Logger.LogDebug("Metadata updated for media file {0}", id); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error updating metadata for media file {0}: {1}", id, ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("Something went wrong, please try again later.")); } }
public async Task <IActionResult> Index(IFormCollection request) { try { Account account = await _Db.Accounts.Where(c => c.Email == request.Str("email")).FirstOrDefaultAsync(); if (account != null) { List <PasswordReset> oldTokens = await _Db.PasswordResets.Where(c => c.Account.Id == account.Id).ToListAsync() ?? new List <PasswordReset>(); foreach (PasswordReset resetToken in oldTokens) { resetToken.ExpiresAt = DateTime.UtcNow; } PasswordReset reset = new PasswordReset( account, DateTime.UtcNow.AddMinutes(_Config["LoginSettings:PasswordResetTokenLength"].ToInt()) ); await _Db.AddAsync(reset); await _Db.SaveChangesAsync(); await _EmailService.SendPasswordResetEmailAsync(reset, this.Request.BaseUrl()); _Logger.LogInformation("Password reset requested for account belonging to {0}", account.Name); } return(Ok()); } catch (Exception ex) { _Logger.LogError("Error requesting password reset for account belonging to {0}: {1}", request.Str("email"), ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message))); } }
public async Task <IActionResult> Index(IFormCollection request) { try { // Create required directories if not existing EnsureInit(); // Deserialize cropping data if applicable CropData cropData = null; if (request.Str("cropData") != null) { cropData = JsonConvert.DeserializeObject <CropData>(request.Str("cropData")); } // Original filename string uploadedName = request.Str("filename"); // Generate a backend filename for the uploaded file - same extension as uploaded file. string filename = Guid.NewGuid().ToString() + Path.GetExtension(uploadedName); string fileType = request.Str("fileType"); // Determine what type of file has been uploaded and act accordingly (may want to refactor these) // FOR IMAGES if (MediaType.MimesForCategory(MediaCategory.Image).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Images", filename); // Save image and all associated versions of it. var filedata = ImageUtils.SaveImage(request.Str("file") .Split(',')[1], filepath, cropData); // Create database record to track images ImageMedia dbImageMedia = new ImageMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = filedata["size"], Title = request.Str("title"), Alt = request.Str("alt"), Width = filedata["width"], Height = filedata["height"], Versions = filedata["versions"] }; await _Db.AddAsync(dbImageMedia); } // FOR AUDIO else if (MediaType.MimesForCategory(MediaCategory.Audio).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Audio", filename); // Save the audio file byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes(); await System.IO.File.WriteAllBytesAsync(filepath, bytes); // Read the audio file to determine its duration - it will either be mp3(mpeg) or wav // Configure ffprobe path using appsettings values FFProbe probe = new FFProbe(); probe.ToolPath = _Config["ffprobePath"]; // If running linux, look for ffprobe instaed of ffprobe.exe if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { probe.FFProbeExeName = "ffprobe"; } // Get audio file metadata MediaInfo mediaInfo = probe.GetMediaInfo(Path.Combine(_HostingEnv.ContentRootPath, filepath)); // Create the media database record AudioMedia audioMedia = new AudioMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = new FileInfo(filepath).Length, Duration = Math.Round(mediaInfo.Duration.TotalSeconds) }; await _Db.AddAsync(audioMedia); } // FOR GENERAL else if (MediaType.MimesForCategory(MediaCategory.General).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Documents", filename); // Save the file byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes(); System.IO.File.WriteAllBytes(filepath, bytes); // Create the media database record GeneralMedia generalMedia = new GeneralMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = new FileInfo(filepath).Length, }; await _Db.AddAsync(generalMedia); } else { return(new UnsupportedMediaTypeResult()); } await _Db.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error uploading file: {0}", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please contact the devloper if the problem persists", ex.Message))); } }
public async Task <IActionResult> UpdateEntry(int id, IFormCollection form) { try { FactFileEntry entryToUpdate = await _Db.FactFileEntries .Include(entry => entry.FactFileEntryImages) .Include(entry => entry.FactFileNuggets) .Where(entry => entry.Id == id) .FirstOrDefaultAsync(); if (entryToUpdate == null) { return(NotFound(new ResponseHelper("Something went wrong, please contact the developers if the problem persists."))); } // Validate inputs first // // // entryToUpdate.Active = form.Bool("active"); // Update text fields entryToUpdate.PrimaryName = form.Str("primaryName"); entryToUpdate.AltName = form.Str("altName"); entryToUpdate.BodyText = form.Str("bodyText"); // Update media fields entryToUpdate.ListenAudioId = form.Int("listenAudioId"); entryToUpdate.PronounceAudioId = form.Int("pronounceAudioId"); if (entryToUpdate.ListenAudioId == 0) { entryToUpdate.ListenAudioId = null; } if (entryToUpdate.PronounceAudioId == 0) { entryToUpdate.PronounceAudioId = null; } entryToUpdate.MainImageId = form.Int("mainImageId"); // Remove and rebuild fact file entry image records int[] imageArray = JsonConvert.DeserializeObject <int[]>(form.Str("images")); _Db.RemoveRange(entryToUpdate.FactFileEntryImages); foreach (int imageId in imageArray) { entryToUpdate.FactFileEntryImages.Add(new FactFileEntryImage { FactFileEntryId = entryToUpdate.Id, MediaFileId = imageId }); } // Remove and rebuild fact file nugget records FactFileNugget[] updatedNuggets = JsonConvert.DeserializeObject <FactFileNugget[]>(form.Str("nuggets")); _Db.RemoveRange(entryToUpdate.FactFileNuggets); for (int i = 0; i < updatedNuggets.Length; i++) { updatedNuggets[i].OrderIndex = i; entryToUpdate.FactFileNuggets.Add(updatedNuggets[i]); } await _Db.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error updating entry", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again in a few minutes.", ex.Message))); } }
public async Task <IActionResult> AddEntry(int categoryId, IFormCollection form) { try { FactFileEntry entryToSave = new FactFileEntry(); // Validate inputs first // // // entryToSave.Active = form.Bool("active"); entryToSave.CategoryId = categoryId; // Update text fields entryToSave.PrimaryName = form.Str("primaryName"); entryToSave.AltName = form.Str("altName"); entryToSave.BodyText = form.Str("bodyText"); // Update media fields entryToSave.ListenAudioId = form.Int("listenAudioId"); entryToSave.PronounceAudioId = form.Int("pronounceAudioId"); if (entryToSave.ListenAudioId == 0) { entryToSave.ListenAudioId = null; } if (entryToSave.PronounceAudioId == 0) { entryToSave.PronounceAudioId = null; } entryToSave.MainImageId = form.Int("mainImageId"); await _Db.AddAsync(entryToSave); await _Db.SaveChangesAsync(); // to generate id // Remove and rebuild fact file entry image records int[] imageArray = JsonConvert.DeserializeObject <int[]>(form.Str("images")); entryToSave.FactFileEntryImages = new List <FactFileEntryImage>(); foreach (int imageId in imageArray) { entryToSave.FactFileEntryImages.Add(new FactFileEntryImage { FactFileEntryId = entryToSave.Id, MediaFileId = imageId }); } // Remove and rebuild fact file nugget records FactFileNugget[] updatedNuggets = JsonConvert.DeserializeObject <FactFileNugget[]>(form.Str("nuggets")); entryToSave.FactFileNuggets = new List <FactFileNugget>(); for (int i = 0; i < updatedNuggets.Length; i++) { updatedNuggets[i].OrderIndex = i; entryToSave.FactFileNuggets.Add(updatedNuggets[i]); } await _Db.SaveChangesAsync(); return(Ok(entryToSave.Id)); } catch (Exception ex) { _Logger.LogError("Error saving new entry", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again in a few minutes.", ex.Message))); } }
public static dynamic Deserialize(this IFormCollection request, Type type, string key) => JsonConvert.DeserializeObject(request.Str(key), type);
public async Task <IActionResult> CreateRevision(int pageId, IFormCollection request) { /* To be supplied in request body - * * Reason for change - e.g. Updated pricing information * Template ID * Collection of text components * Collection of media components * */ try { // Load page from database Page page = await _Db.Pages.FindAsync(pageId); if (page == null) { return(BadRequest("No page exists for given page ID")); } List <TextComponent> newRevisionTextComponents = request.Deserialize(typeof(List <TextComponent>), "textComponents"); List <MediaComponent> newRevisionMediaComponents = request.Deserialize(typeof(List <MediaComponent>), "imageComponents"); // Todo: Do this after the view has had template switching enabled // Load template from database // PageTemplate template = await _Db.PageTemplates // .FindAsync(request.Int("templateId")); // Fetch the original revision PageRevision old = await _Db.PageRevisions .Include(pr => pr.Template) .Include(pr => pr.RevisionMediaComponents) .ThenInclude(rmc => rmc.MediaComponent) .Include(pr => pr.RevisionTextComponents) .ThenInclude(rtc => rtc.TextComponent) .ThenInclude(tc => tc.CmsButton) .Where(pr => pr.Page == page) .OrderByDescending(pr => pr.CreatedAt) .FirstOrDefaultAsync(); var oldRevision = new { old.Template, TextComponents = old.RevisionTextComponents .Select(rtc => rtc.TextComponent) .OrderBy(tc => tc.SlotNo) .ToList(), MediaComponents = old.RevisionMediaComponents .Select(rmc => rmc.MediaComponent) .OrderBy(tc => tc.SlotNo) .ToList() }; // Create the new page revision PageRevision newRevision = new PageRevision { Page = page, Template = oldRevision.Template, Reason = request.Str("reason"), CreatedBy = await _Db.Accounts.FindAsync(User.AccountId()), }; // Assign the new revision an ID await _Db.AddAsync(newRevision); for (int i = 0; i < newRevision.Template.TextAreas; i++) { TextComponent textComponentToSave = null; // Only save a new text component if it has changed if (!newRevisionTextComponents[i].Equals(oldRevision.TextComponents[i])) { textComponentToSave = newRevisionTextComponents[i]; // Set ID to 0 so that EF Core assigns us a new one textComponentToSave.Id = 0; // Save a new button if the components button does not yet exist in database. if (textComponentToSave.CmsButton != null && !textComponentToSave.CmsButton.Equals(oldRevision.TextComponents[i].CmsButton)) { await _Db.AddAsync(textComponentToSave.CmsButton); } // Generate ID for the new TextComponent await _Db.AddAsync(textComponentToSave); } // Add association between component and new revision await _Db.AddAsync(new RevisionTextComponent { // Use the new components ID if it exists, other use existing (unchanged) component // from previous revision TextComponentId = textComponentToSave?.Id ?? oldRevision.TextComponents[i].Id, PageRevisionId = newRevision.Id }); } // Do the same for media components for (int i = 0; i < newRevision.Template.MediaAreas; i++) { MediaComponent mediaComponentToSave = null; // Only create new media component if the old one was modified if (!newRevisionMediaComponents[i].Equals(oldRevision.MediaComponents[i])) { mediaComponentToSave = newRevisionMediaComponents[i]; // Generate new ID mediaComponentToSave.Id = 0; await _Db.AddAsync(mediaComponentToSave); } // Add association to new revision await _Db.AddAsync(new RevisionMediaComponent { PageRevisionId = newRevision.Id, MediaComponentId = mediaComponentToSave?.Id ?? oldRevision.MediaComponents[i].Id }); } // Save changes await _Db.SaveChangesAsync(); _Logger.LogDebug("New page revision created for page {0} ({1}): {2}", pageId, page.Name, newRevision.Reason); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error creating new revision for page {0}: {1}", pageId, ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("Something went wrong, please try again later.")); } }
public async Task <IActionResult> Index(IFormCollection request, string ReturnUrl) { if (!User.Identity.IsAuthenticated) { try { Account account = await _Db.Accounts.Where(c => c.Email == request.Str("email")).FirstOrDefaultAsync(); // No Account if (account == null) { _Logger.LogInformation("User attempted logging in with invalid email address"); return(Unauthorized(new ResponseHelper("Invalid email or password"))); } // Invalid Password if (_Hasher.VerifyHashedPassword(account, account.Password, request.Str("password")) != PasswordVerificationResult.Success) { _Logger.LogInformation("User attempted logging into account belonging to {0} with invalid password", account.Name); return(Unauthorized(new ResponseHelper("Invalid email or password"))); } // Inactive Account if (!account.Active) { _Logger.LogInformation("User attempted logging into account belonging to {0}, but the account needs to be activated", account.Name); return(Unauthorized(new ResponseHelper("Your account requires activation from an administrator"))); } var claims = new List <Claim> { new Claim("id", account.Id.ToString()), new Claim("name", account.Name), new Claim("email", account.Email) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { AllowRefresh = true, IsPersistent = true, }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); account.LastLogin = DateTime.UtcNow; await _Db.SaveChangesAsync(); _Logger.LogDebug("User has logged into account belonging to {0}", account.Name); } catch (Exception ex) { _Logger.LogError("Error while logging in: {0}", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message))); } } if (string.IsNullOrEmpty(ReturnUrl)) { ReturnUrl = Url.Action( "Index", "Dashboard", new { area = "admin" } ); } else { ReturnUrl = this.Request.BaseUrl() + ReturnUrl.Substring(1); } return(Ok(ReturnUrl)); }