public async Task <ActionResult> ResetPassword(ResetPasswordInputModel inputModel, CancellationToken cancellationToken) { var existingAccount = await _accountManager.GetAsync(int.Parse(inputModel.AccountId), cancellationToken); if (existingAccount == null) { return(BadRequest("invalid_account_id", "Account not found.")); } if (existingAccount.ResetPasswordToken != inputModel.Token) { return(BadRequest("invalid_code", "Link is not valid.")); } if (existingAccount.ResetPasswordTokenGenerationTime?.AddHours(48) < DateTime.UtcNow) { return(BadRequest("expired_code", "Link is expired.")); } existingAccount.PasswordHash = PasswordHash.CreateHash(inputModel.NewPassword); existingAccount.ResetPasswordToken = null; existingAccount.ResetPasswordTokenGenerationTime = null; await _accountManager.SaveAsync(existingAccount, cancellationToken); return(Ok()); }
public async Task <IActionResult> ResetPassword([FromForm] ResetPasswordInputModel inputModel, [FromQuery] string returnUrl) { if (!ModelState.IsValid) { var viewModel = BuildResetPasswordViewModel(inputModel.Code, returnUrl); return(View(viewModel)); } var user = await _userManager.FindByEmailAsync(inputModel.EmailAddress); if (user == null) { ModelState.AddModelError(nameof(inputModel.EmailAddress), "Please check the email address"); var viewModel = BuildResetPasswordViewModel(inputModel.Code, returnUrl); return(View(viewModel)); } var result = await _userManager.ResetPasswordAsync(user, inputModel.Code, inputModel.Password); if (!result.Succeeded) { ModelState.AddModelError(nameof(inputModel.EmailAddress), "Please check the email address"); var viewModel = BuildResetPasswordViewModel(inputModel.Code, returnUrl); return(View(viewModel)); } return(RedirectToRoute("ResetPasswordConfirmation", new { user.EmailAddress, returnUrl })); }
/// <summary> /// Perform the reset password process based on the given input model /// </summary> /// <param name="inputModel">The reset password input model object</param> /// <returns>Reset password view model correctly populated for display, regardless of mode</returns> public ResetPasswordViewModel ResetPassword(ResetPasswordInputModel inputModel) { ResetPasswordViewModel viewModel; switch (inputModel.Mode) { case GlobalConstants.PASSWORD_ENC_MODE_INITIAL: viewModel = new ResetPasswordViewModel(true); viewModel.Mode = GlobalConstants.PASSWORD_ENC_MODE_INITIAL; break; case GlobalConstants.PASSWORD_ENC_MODE_USER_SIGNED_IN: viewModel = new ResetPasswordViewModel(true); viewModel.Mode = GlobalConstants.PASSWORD_ENC_MODE_USER_SIGNED_IN; break; case GlobalConstants.PASSWORD_ENC_MODE_RESPONSE: viewModel = resetUserPassword(inputModel); break; default: viewModel = new ResetPasswordViewModel(true); break; } return(viewModel); }
public async Task <IActionResult> ResetPassword(ResetPasswordInputModel model) { if (!ModelState.IsValid) { return(View(model)); } User user; using (_db.DisableTenantFilter()) { user = await _userManager.FindByIdAsync(model.UserId); if (user == null) { ModelState.AddModelError(nameof(model.UserId), "User wasn't found"); return(View(model)); } } _db.SetTenantFilterValue(user.TenantId); var identityResult = await _userManager.ResetPasswordAsync(user, model.Code, model.NewPassword); if (!identityResult.Succeeded) { var error = identityResult.Errors.FirstOrDefault(); var errorMessage = error != null ? error.Code + ": " + error.Description : "Identity error"; ModelState.AddModelError("", errorMessage); return(View(model)); } return(RedirectToAction("PasswordResetSuccess")); }
public async Task <IActionResult> ResetPassword(ResetPasswordInputModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { return(View(model)); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { //return RedirectToAction("ResetPasswordConfirmation"); return(View("ResetPasswordConfirmation")); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(View(model)); }
public BaseResponseModel ResetPassword(ResetPasswordInputModel inputModel) { // Get existing user var vm = new BaseResponseModel(); var validationState = new ValidationDictionary(); inputModel.ValidateRequest(validationState); if (validationState.IsValid) { var user = UserService.GetUserByResetToken(inputModel.ResetToken); if (user != null) { UserService.ResetPassword(user, inputModel.Password); vm.Success = true; } else { validationState.AddError("ResetToken", "Invalid reset token."); } } vm.Errors = validationState.Errors; return(vm); }
public ActionResult ResetPassword(ResetPasswordInputModel model) { bool resetComplete = false; string error = string.Empty; if (ModelState.IsValid) { try { var securityParams = HttpUtility.ParseQueryString(model.SecurityToken); this.Model.ResetUserPassword(model.NewPassword, model.ResetPasswordAnswer, securityParams); resetComplete = true; } catch (NotSupportedException) { error = Res.Get <LoginFormResources>().ResetPasswordNotEnabled; } catch (ResetPasswordUserNotFoundException) { error = Res.Get <LoginFormResources>().ResetPasswordIncorrectResetPasswordLink; } catch (Exception ex) { if (string.Compare(ex.Message, Res.Get <ErrorMessages>().WrongPasswordAnswer) == 0) { error = Res.Get <LoginFormResources>().ResetPasswordIncorrectAnswerErrorMessage; } else { error = Res.Get <LoginFormResources>().ResetPasswordGeneralErrorMessage; } } } else { try { error = Res.Get <LoginFormResources>().Get(this.Model.GetErrorFromViewModel(this.ModelState)); } catch (KeyNotFoundException) { error = Res.Get <LoginFormResources>().ResetPasswordGeneralErrorMessage; } } error = HttpUtility.UrlEncode(error); var validator = ObjectFactory.Resolve <IRedirectUriValidator>(); var pageUrl = this.Model.GetPageUrl(null); if (validator.IsValid(pageUrl)) { var queryString = string.Format("{0}&resetComplete={1}&error={2}", model.SecurityToken, resetComplete, error); return(this.Redirect(string.Format("{0}/ResetPassword?{1}", pageUrl, queryString))); } return(this.Redirect("~/")); }
/// <summary> /// Does the main work for resetting a user's password. Validates their token, then sends the details to the backend for update. /// </summary> /// <param name="inputModel">The reset password input model</param> /// <returns>viewModel for handling</returns> private ResetPasswordViewModel resetUserPassword(ResetPasswordInputModel inputModel) { //Initialise everything we need. ResetPasswordViewModel viewModel = new ResetPasswordViewModel(true); ErrorObj talentErrObj = new ErrorObj(); DECustomer deCust = new DECustomer(); Mapper.CreateMap <ResetPasswordInputModel, DECustomer>(); DECustomerV11 deCustV11 = new DECustomerV11(); PasswordHash pH = new PasswordHash(); //Make sure token is still valid inputModel = validateToken(inputModel); if (inputModel.IsValid) { //Hash the user's new password. inputModel.NewHashedPassword = pH.HashSalt(inputModel.NewPassword, Environment.Settings.DefaultValues.SaltString); //Map the inputModel parameters to a DECustomer object. deCust = Mapper.Map <DECustomer>(inputModel); deCust.Source = GlobalConstants.SOURCE; deCustV11.DECustomersV1.Add(deCust); _talCust.DeV11 = deCustV11; _talCust.Settings = Environment.Settings.DESettings; //Backend call, and error checking talentErrObj = _talCust.ResetPassword(); viewModel.Error = Data.PopulateErrorObject(talentErrObj, _talCust.ResultDataSet, _talCust.Settings, null); if (!viewModel.Error.HasError) { viewModel.Mode = GlobalConstants.PASSWORD_ENC_MODE_RESPONSE; expireUsedToken(inputModel); } else { viewModel.Mode = GlobalConstants.PASSWORD_ENC_MODE_INITIAL; if (viewModel.Error == null) { viewModel.Error = new ErrorModel(); viewModel.Error.HasError = true; viewModel.Error.ErrorMessage = viewModel.GetPageText("UnspecifiedError"); } } } else { viewModel.Mode = GlobalConstants.PASSWORD_ENC_MODE_INITIAL; if (viewModel.Error == null) { viewModel.Error = new ErrorModel(); viewModel.Error.HasError = true; viewModel.Error.ErrorMessage = viewModel.GetPageText("GenericError"); } } return(viewModel); }
/// <summary> /// Expire the used tokens based on the current token /// </summary> /// <param name="inputModel">The reset password input model</param> public void expireUsedToken(ResetPasswordInputModel inputModel) { int affectedRows = 0; affectedRows = TDataObjects.ProfileSettings.tblForgottenPassword.SetTokenAsUsed(inputModel.HashedToken); if (affectedRows != 1) { _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Token expiry failure.", "RPW-005", "Could not set tokens to expired for customer: " + inputModel.CustomerNumber, "PasswordEncryptionLog"); } }
public ActionResult ResetPassword(int Id) { if (Id == 0 || Id == null) { Id = _userManager.GetIdByName(HttpContext.User.Identity.Name.ToString()); } ResetPasswordInputModel resetPasswordInput = _userManager.GetUserForResetPassword(Id); return(View(resetPasswordInput)); }
public async Task <IdentityResult> ResetPassword([FromBody] ResetPasswordInputModel request) { if (!this.ModelState.IsValid) { throw new InvalidOperationException(); } var user = await _userManager.FindByEmailAsync(request.Email); return(await _userManager.ResetPasswordAsync(user, request.Token, request.Password)); }
public async Task <IActionResult> ResetPasswordAsync([FromForm] ResetPasswordInputModel input) { if (await AuthService.ResetPasswordAsync(input)) { return(Ok("Password cambiata")); } else { return(BadRequest("Impossibile cambiare la password")); } }
public Task BindModelAsync(ModelBindingContext bindingContext) { string username = bindingContext.ValueProvider.GetValue("username").FirstValue; string token = bindingContext.ValueProvider.GetValue("token").FirstValue; string password = bindingContext.ValueProvider.GetValue("password").FirstValue; string confirmPassword = bindingContext.ValueProvider.GetValue("confirmPassword").FirstValue; var input = new ResetPasswordInputModel(username, token, password, confirmPassword); bindingContext.Result = ModelBindingResult.Success(input); return(Task.CompletedTask); }
public IActionResult OnGet(string code = null) { if (code == null) { return(this.BadRequest("A code must be supplied for password reset.")); } this.Input = new ResetPasswordInputModel { Code = code, }; return(this.Page()); }
public IActionResult OnGet(string code = null) { if (code == null) { return(this.BadRequest("A code must be supplied for password reset.")); } else { this.Input = new ResetPasswordInputModel { Code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)), }; return(this.Page()); } }
public async Task <bool> ResetPasswordAsync(ResetPasswordInputModel input) { try { IdentityUser user = await UserManager.FindByNameAsync(input.Username); var result = await UserManager.ResetPasswordAsync(user, input.Token, input.Password); return(true); } catch { return(false); } }
public IActionResult ResetPassword(string code = null) { if (code == null) { return(View("Error", new ErrorViewModel { Error = new ErrorMessage { Error = "Žádost neobsahuje potvrzovací kód." } })); } else { var model = new ResetPasswordInputModel { Code = code }; return(View(model)); } }
public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordInputModel inputModel) { var user = await _userManager.FindByEmailAsync(inputModel.Email); if (user == null) { return(NotFound($"User with email {inputModel.Email} does not exist.")); } var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(inputModel.Code)); var result = await _userManager.ResetPasswordAsync(user, code, inputModel.Password); if (!result.Succeeded) { return(BadRequest(result.Errors)); } return(Ok()); }
public ActionResult ResetPassword(ResetPasswordInputModel model) { bool resetComplete = false; string error = string.Empty; if (ModelState.IsValid) { try { var securityParams = HttpUtility.ParseQueryString(model.SecurityToken); this.Model.ResetUserPassword(model.NewPassword, model.ResetPasswordAnswer, securityParams); resetComplete = true; } catch (NotSupportedException) { error = Res.Get <LoginFormResources>().ResetPasswordNotEnabled; } catch (Exception) { error = Res.Get <LoginFormResources>().ResetPasswordGeneralErrorMessage; } } else { try { error = Res.Get <LoginFormResources>().Get(this.Model.GetErrorFromViewModel(this.ModelState)); } catch (KeyNotFoundException) { error = Res.Get <LoginFormResources>().ResetPasswordGeneralErrorMessage; } } error = HttpUtility.UrlEncode(error); var pageUrl = this.Model.GetPageUrl(null); var queryString = string.Format("{0}&resetComplete={1}&error={2}", model.SecurityToken, resetComplete, error); return(this.Redirect(string.Format("{0}/ResetPassword?{1}", pageUrl, queryString))); }
public IActionResult OnGet(string code = null, string mobile = null, string mobileDeepLink = null) { MobileMode = mobile; if (string.IsNullOrWhiteSpace(code)) { return(BadRequest("A code must be supplied for password reset.")); } if (!string.IsNullOrWhiteSpace(mobileDeepLink)) { return(Redirect($"{mobileDeepLink}&code={code}")); } Input = new ResetPasswordInputModel { Code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)) }; return(Page()); }
public async Task <IdentityResult> ResetPassword(ResetPasswordInputModel model) { _logger.LogInformation(GetLogMessage("Email: {0}; Code: {1}"), model.Email, model.Code); var user = await _userManager.FindByEmailAsync(model.Email); var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { await Task.Run(() => { RaiseEvent(new ResetPasswordEvent() { PersonId = user.Id }); }); } return(result); }
public async Task <ActionResult> ResetPassword(ResetPasswordInputModel inputModel) { try { var confirmEmailIdentityResult = await this.userService.ResetPassword( inputModel.ResetPasswordToken, inputModel.Email, inputModel.NewPassword); if (confirmEmailIdentityResult.Succeeded) { return(this.Ok()); } return(this.BadRequest(confirmEmailIdentityResult.Errors)); } catch (Exception ex) { this.loggerService.LogException(ex); return(this.BadRequest()); } }
public async Task <IActionResult> ResetPassword([FromForm] ResetPasswordInputModel inputModel) { var user = await this.userManager.FindByEmailAsync(inputModel.Email); if (user == null) { // Don't reveal that the user does not exist return(this.Ok()); } var result = await this.userManager.ResetPasswordAsync(user, inputModel.Code, inputModel.Password); if (result.Succeeded) { return(this.Ok()); } foreach (var error in result.Errors) { logger.LogError(error.Description); } return(Ok()); }
/// <summary> /// Validates the user's token in tbl_forgotten_password /// </summary> private ResetPasswordInputModel validateToken(ResetPasswordInputModel inputModel) { string customerNumber = string.Empty; string token = string.Empty; string hashedToken = string.Empty; PasswordHash passHash = new PasswordHash(); DataTable tokenRows = new DataTable(); DateTime timeNow; customerNumber = inputModel.CustomerNumber; token = inputModel.Token; timeNow = inputModel.DateNow; hashedToken = passHash.HashTokenWithCurrentAlgorithm(token); //Get row from table tokenRows = TDataObjects.ProfileSettings.tblForgottenPassword.GetByHashedToken(hashedToken); if (tokenRows.Rows.Count > 0) { //Check everything individually. Since certain patterns indicate hacking attempts and should be logged if (tokenRows.Rows.Count > 1) { TDataObjects.ProfileSettings.tblForgottenPassword.SetTokenAsUsed(hashedToken); _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-001", "More than 1 token found in tbl_forgotten_password. Customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } else { //Check customer number if (tokenRows.Rows[0]["CUSTOMER_NUMBER"].ToString().Trim() == customerNumber) { inputModel.IsCustomerValid = true; inputModel.EmailAddress = tokenRows.Rows[0]["EMAIL_ADDRESS"].ToString().Trim(); inputModel.UserName = customerNumber; } else { inputModel.IsCustomerValid = false; _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-002", "customer number in tbl_forgotten_password doesn't match the requested token. A user is attempting to reset a password suspiciously with the customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } //Check token if (tokenRows.Rows[0]["HASHED_TOKEN"].ToString().Trim() == hashedToken) { inputModel.IsTokenValid = true; inputModel.HashedToken = hashedToken; } else { inputModel.IsTokenValid = false; _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-003", "hashed token in tbl_forgotten_password doesn't match the requested token. A user is attempting to reset a password suspiciously with the customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } //Check date if (Convert.ToDateTime(tokenRows.Rows[0]["EXPIRE_TIMESTAMP"]) >= timeNow) { inputModel.IsDateValid = true; } else { inputModel.IsDateValid = false; _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-004", "The date in tbl_forgotten_password doesn't match the requested token. Token has probably expired customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } //If everything is valid then the input model is valid if (inputModel.IsTokenValid && inputModel.IsDateValid && inputModel.IsCustomerValid) { inputModel.IsValid = true; } else { inputModel.IsValid = false; } } } else { //Token not valid, error. inputModel.IsValid = false; _talCust.Settings.Logging.ErrorObjectLog("ResetPassword.aspx - Reset Password validation fail", "RPW-000", "No token found in tbl_forgotten_password. A user is attempting to reset a password suspiciously with the customer number:" + inputModel.CustomerNumber, "PasswordEncryptionLog"); } return(inputModel); }
public async Task <ActionResult> ResetPassword(ResetPasswordInputModel model) { //model.OldPassword = ""; #if DEBUG Debug.WriteLine("UserName="******"Password="******"ConfirmPassword="******"OldPassword="******"Id=" + model.Id.ToString()); #endif if (ModelState.IsValid) { #if DEBUG Debug.WriteLine("Model is valid"); #endif var user = await _userManager.FindByNameAsync(model.UserName); if (user != null) { #if DEBUG Debug.WriteLine("user is not null"); #endif /* * var checkOldPassword =await _userManager.CheckPasswordAsync(user, model.OldPassword); * * if (checkOldPassword) * { */ var result = await _userManager.RemovePasswordAsync(user.UserID); if (result.Succeeded) { #if DEBUG Debug.WriteLine("Password is removed to succeeded"); #endif var result2 = await _userManager.AddPasswordAsync(user.UserID, model.Password); if (result2.Succeeded) { #if DEBUG Debug.WriteLine("Password is added to succeeded"); #endif var result3 = await _userManager.SetSigninEndDateAsync(user); #if DEBUG if (result3) { Debug.WriteLine("SetSigninEndDateAsync is well done"); } #endif var result4 = await _userManager.ResetAccessFailedCountAsync(user.UserID); #if DEBUG if (result4.Succeeded) { Debug.WriteLine("ResetAccessFailedCountAsync is executed."); } #endif /* * result4 = await _userManager.SetChangePasswordEndDateAsync(user); #if DEBUG * if (result4.Succeeded) * { * Debug.WriteLine("SetChangePasswordEndDateAsync is executed."); * } #endif * * result4 = await _userManager.SetPasswordEnabledAsync(user, false); #if DEBUG * if (result4.Succeeded) * { * Debug.WriteLine("SetPasswordEnabledAsync is executed."); * } #endif */ return(RedirectToAction("List")); } } // } /* else * { * // Активизирована ли функция блокировки учётки в системе * if (_userManager.LockoutEnabled) * { * #if DEBUG * Debug.WriteLine("++++ GetLockoutEnabledAsync is enabled"); #endif * // Увелечение счётчика неудачных попыток ввода пароля * if (await _userManager.AccessFailedAsync(user.UserID) == IdentityResult.Success) * { #if DEBUG * Debug.WriteLine("~~~ AccessFailedAsync is working!"); #endif * if (await _userManager.IsLockedOutAsync(user.UserID)) * { #if DEBUG * Debug.WriteLine("Account is locked out!"); #endif * //Заблокировать учётку * return View("Lockout"); * } * * * } * * * } * * } */ } } #if DEBUG Debug.WriteLine("Error is occured in ResetPassword"); #endif return(View(model)); }