public async Task <IActionResult> ChangePassword(ChangePasswordViewModel model) { if (ModelState.IsValid) { if (model.OldPassword == model.NewPassword) { ModelState.AddModelError(string.Empty, "Новый и старый пароли не должны совпадать"); return(View(model)); } User user = await userManager.FindByNameAsync(User.Identity.Name); user.UserName += ApplicationConstantsProvider.AvoidValidationCode(); user.Email += ApplicationConstantsProvider.AvoidValidationCode(); var changePasswordResult = await userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (changePasswordResult.Succeeded) { return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.AccountUpdatedMessages(), RedirectUrl = "/Account/Personal", SecondsToRedirect = ApplicationConstantsProvider.GetShortRedirectionTime() })); } else { ModelState.AddModelError(string.Empty, "Вы ввели неверный старый пароль"); } } return(View(model)); }
public async Task <IActionResult> Personal(int page = 1) { User user = await userManager.FindByNameAsync(User.Identity.Name); List <AuctionLot> userLots = new List <AuctionLot>(); int count = 0; if (await userManager.IsInRoleAsync(user, "regular user")) { userLots = await lotLogic.GetPage(page, new AuctionLot { User = user }); count = await lotLogic.GetCount(new AuctionLot { User = user }); } PersonalAccountViewModel model = new PersonalAccountViewModel { UserName = user.UserName, Email = user.Email, TelegramId = user.TelegramUsername, PersonalLotsList = new AuctionLotsViewModel { AuctionLots = userLots, PageViewModel = new PageViewModel(count, page, ApplicationConstantsProvider.GetPageSize()) } }; return(View(model)); }
public async Task <IActionResult> CreateUser(CreateUserViewModel model) { if (ModelState.IsValid) { User moderator = new User { Email = model.Email, UserName = model.UserName }; var registerResult = await userManager.CreateAsync(moderator, model.Password); if (registerResult.Succeeded) { moderator.Email += ApplicationConstantsProvider.AvoidValidationCode(); moderator.UserName += ApplicationConstantsProvider.AvoidValidationCode(); await userManager.AddToRoleAsync(moderator, "moderator"); return(RedirectToAction("UsersList")); } else { foreach (var error in registerResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } return(View(model)); }
public async Task <IActionResult> RejectLot(LotModerationModel model) { if (ModelState.IsValid) { await crudLotLogic.Update(new AuctionLot { Id = model.AuctionLot.Id, Status = LotStatusProvider.GetRejectedStatus() }); await crudNoteLogic.Delete(new Note { AuctionLotId = model.AuctionLot.Id }); await crudNoteLogic.Create(new Note { AuctionLotId = model.AuctionLot.Id, Text = model.RejectNote }); await SendRejectMessage(model.AuctionLot.Id, model.RejectNote); return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.LotRejectedMessages(), SecondsToRedirect = ApplicationConstantsProvider.GetLongRedirectionTime(), RedirectUrl = "/Moderator/Lots" })); } model.Expanded = true; return(View("CheckLot", model)); }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { if (!string.IsNullOrWhiteSpace(model.TelegramId)) { User sameTelegramUser = (await userLogic.Read(new User { TelegramUsername = model.TelegramId }))?.FirstOrDefault(); if (sameTelegramUser != null) { ModelState.AddModelError(string.Empty, "Уже есть пользователь с таким Telegram-идентификатором"); return(View(model)); } } User user = new User { Email = model.Email, UserName = model.UserName, TelegramUsername = string.IsNullOrWhiteSpace(model.TelegramId) ? string.Empty : model.TelegramId, TelegramChatId = string.Empty }; var registerResult = await userManager.CreateAsync(user, model.Password); if (registerResult.Succeeded) { user.Email += ApplicationConstantsProvider.AvoidValidationCode(); user.UserName += ApplicationConstantsProvider.AvoidValidationCode(); await userManager.AddToRoleAsync(user, "regular user"); await savedListLogic.Create(user); await signInManager.SignInAsync(user, false); return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.AccountCreatedMessages(), RedirectUrl = "/Home/Lots", SecondsToRedirect = ApplicationConstantsProvider.GetShortRedirectionTime() })); } else { foreach (var error in registerResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } return(View(model)); }
public async Task <IActionResult> CreateLot(CreateLotViewModel model) { if (ModelState.IsValid) { AuctionLot toAdd = new AuctionLot { Name = model.Name, User = new User { UserName = User.Identity.Name }, Description = model.Description, StartDate = model.StartDate.Value, EndDate = model.EndDate.Value, PriceInfo = new PriceInfo { StartPrice = model.StartPrice.Value, CurrentPrice = model.StartPrice.Value, BidStep = model.BidStep.Value } }; string dbPhotoPath = $"/images/{User.Identity.Name}/{model.Name}/photo{Path.GetExtension(model.Photo.FileName)}"; toAdd.PhotoSrc = dbPhotoPath; try { await lotLogic.Create(toAdd); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View(model)); } string physicalDirectory = Path.GetDirectoryName($"{environment.WebRootPath + dbPhotoPath}"); if (!Directory.Exists(physicalDirectory)) { Directory.CreateDirectory(physicalDirectory); } using (FileStream fs = new FileStream($"{environment.WebRootPath + dbPhotoPath}", FileMode.Create)) { await model.Photo.CopyToAsync(fs); } return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.LotCreatedMessages(), RedirectUrl = "/Home/Lots", SecondsToRedirect = ApplicationConstantsProvider.GetMaxRedirectionTime() })); } return(View(model)); }
public async Task <List <AuctionLot> > GetPage(int pageNumber, AuctionLot model) { return(await context.AuctionLots.Include(lot => lot.User).Include(lot => lot.PriceInfo).Where(lot => model == null || !string.IsNullOrWhiteSpace(model.Status) && lot.Status == model.Status || model.User != null && lot.User == model.User) .OrderByDescending(lot => lot.StartDate) .Skip((pageNumber <= 0 ? 0 : pageNumber - 1) * ApplicationConstantsProvider.GetPageSize()) .Take(ApplicationConstantsProvider.GetPageSize()) .ToListAsync()); }
public Task <IdentityResult> ValidateAsync(UserManager <User> manager, User user) { List <IdentityError> errors = new List <IdentityError>(); string avoidValidationCode = ApplicationConstantsProvider.AvoidValidationCode(); if (user.UserName == user.Email) { errors.Add(new IdentityError { Description = "Имя пользователя и адрес электронной почты не должны совпадать" }); } if (user.Email.Contains(avoidValidationCode)) { user.Email = user.Email.Replace(avoidValidationCode, string.Empty); } else { User existingEmail = manager.FindByEmailAsync(user.Email).Result; if (existingEmail != null) { errors.Add(new IdentityError { Description = "Данный Email уже используется" }); } } if (user.UserName.Contains(avoidValidationCode)) { user.UserName = user.UserName.Replace(avoidValidationCode, string.Empty); } else { User existingUserName = manager.FindByNameAsync(user.UserName).Result; if (existingUserName != null) { errors.Add(new IdentityError { Description = "Имя пользователя занято" }); } } return(Task.FromResult(errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray()))); }
public async Task <IActionResult> Lots(int page = 1) { List <AuctionLot> lotsOnModeration = await paginationLotLogic.GetPage(page, new AuctionLot { Status = LotStatusProvider.GetOnModerationStatus() }); int lotsCount = await paginationLotLogic.GetCount(new AuctionLot { Status = LotStatusProvider.GetOnModerationStatus() }); return(View(new AuctionLotsViewModel { AuctionLots = lotsOnModeration, PageViewModel = new PageViewModel(lotsCount, page, ApplicationConstantsProvider.GetPageSize()) })); }
public async Task <IActionResult> Lots(int page = 1) { List <AuctionLot> lotsToDisplay = await lotLogic.GetPage(page, new AuctionLot { Status = LotStatusProvider.GetAcceptedStatus() }); int lotsCount = await lotLogic.GetCount(new AuctionLot { Status = LotStatusProvider.GetAcceptedStatus() }); return(View(new AuctionLotsViewModel() { PageViewModel = new PageViewModel(lotsCount, page, ApplicationConstantsProvider.GetPageSize()), AuctionLots = lotsToDisplay })); }
public async Task <IActionResult> AcceptLot(string id) { if (!string.IsNullOrWhiteSpace(id)) { await crudLotLogic.Update(new AuctionLot { Id = id, Status = LotStatusProvider.GetAcceptedStatus() }); await SendAcceptMessage(id); return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.LotAcceptedMessages(), SecondsToRedirect = ApplicationConstantsProvider.GetLongRedirectionTime(), RedirectUrl = "/Moderator/Lots" })); } return(NotFound()); }
public async Task <IActionResult> PlaceBid(string lotId) { if (!string.IsNullOrWhiteSpace(lotId)) { User user = await userManager.FindByNameAsync(User.Identity.Name); try { await bidLogic.Create(new Bid { AuctionLot = (await lotLogic.Read(new AuctionLot { Id = lotId }))?.First(), User = user }); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.AuctionTimeUpMessages(), RedirectUrl = $"/User/OpenLot/?id={lotId}", SecondsToRedirect = ApplicationConstantsProvider.GetShortRedirectionTime() })); } AuctionLot lotToAdd = new AuctionLot { Id = lotId }; await savedListLogic.Add(user, lotToAdd); await SendNotifications(lotId, User.Identity.Name); return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.BidPlacedMessages(), RedirectUrl = $"/User/OpenLot/?id={lotId}", SecondsToRedirect = ApplicationConstantsProvider.GetShortRedirectionTime() })); } return(NotFound()); }
public static async Task InitializeAdmin(UserManager <User> userManager, IConfiguration configuration) { string email = configuration["AdminEmailAzure"]; string password = configuration["AdminPasswordAzure"]; string username = configuration["AdminUsernameAzure"]; if (await userManager.FindByEmailAsync(email) == null) { User admin = new User { Email = email, UserName = username }; var registerResult = await userManager.CreateAsync(admin, password); if (registerResult.Succeeded) { admin.Email += ApplicationConstantsProvider.AvoidValidationCode(); admin.UserName += ApplicationConstantsProvider.AvoidValidationCode(); await userManager.AddToRoleAsync(admin, "admin"); } } }
public async Task <IActionResult> Update(UpdateAccountViewModel model) { if (ModelState.IsValid) { User userToUpdate = await userManager.FindByNameAsync(User.Identity.Name); if (!string.IsNullOrWhiteSpace(model.NewEmail)) { if (model.NewEmail == userToUpdate.Email) { ModelState.AddModelError(string.Empty, "Новый email совпадает со старым"); return(View(model)); } else { userToUpdate.UserName += ApplicationConstantsProvider.AvoidValidationCode(); var updateEmailResult = await userManager.SetEmailAsync(userToUpdate, model.NewEmail); if (!updateEmailResult.Succeeded) { foreach (var updateEmailError in updateEmailResult.Errors) { ModelState.AddModelError(string.Empty, updateEmailError.Description); } return(View(model)); } } } if (!string.IsNullOrWhiteSpace(model.NewTelegramUserName)) { if (model.NewTelegramUserName == userToUpdate.TelegramUsername) { ModelState.AddModelError(string.Empty, "Новое имя пользователя в Telegram совпадает со старым"); return(View(model)); } else { User sameTelegramUser = (await userLogic.Read(new User { TelegramUsername = model.NewTelegramUserName }))?.FirstOrDefault(); if (sameTelegramUser != null) { ModelState.AddModelError(string.Empty, "Уже есть пользователь с таким Telegram-идентификатором"); } else { userToUpdate.Email += ApplicationConstantsProvider.AvoidValidationCode(); userToUpdate.UserName += ApplicationConstantsProvider.AvoidValidationCode(); userToUpdate.TelegramUsername = model.NewTelegramUserName; string tempChatId = userToUpdate.TelegramChatId; userToUpdate.TelegramChatId = string.Empty; var updateTelegramResult = await userManager.UpdateAsync(userToUpdate); if (updateTelegramResult.Succeeded) { if (!string.IsNullOrWhiteSpace(tempChatId)) { await telegramBot.SendMessage("Вы отписаны от уведомлений, " + "т.к. изменили учетные данные на сайте", tempChatId); } } else { foreach (var updateTelegramError in updateTelegramResult.Errors) { ModelState.AddModelError(string.Empty, updateTelegramError.Description); } return(View(model)); } } } } return(RedirectToAction("Personal", "Account")); } return(View(model)); }
public async Task <IActionResult> EditLot(EditLotViewModel model) { if (ModelState.IsValid) { if (string.IsNullOrWhiteSpace(model.Id)) { return(NotFound()); } AuctionLot lotToEdit = new AuctionLot { Id = model.Id, Name = model.Name, Description = model.Description, StartDate = model.StartDate.Value, EndDate = model.EndDate.Value, Status = LotStatusProvider.GetOnModerationStatus(), PriceInfo = new PriceInfo { StartPrice = model.StartPrice.Value, BidStep = model.BidStep.Value } }; string newDbPath = $"/images/{User.Identity.Name}/{model.Name}/photo{Path.GetExtension(model.Photo.FileName)}"; lotToEdit.PhotoSrc = newDbPath; try { await lotLogic.Update(lotToEdit); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View(model)); } string oldPath = $"{environment.WebRootPath + Path.GetDirectoryName(model.OldPhotoSrc)}"; if (Directory.Exists(oldPath)) { Directory.Delete(oldPath, true); } string newPhysicalDirectory = Path.GetDirectoryName($"{environment.WebRootPath + newDbPath}"); if (!Directory.Exists(newPhysicalDirectory)) { Directory.CreateDirectory(newPhysicalDirectory); } using (FileStream fs = new FileStream($"{environment.WebRootPath + newDbPath}", FileMode.Create)) { await model.Photo.CopyToAsync(fs); } return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.LotUpdatedMessages(), RedirectUrl = "/Home/Lots", SecondsToRedirect = ApplicationConstantsProvider.GetMaxRedirectionTime() })); } return(View(model)); }