public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { var user = await _userManager.GetUserAsync(HttpContext.User); model.OldEmail = user.Email; if (!ModelState.IsValid) { return(View(model)); } if (user != null) { user.Email = model.NewEmail; var result = await _userManager.UpdateAsync(user); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); return(RedirectToAction("Manage", new { Message = ManageMessageId.ChangeEmailSuccess })); } else { return(RedirectToAction("Manage", new { Message = ManageMessageId.Error })); } } else { return(RedirectToAction("Manage", new { Message = ManageMessageId.Error })); } }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (model.Email != user.Email) { user.Email = model.Email; user.UserName = model.Email; } var result = await UserManager.UpdateAsync(user); if (result.Succeeded) { user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); } return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeNameSuccess })); } AddErrors(result); return(View(model)); }
public async Task <IActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!this.ModelState.IsValid) { return(this.View(model)); } var user = await this.GetCurrentUserAsync(); if (user != null) { var result = await this.userManager.ChangeEmailAsync(user, model.NewEmail, model.Token); if (result.Succeeded) { await this.signInManager.SignInAsync(user, isPersistent : false); this.logger.LogInformation(4, "User changed their email successfully."); return(this.RedirectToAction(nameof(ManageController.Index), new { Message = ManageMessageId.ChangeEmailSuccess })); } this.AddErrors(result); return(this.View(model)); } return(this.RedirectToAction(nameof(ManageController.Index), new { Message = ManageMessageId.Error })); }
public async Task <IActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await GetCurrentUserAsync(); if (user != null) { user.UnconfirmedEmail = model.NewEmail; var result = await userManager.UpdateAsync(user); if (result.Succeeded) { var tokenForNewEmail = await userManager.GenerateChangeEmailTokenAsync(user, user.UnconfirmedEmail); var callbackUrl = Url.Action("UpdateEmail", "Manage", new { userId = user.Id, code = tokenForNewEmail }, protocol: HttpContext.Request.Scheme); var confirmationEmailBody = MessageConstants.ConfirmationEmailBodyTemplate.Replace("callbackUrl", callbackUrl); await emailSender.SendEmailAsync(model.NewEmail, "Confirm your new email", confirmationEmailBody); logger.LogInformation(3, "User was sent a new confirmation link."); return(View("ConfirmationEmailSent")); } } new AlertFactory(HttpContext).CreateAlert(AlertType.Danger, SessionConstants.ERROR); return(RedirectToAction(nameof(Index))); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = UserManager.FindById(User.Identity.GetUserId <int>()); if (UserManager.CheckPassword(user, model.CurrentPassword)) { user.Email = model.NewEmail; IdentityResult result = await UserManager.UpdateAsync(user); if (result.Succeeded) { if (UserManager.IsEmailConfirmed(user.Id)) { user.EmailConfirmed = false; await UserManager.UpdateAsync(user); } return(RedirectToAction("SendConfirmationEmail", "Email", new { area = "Account", Message = ManageMessageId.ChangeEmailSuccess })); } AddErrors(result); return(View()); } else { IdentityResult uncorrectPassword = IdentityResult.Failed("You entered a wrong password."); AddErrors(uncorrectPassword); model.CurrentPassword = ""; return(View(model)); } }
public async Task <IActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetUserNameAsync(user, model.NewEmail); if (result.Succeeded) { result = await _userManager.SetEmailAsync(user, model.NewEmail); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation(3, "User changed their password successfully."); return(RedirectToAction(nameof(Index))); } else { await _userManager.SetUserNameAsync(user, model.OldEmail); } } AddErrors(result); return(View(model)); } return(RedirectToAction(nameof(Index))); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var userName = !string.IsNullOrEmpty(model.UserName) ? model.UserName : User.Identity.Name; var user = await UserManager.FindByNameAsync(userName); var oldName = user.UserName; if (user != null) { UserManager.UpdateEmail(user.Id, model.NewEmail); if (oldName == User.Identity.Name) { FormsAuthentication.SignOut(); AuthHelper.SignIn(HttpContext, model.NewEmail, false); } return(RedirectToAction("Index", "Manage", new { userName = model.NewEmail })); } else { ModelState.AddModelError("", "Пользователь не найден."); return(View(model)); } }
public async Task <IActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(PartialView(ViewNames.Manage._ChangeEmailModalPartial, model)); } var user = await GetCurrentUserAsync(); if (user == null) { TempData.Put <ManageMessage>(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Danger, MessageId = MessageId.ChangeEmailFailure }); return(JsonAjaxRedirectForModal(Url.Action(nameof(Index), nameof(Manage), new { Organization = _siteContext.UrlSegmentValue }))); } if (user.NormalizedEmail == _userManager.KeyNormalizer.NormalizeEmail(model.Email)) { _logger.LogInformation($"Current and new email are equal ('{model.Email}')."); ModelState.AddModelError(nameof(ChangeEmailViewModel.Email), _localizer["Current and new email must be different"]); return(PartialView(ViewNames.Manage._ChangeEmailModalPartial, model)); } await SendEmail(user, EmailPurpose.NotifyCurrentPrimaryEmail, model.Email); await SendEmail(user, EmailPurpose.ConfirmNewPrimaryEmail, model.Email); TempData.Put <ManageMessage>(nameof(ManageMessage), new ManageMessage { AlertType = SiteAlertTagHelper.AlertType.Success, MessageId = MessageId.ChangeEmailConfirmationSent }); return(JsonAjaxRedirectForModal(Url.Action(nameof(Index), nameof(Manage), new { Organization = _siteContext.UrlSegmentValue }))); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { var userId = User.Identity.GetUserId(); await UserManager.SetEmailAsync(userId, model.Email); return(RedirectToAction("Index", "AccountManage")); }
public ActionResult ChangeEmail(ChangeEmailViewModel model) { int?Id = User.Identity.GetUserId <int>(); if (Id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (TryUpdateModel(model, "", new string[] { "FirstName" })) { try { db.Users.Find(Id).Email = model.NewEmail; db.SaveChanges(); return(RedirectToAction("Index")); } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Nem sikerült a mentés. Próbáld újra – ha úgy se működik, adminisztrátori segítség kell!"); } } return(View(model)); }
public void ChangeMail_check_if_redirect_to_correct_action() { try { var controllerContext = new Mock <ControllerContext>(); var principal = new Moq.Mock <IPrincipal>(); principal.SetupGet(x => x.Identity.Name).Returns("uname"); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); ChangeEmailViewModel mail = new ChangeEmailViewModel(); mail.NewEmail = "*****@*****.**"; mail.OldEmail = "*****@*****.**"; mail.UserProfileViewModel = new UserProfileViewModel(); mail.Id = 2; var serviceMock = new Mock <IUserService>(); var serviceOfferMock = new Mock <IOfferService>(); var serviceOrderMock = new Mock <IOrderService>(); serviceMock.Setup(s => s.EditUserEmailAsync(It.IsAny <User>())).ReturnsAsync(true); var controller = new UserController(serviceMock.Object, serviceOfferMock.Object, serviceOrderMock.Object); controller.ControllerContext = controllerContext.Object; var task = controller.ChangeEmail(mail);//Task<actionRsult>> var result = task.Result; Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult)); RedirectToRouteResult routeResult = result as RedirectToRouteResult; Assert.AreEqual(routeResult.RouteValues["action"], "UserProfile"); Assert.AreEqual(routeResult.RouteValues["controller"], "User"); } catch { Assert.Fail(); } }
public IActionResult ChangeEmailPost(ChangeEmailViewModel viewModel) { viewModel.ParseAndValidateParameters(Request, m => m.NewEmailAddress); if (viewModel.HasAnyErrors()) { return(View("ChangeEmail", viewModel)); } User user = ControllerHelper.GetGpgUserFromAspNetUser(User, dataRepository); if (viewModel.NewEmailAddress == user.EmailAddress) { viewModel.AddErrorFor(m => m.NewEmailAddress, "The new email address must be different to your current email address"); return(View("ChangeEmail", viewModel)); } if (OtherUserWithThisEmailAddressAlreadyExists(viewModel.NewEmailAddress)) { viewModel.AddErrorFor(m => m.NewEmailAddress, "This email address is already taken by another user"); return(View("ChangeEmail", viewModel)); } SendVerificationEmail(viewModel.NewEmailAddress, user); return(View("PleaseVerifyNewEmailAddress", viewModel.NewEmailAddress)); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { IdentityResult isChanged = new IdentityResult("Nu s-a putut modifica!"); if (!ModelState.IsValid) { return(View(model)); } var verifyUser = await UserManager.FindAsync(User.Identity.Name, model.Password); if (verifyUser != null) { verifyUser.Email = model.Email; isChanged = UserManager.Update(verifyUser); if (isChanged.Succeeded) { return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeEmailSuccess })); } AddErrors(isChanged); } else { ModelState.AddModelError("Parola actuala", "Parola nu este corecta"); } return(View(model)); }
public ActionResult ChangeEmail(ChangeEmailViewModel model) { return(this.RedirectToAction("ExternalNotify", "Account", new { area = string.Empty })); if (this.ModelState.IsValid) { if (this.Data.Users.All().Any(x => x.Email == model.Email)) { this.ModelState.AddModelError("Email", Resources.Account.AccountViewModels.Email_already_registered); } var passwordVerificationResult = this.UserManager.PasswordHasher.VerifyHashedPassword(this.UserProfile.PasswordHash, model.Password); if (passwordVerificationResult != PasswordVerificationResult.Success) { this.ModelState.AddModelError("Password", Resources.Account.AccountViewModels.Incorrect_password); } if (this.ModelState.IsValid) { var currentUser = this.Data.Users.GetById(this.UserProfile.Id); currentUser.Email = model.Email; this.Data.SaveChanges(); this.TempData[GlobalConstants.InfoMessage] = "Success"; return(this.RedirectToAction("Profile", new { controller = "Users", area = string.Empty })); } } return(this.View(model)); }
public async Task <IActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(View(model)); } User user = await userManager.FindByIdAsync(model.Id); IdentityResult emailResult = await userManager.SetEmailAsync(user, model.NewEmail); if (!emailResult.Succeeded) { foreach (var error in emailResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); return(View(model)); } } bool passwordResult = await userManager.CheckPasswordAsync(user, model.Password); if (!passwordResult) { ModelState.AddModelError(string.Empty, "Incorrect password"); return(View(model)); } return(RedirectToAction("Index", "Home")); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel profile) { var result = await _userService.SetEmailAsync(profile.Id, profile.Email); return(RedirectToAction("Details", "Usuarios", new { id = profile.Id })); }
public async Task <IActionResult> ChangeEmail(ChangeEmailViewModel model) { if (ModelState.IsValid) { var user = await userManager.GetUserAsync(HttpContext.User); if (user == null) { return(View("NotFound")); } var checkEmail = await userManager.FindByEmailAsync(model.NewEmail); if (checkEmail != null) { TempData["AlreadyInUseEmail"] = "This email already exists"; ModelState.AddModelError(string.Empty, "This email exists"); return(View()); } var token = await userManager.GenerateChangeEmailTokenAsync(user, model.NewEmail); var callback = Url.Action(nameof(EmailChangedConfirmation), "Account", new { token, email = model.NewEmail }, Request.Scheme); var message = new Message(new string[] { user.Email }, "Change Email confirmation", callback); await emailSender.SendEmailAsync(message); TempData["ChangeEmail"] = "An email confirmation link has been sent to email successfully!"; return(RedirectToAction(nameof(UserProfile))); } return(View(model)); }
public async Task <IActionResult> ChangeEmail([FromForm] ChangeEmailViewModel formData) { var checkResult = await CheckUserRegisteredOkAsync(); if (checkResult != null) { return(checkResult); } // return to page if there are errors if (ModelState.IsValid == false) { return(View(nameof(ChangeEmail), formData)); } // initialize change email process var errors = await ChangeEmailService.InitiateChangeEmailAsync(formData.EmailAddress, VirtualUser); if (errors.ErrorCount > 0) { ModelState.Merge(errors); return(View(nameof(ChangeEmail), formData)); } // confirm email change link sent var changeEmailModel = new ChangeEmailStatusViewModel { OldEmail = VirtualUser.EmailAddress, NewEmail = formData.EmailAddress }; // go to pending page return(RedirectToAction(nameof(ChangeEmailPending), new { data = Encryption.EncryptModel(changeEmailModel) })); }
public async Task <JsonResult> ChangeEmail(ChangeEmailViewModel model) { if (ModelState.IsValid) { var loggedUser = Person.GetLoggedPerson(User); loggedUser = UserManager.FindById(loggedUser.Id); if (!loggedUser.ChangeEmailDate.HasValue || loggedUser.ChangeEmailDate.Value.Date < DateTime.Now.Date) { loggedUser.ChangeEmailDate = DateTime.Now; loggedUser.DailyChangeMailCount = 0; } else if (loggedUser.DailyChangeMailCount > 2) { var jsonResult = new Result() { Errors = new System.Collections.Generic.List <string>(), Succeeded = false }; jsonResult.Errors.Add("Wykorzystałeś maksymalną dzienną liczbę zmian."); return(Json(jsonResult)); } loggedUser.DailyChangeMailCount = (loggedUser.DailyChangeMailCount ?? 0) + 1; var result = await loggedUser.ChangeEmailAsync(UserManager, Request, model.Email); return(Json(result)); } return(getErrorsFromModel()); }
private ManageAccountViewModel GetBaseManageAccountViewModel() { ManageAccountViewModel viewModel = new ManageAccountViewModel(); string currentUserId = User.Identity.GetUserId(); ApplicationUser user = userManager.FindById(currentUserId); viewModel.PasswordViewModel = HasPassword() ? (PasswordViewModel) new ChangePasswordViewModel() : new SetPasswordViewModel(); ChangeEmailViewModel emailViewModel = new ChangeEmailViewModel(); emailViewModel.EmailAddress = user.Email; viewModel.ChangeEmailViewModel = emailViewModel; var bggUser = _userRetriever.RetrieveUserInformation(user).BoardGameGeekUser; if (bggUser != null) { viewModel.BoardGameGeekIntegrationModel = new BoardGameGeekIntegrationModel { BoardGameGeekUserName = bggUser.Name, AvatarUrl = bggUser.Avatar, IntegrationComplete = true, BoardGameGeekUserUrl = BoardGameGeekUriBuilder.BuildBoardGameGeekUserUri(bggUser.Name) }; } return(viewModel); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { if (Adxstudio.Xrm.Configuration.PortalSettings.Instance.Ess.IsEss) { return(HttpNotFound()); } if (ModelState.IsValid) { var userId = User.Identity.GetUserId(); var result = ViewBag.Settings.LocalLoginByEmail ? await UserManager.SetUsernameAndEmailAsync(userId, model.Email, model.Email) : await UserManager.SetEmailAsync(userId, model.Email); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(userId); if (user != null) { await SignInAsync(user, isPersistent : false); } return(ViewBag.Settings.EmailConfirmationEnabled ? RedirectToAction("ConfirmEmailRequest", new { Message = ManageMessageId.ChangeEmailSuccess }) : RedirectToProfile(ManageMessageId.ChangeEmailSuccess)); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { ViewBag.Message = "Please enter correct information"; return(View(model)); } var user = Session["user"] as TblUser; if (model.OldEmail.Equals(user.Email)) { user.Email = model.NewEmail; zTest2DBEntities db = new zTest2DBEntities(); db.TblUsers.Find(user.UserId).Email = model.NewEmail; db.SaveChanges(); Session["welcome msg"] = "You successfully changed your email address!"; return(RedirectToAction("Index", "Manage")); } else { ViewBag.Message = "Please enter correct information"; return(View(model)); } }
public ActionResult ChangeEmail(ChangeEmailViewModel model) { if (TravelExpertsData.IsUniqueEmail(model.NewEmail, out string error)) { Customer curr = GetCurrentCustomer(); // make sure we found customer if (curr == null) { ModelState.AddModelError(String.Empty, "Sorry an error occured while trying to find you. Please try log in again."); return(View()); } curr.CustEmail = model.NewEmail; if (model.Update(curr)) { return(RedirectToAction("Index", new { Message = ManageMessageId.EditEmailSuccess })); } // something went wrong return(RedirectToAction("Index", new { Message = ManageMessageId.Error })); } // an account is already linked if (!string.IsNullOrEmpty(error)) { ModelState.AddModelError(string.Empty, "An account is already linked to this email."); } return(View()); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { ApplicationDbContext ctx = ApplicationDbContext.Create(); var user = ctx.Users.Find(User.Identity.GetUserId()); if (ModelState.IsValid) { var userE = UserManager.FindByEmail(model.Email); if (userE != null) { ModelState.AddModelError("", "User with that email is already registered."); return(View(model)); } else { user.Email = model.Email; ctx.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeEmailSuccess })); } } else { // ModelState.AddModelError("", "Email is not good."); return(View(model)); } }
public async Task <ActionResult> ChangeEmail([FromBody] ChangeEmailViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByIdAsync(User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value); if (user != null) { //doing a quick swap so we can send the appropriate confirmation email user.UnConfirmedEmail = user.Email; user.Email = model.UnConfirmedEmail; user.EmailConfirmed = false; var result = await _userManager.UpdateAsync(user); if (result.Succeeded) { var tempUnconfirmed = user.Email; user.Email = user.UnConfirmedEmail; user.UnConfirmedEmail = tempUnconfirmed; result = await _userManager.UpdateAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Uri.UriSchemeHttps); //Once routes are fixed remove this substr //Current need to remove the /Account from start of URL because //There is a conflict with the routes on client side for /Account var updatedCallbackUrl = callbackUrl.Remove(callbackUrl.IndexOf("/Account"), 8); await _emailSender.SendEmailChangeConfirmationAsync(new List <string>() { user.Email, user.UnConfirmedEmail }, updatedCallbackUrl); } } } return(BadRequest()); }
public async Task <ActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(RedirectToAction("ChangeEmail", "Manage")); } var user = await UserManager.FindByEmailAsync(model.ConfirmedEmail); var userId = user.Id; if (user != null) { //doing a quick swap so we can send the appropriate confirmation email user.UnConfirmedEmail = user.Email; user.Email = model.UnConfirmedEmail; user.EmailConfirmed = false; var result = await UserManager.UpdateAsync(user); if (result.Succeeded) { string callbackUrl = await SendEmailConfirmationTokenAsync(userId, "Confirm your new email"); var tempUnconfirmed = user.Email; user.Email = user.UnConfirmedEmail; user.UnConfirmedEmail = tempUnconfirmed; result = await UserManager.UpdateAsync(user); callbackUrl = await SendEmailConfirmationWarningAsync(userId, "You email has been updated to: " + user.UnConfirmedEmail); } } return(RedirectToAction("Index", "Manage")); }
internal virtual ManageAccountViewModel GetBaseManageAccountViewModel() { var viewModel = new ManageAccountViewModel(); var currentUserId = User.Identity.GetUserId(); var user = _userManager.FindById(currentUserId); viewModel.PasswordViewModel = HasPassword() ? (PasswordViewModel) new ChangePasswordViewModel() : new SetPasswordViewModel(); var emailViewModel = new ChangeEmailViewModel(); emailViewModel.EmailAddress = user.Email; viewModel.ChangeEmailViewModel = emailViewModel; var userInformation = _userRetriever.RetrieveUserInformation(user); var bggUser = userInformation.BoardGameGeekUser; if (bggUser != null) { viewModel.BoardGameGeekIntegrationModel = new BoardGameGeekIntegrationModel { BoardGameGeekUserName = bggUser.Name, AvatarUrl = bggUser.Avatar, IntegrationComplete = true, BoardGameGeekUserUrl = BoardGameGeekUriBuilder.BuildBoardGameGeekUserUri(bggUser.Name) }; } viewModel.GamingGroupsSummary = new GamingGroupsSummaryViewModel { ShowForEdit = true, GamingGroups = userInformation.GamingGroups.Select(x => _transformer.Transform <GamingGroupSummaryViewModel>(x)).ToList() }; return(viewModel); }
public ActionResult ChangeEmail() { //prevents users from accessing the form if they are not logged in Account account = GetAccount(); if (account == null) { return(Content("You are not logged in. Please login to change your email")); } //prevents admin users from accessing this feature var adminUser = accountPermissionDAO.FetchByEmail(account.email); if (adminUser != null) { return(Content("This feature is not available to admin users")); } ChangeEmailViewModel model = new ChangeEmailViewModel(); model.userSession = userSession.LoggedIn; model.loggedInAccount = account; model.loggedInAccountID = account.accountID; model.adminUser = false; return(View(model)); }
public async Task <ActionResult> ChangeEmail(String NewEmail, [Bind("NewEmail")] ChangeEmailViewModel model) { if (!ModelState.IsValid) { return(View()); } AppUser userLoggedIn = await _userManager.FindByNameAsync(User.Identity.Name); userLoggedIn.Email = NewEmail; _db.SaveChanges(); IndexViewModel ivm = new IndexViewModel(); //populate the view model ivm.Email = userLoggedIn.Email; ivm.UserName = userLoggedIn.UserName; ivm.HasPassword = true; ivm.UserID = userLoggedIn.Id; ivm.FirstName = userLoggedIn.FirstName; ivm.LastName = userLoggedIn.LastName; ivm.PhoneNumber = userLoggedIn.PhoneNumber; ivm.Address = userLoggedIn.StAddress + " , " + userLoggedIn.City + ", " + userLoggedIn.State + " " + userLoggedIn.ZipCode; return(View("Index", ivm)); }
public async Task <IActionResult> Index(ChangeEmailViewModel model) { if (!(await _siteService.GetSiteSettingsAsync()).As <ChangeEmailSettings>().AllowChangeEmail) { return(NotFound()); } if (ModelState.IsValid) { var user = await _userService.GetAuthenticatedUserAsync(User); var userWithEmail = await _userManager.FindByEmailAsync(model.Email); if (((User)user).Email == model.Email) { ModelState.AddModelError("Email", S["This email is already your current one."]); } else if (userWithEmail != null && user.UserName != userWithEmail.UserName) { ModelState.AddModelError("Email", S["A user with the same email already exists."]); } else { if (await _userService.ChangeEmailAsync(user, model.Email, (key, message) => ModelState.AddModelError(key, message))) { return(RedirectToLocal(Url.Action("ChangeEmailConfirmation", "ChangeEmail"))); } } } return(View(model)); }
public async Task<ActionResult> ChangeEmail(ChangeEmailViewModel model) { if (this.ModelState.IsValid) { if (this.UserManager.Users.Any(x => x.Email == model.NewEmail)) { this.AddErrors(new IdentityResult(new string[] { "This email is already registered." })); } var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId()); var passwordVerificationResult = this.UserManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, model.Password); if (passwordVerificationResult != PasswordVerificationResult.Success) { this.AddErrors(new IdentityResult(new string[] { "Incorrect password." })); } if (this.ModelState.IsValid) { var result = await this.UserManager.SetEmailAsync(User.Identity.GetUserId(), model.NewEmail); if (result.Succeeded) { return this.RedirectToAction("Index", new { Message = ManageMessageId.ChangeEmailSuccess }); } else { this.AddErrors(result); } } } return this.View(model); }
public async Task<IActionResult> ChangeEmail(ChangeEmailViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUser(); if (user != null) { if(!await _userManager.CheckPasswordAsync(user, model.Password)) { ModelState.AddModelError(nameof(model.Password), "The password supplied is not correct"); return View(model); } var existingUser = await _userManager.FindByEmailAsync(model.NewEmail.Normalize()); if(existingUser != null) { // The username/email is already registered ModelState.AddModelError(nameof(model.NewEmail), "The email supplied is already registered"); return View(model); } user.PendingNewEmail = model.NewEmail; await _userManager.UpdateAsync(user); await BuildCallbackUrlAndSendNewEmailAddressConfirmationEmail(user, model.NewEmail); return RedirectToAction(nameof(EmailConfirmationSent)); } return RedirectToAction(nameof(Microsoft.EntityFrameworkCore.Metadata.Internal.Index), new { Message = ManageMessageId.Error }); }