public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { // ChangePassword는 특정 실패 시나리오에서 false를 반환하지 않고 // 예외를 throw합니다. bool changePasswordSucceeded; try { MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */); changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "현재 암호가 정확하지 않거나 새 암호가 잘못되었습니다."); } } // 이 경우 오류가 발생한 것이므로 폼을 다시 표시하십시오. return View(model); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (!ModelState.IsValid) return View(model); servicoAutorizacao.AlterarSenha(User.Identity.Name, model.OldPassword, model.NewPassword); return RedirectToAction("ChangePasswordSuccess"); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { var status = _userService.ChangePassword(UserProfile.Current, model.OldPassword, model.NewPassword); switch (status) { case ChangePasswordStatus.Success: TempData.AddSuccessMessage(status.GetDescription()); return RedirectToAction("Index", "Home"); case ChangePasswordStatus.InvalidPassword: ModelState.AddModelError(string.Empty, status.GetDescription()); break; case ChangePasswordStatus.Failure: ModelState.AddModelError(string.Empty, status.GetDescription()); break; } } ViewBag.PasswordLength = _membershipSetings.MinimumPasswordLength; return View(model); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { // ChangePassword iniciará una excepción en lugar de // devolver false en determinados escenarios de error. bool changePasswordSucceeded; try { MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */); changePasswordSucceeded = currentUser.ChangePassword(EncodePassword(model.OldPassword), EncodePassword(model.NewPassword)); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "La contraseña actual es incorrecta o la nueva contraseña no es válida."); } } // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario return View(model); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (!ModelState.IsValid) { return View(model); } bool changePasswordSucceeded; try { var currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */); Debug.Assert(currentUser != null, "currentUser != null"); changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword); } catch (Exception) { changePasswordSucceeded = false; } if (!changePasswordSucceeded) { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); return View(model); } return RedirectToAction("ChangePasswordSuccess"); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { // ChangePassword will throw an exception rather // than return false in certain failure scenarios. bool changePasswordSucceeded; try { MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */); changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } // If we got this far, something failed, redisplay form return View(model); }
public ActionResult ChangePassword() { var model = new ChangePasswordModel(); model.Username = User.Identity.Name; var user = context.Accounts.FirstOrDefault(x => x.Username.Contains(model.Username)); model.Email = user.Email; return View(model); }
public void TestChangePassword() { string testUserName = "******"; string testOldPassword = "******"; string testNewPassword = "******"; var changePasswordModel = new ChangePasswordModel { OldPassword = testOldPassword, NewPassword = testNewPassword }; var accountController = new AccountController(); //Stub HttpContext var stubHttpContext = new StubHttpContextBase(); //Setup ControllerContext so AccountController will use our stubHttpContext accountController.ControllerContext = new ControllerContext(stubHttpContext, new RouteData(), accountController); //Stub IPrincipal var principal = new StubIPrincipal(); principal.IdentityGet = () => { var identity = new StubIIdentity { NameGet = () => testUserName }; return identity; }; stubHttpContext.UserGet = () => principal; RedirectToRouteResult redirectToRouteResult; //Scope the detours we're creating using (ShimsContext.Create()) { ShimMembership.GetUserStringBoolean = (identityName, userIsOnline) => { Assert.AreEqual(testUserName, identityName); Assert.AreEqual(true, userIsOnline); var memberShipUser = new ShimMembershipUser(); //Sets up a detour for MemberShipUser.ChangePassword to our mocked implementation memberShipUser.ChangePasswordStringString = (oldPassword, newPassword) => { Assert.AreEqual(testOldPassword, oldPassword); Assert.AreEqual(testNewPassword, newPassword); return true; }; return memberShipUser; }; var actionResult = accountController.ChangePassword(changePasswordModel); Assert.IsInstanceOf(typeof(RedirectToRouteResult), actionResult); redirectToRouteResult = actionResult as RedirectToRouteResult; } Assert.NotNull(redirectToRouteResult); Assert.AreEqual("ChangePasswordSuccess", redirectToRouteResult.RouteValues["Action"]); }
public HttpResponseMessage ChangePassword(ChangePasswordModel model) { model.UserID = User.UserID; ActionOutput output = _userManager.ChangePassword(model); return Request.CreateResponse<ApiActionOutput>(new ApiActionOutput { Status = output.Status, Message = output.Message }); }
public void ChangePassword(ChangePasswordModel changePasswordModel) { var db = GetDbContext(); var user = GetCurrentUser(); user.Password = EncryptPassword(changePasswordModel.NewPassword); db.SubmitChanges(); SendEmail("admin@iudico", user.Email, "Iudico Notification", "Your passord has been changed."); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { bool changePasswordSucceeded = true; try { if (ModelState.IsValid && model.OldPassword != null) { int id = ((Session)Session["Session"]).UserID; User oldUser = db.Users.Single(u => u.UserID == id); string source = model.OldPassword; using (MD5 md5Hash = MD5.Create()) { Encryptor enc = new Encryptor(); string hash = enc.GetMd5Hash(md5Hash, source); if (enc.VerifyMd5Hash(md5Hash, source, hash)) { if (hash == oldUser.Password) { source = model.NewPassword; hash = enc.GetMd5Hash(md5Hash, source); if (enc.VerifyMd5Hash(md5Hash, source, hash)) { oldUser.Password = hash; db.Users.Attach(oldUser); db.ObjectStateManager.ChangeObjectState(oldUser, EntityState.Modified); db.SaveChanges(); changePasswordSucceeded = true; } } } } } } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } // If we got this far, something failed, redisplay form return View(model); }
public ActionResult ChangePassword(int id) { User user = userService.GetUserById(id); ChangePasswordModel model = new ChangePasswordModel() { User = user }; return this.View("ChangePassword", model); }
public ActionResult ChangePassword(string key) { var model = new ChangePasswordModel(key); if (model.Key != null) { return View(model); } return RedirectToAction("Login", new { returnUrl = "/" }); }
public void ShouldNotValidateModelWhenGetActionResult() { // arrange var invalidModel = new ChangePasswordModel { }; var controllerAction = new AccountController().Action(c => c.ChangePassword(invalidModel)); var context = controllerAction.GetExecutionContext(); // act controllerAction.GetActionResult(context); //assert context.ModelState.IsValid.Should().BeTrue(); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } // If we got this far, something failed, redisplay form return View(model); }
public ActionResult ChangePassword(string Email) { var user = userRepository.GetUserProfile(Email); ChangePasswordModel dv = null; if (user != null) { dv = new ChangePasswordModel(); dv.Id = user.Id; dv.OldPassword = user.Password; } return GetView(WebConstants.View_ChangePassword, dv); //return GetView(WebConstants.View_ChangePasswordPartial, dv); }
public RedirectToRouteResult ChangePassword(ChangePasswordModel model) { string status = "Fail"; string message = "Sai mật khẩu. Vui lòng thử lại."; var user = context.Accounts.FirstOrDefault(x => x.Username == User.Identity.Name && x.Password == model.Password); if (user != null) { user.Password = model.NewPassword; context.SaveChanges(); status = "Success"; message = "Đổi mật khẩu thành công."; } TempData["Status"] = status; TempData["Message"] = message; return RedirectToAction("ChangePassword"); }
public Task<HttpResponseMessage> ChangePassword(ChangePasswordModel model) { HttpResponseMessage response = new HttpResponseMessage(); try { _service.ChangePassword(User.Identity.Name, model.Password, model.NewPassword, model.ConfirmNewPassword); response = Request.CreateErrorResponse(HttpStatusCode.OK, Messages.PasswordSuccessfulyChanges); } catch (Exception ex) { response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message); } var tsc = new TaskCompletionSource<HttpResponseMessage>(); tsc.SetResult(response); return tsc.Task; }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "Неправильный текущий пароль или недопустимый новый пароль."); } } // Появление этого сообщения означает наличие ошибки; повторное отображение формы ViewData["PasswordLength"] = MembershipService.MinPasswordLength; return View(model); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "当前密码不正确或新密码无效。"); } } // 如果我们进行到这一步时某个地方出错,则重新显示表单 ViewData["PasswordLength"] = MembershipService.MinPasswordLength; return View(model); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { ViewBag.Success = "密码修改成功。"; return View(); } else { ModelState.AddModelError("", "当前密码不正确或新密码无效。"); } } // 如果我们进行到这一步时某个地方出错,则重新显示表单 ViewBag.PasswordLength = MembershipService.MinPasswordLength; return View(model); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (!User.IsInRole("admin")) { return RedirectToAction("UserProfile", "UserPages", new { UserName = User.Identity.Name }); } if (ModelState.IsValid) { // ChangePassword will throw an exception rather // than return false in certain failure scenarios. string OldPassword; string NewPassword; bool changePasswordSucceeded; try { // Get user MembershipUser currentUser = Membership.GetUser(model.UserName); // Get old password OldPassword = currentUser.GetPassword(); // Get new password NewPassword = model.NewPassword; changePasswordSucceeded = currentUser.ChangePassword(OldPassword, NewPassword); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "OldPass:"******"NewPass:"******"User:" + model.UserName); } } // If we got this far, something failed, redisplay form return View(model); }
public void AccountController_ChangePassword_Post_ReturnsRedirectOnSuccess() { // Arrange AccountController controller = GetAccountController(); ChangePasswordModel model = new ChangePasswordModel() { OldPassword = "******", NewPassword = "******", ConfirmPassword = "******" }; // Act ActionResult result = controller.ChangePassword(model); // Assert Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult)); RedirectToRouteResult redirectResult = (RedirectToRouteResult)result; Assert.AreEqual("ChangePasswordSuccess", redirectResult.RouteValues["action"]); }
ActionOutput IUserManager.ChangePassword(ChangePasswordModel model) { byte[] oldPassword = Utility.GetEncryptedValue(model.OldPassword); byte[] newPassword = Utility.GetEncryptedValue(model.NewPassword); User user = Context.Users.Where(m => m.UserID == model.UserID && m.Password == oldPassword).FirstOrDefault(); if (user == null) return new ActionOutput { Status = ActionStatus.Error, Message = "Old password is incorrect." }; user.Password = newPassword; SaveChanges(); return new ActionOutput { Status = ActionStatus.Successfull, Message = "Password has been changed." }; }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { if (dbContext.Users.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { //var _event = new PasswordChangedEvent(User.Identity.Name, model.OldPassword, model.NewPassword); //_event.Raise(HttpContext); this.Trigger("PasswordChanged", model); //var app = App.Get(); //var user = app.Users[User.Identity.Name]; //App.Get().SendMail(SystemMails.PasswodChanged, model, user.Email); } else { ModelState.AddModelError("", Resources.Validations.Password_Incorrect); } } return PartialView(model); }
public void ChangePassword_Post_ReturnsViewIfChangePasswordFails() { // 排列 AccountController controller = GetAccountController(); ChangePasswordModel model = new ChangePasswordModel() { OldPassword = "******", NewPassword = "******", ConfirmPassword = "******" }; // 操作 ActionResult result = controller.ChangePassword(model); // 断言 Assert.IsInstanceOfType(result, typeof(ViewResult)); ViewResult viewResult = (ViewResult)result; Assert.AreEqual(model, viewResult.ViewData.Model); Assert.AreEqual("当前密码不正确或新密码无效。", controller.ModelState[""].Errors[0].ErrorMessage); Assert.AreEqual(10, viewResult.ViewData["PasswordLength"]); }
public void AccountController_ChangePassword_Post_ReturnsViewIfChangePasswordFails() { // Arrange AccountController controller = GetAccountController(); ChangePasswordModel model = new ChangePasswordModel() { OldPassword = "******", NewPassword = "******", ConfirmPassword = "******" }; // Act ActionResult result = controller.ChangePassword(model); // Assert Assert.IsInstanceOfType(result, typeof(ViewResult)); ViewResult viewResult = (ViewResult)result; Assert.AreEqual(model, viewResult.ViewData.Model); Assert.AreEqual("The current password is incorrect or the new password is invalid.", controller.ModelState[""].Errors[0].ErrorMessage); Assert.AreEqual(10, viewResult.ViewData["PasswordLength"]); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { try { if (this._userService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { return View("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "Error changing password"); } } catch (ValidationException ex) { ModelState.AddModelError("", ex.Message); } } return View(model); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { var user = userRepository.GetById(model.Id); string hPassword = Encryptor.MD5Hash(model.OldPassword); if (hPassword.Equals(user.Password)) { var result = userRepository.ChangePassword(model.Id, model.NewPassword); if (result) ModelState.AddModelError("Success", "The password is changed successful."); } else { ModelState.AddModelError("Error", "The current password did not match with old password."); } } return GetView(WebConstants.View_ChangePassword, model); //return GetView(WebConstants.View_ChangePasswordPartial, model); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (!ModelState.IsValid) { return View(model); } var user = WebSecurity.GetUserFromKey(model.Key); if (user == null) { return RedirectToAction("Login"); } var u = Membership.GetUser(user.Username); if (u == null) { return RedirectToAction("Login"); } WebSecurity.ChangePassword(u.UserName, model.Password); WebSecurity.ClearResetKey(u.UserName); return RedirectToAction("Login"); }
public async Task <IActionResult> Post([FromBody] ChangePasswordModel model) { // Validate the request if (model == null) { return(BadRequest(ApiResult.InvalidRequest())); } var result = new ApiResult(); // Validate the model if (ModelState.IsValid == false) { result.AddModelStateErrors(ModelState); return(BadRequest(result)); } // Validate the Captcha try { // Sonar-Codacy suggested ConfigureAwait if (await ValidateRecaptcha(model.Recaptcha).ConfigureAwait(false) == false) { result.Errors.Add(new ApiErrorItem { ErrorCode = ApiErrorCode.InvalidCaptcha }); } } catch (Exception ex) { result.Errors.Add(new ApiErrorItem { ErrorCode = ApiErrorCode.Generic, Message = ex.Message }); } if (result.HasErrors) { return(BadRequest(result)); } var currentUsername = GetUserName(model, result); if (result.HasErrors) { return(BadRequest(result)); } var resultPasswordChange = _passwordChangeProvider.PerformPasswordChange(currentUsername, model.CurrentPassword, model.NewPassword); if (resultPasswordChange != null) { result.Errors.Add(resultPasswordChange); } if (result.HasErrors) { Response.StatusCode = (int)HttpStatusCode.BadRequest; } return(Json(result)); }
public ActionResult ChangePassword() { var model = new ChangePasswordModel(); return(View(model)); }
/// <summary> /// To check and update the password.. /// </summary> /// <param name="users"></param> /// <returns></returns> public DataTable ChangePassword(ChangePasswordModel ChangePasswordModel) { var DbManager = new DBManager("DBConnection"); return(DbManager.GetDataTable(_StoredProcedures.UpdateUserPassword_SP, CommandType.StoredProcedure, _instanceRepository.AddParasUpdatePassword(ChangePasswordModel))); }
public async Task <IHttpActionResult> ChangePassword(ChangePasswordModel model) { return(await RunTask(() => AccountManager.ChangePasswordAsync(User, model))); }
public ActionResult ChangePassword(ChangePasswordModel model) { //DependencyResolver.SetResolver(); return(View(model)); }
public async Task <IActionResult> ChangePassword(Guid id, ChangePasswordModel changePasswordModel) { return(Ok(ApiResult <BaseResponseModel> .Success( await _userService.ChangePasswordAsync(id, changePasswordModel)))); }
public ActionResult ChangePassword(ChangePasswordModel changePassword) { changePassword.Password = GetMD5(changePassword.Password); user.changepassword(changePassword); return(View()); }
public async Task <IHttpActionResult> ChangePassword(ChangePasswordModel model) { var result = await _authRepo.ChangePassword(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); return(Ok()); }
public ActionResult ChangePassword(ChangePasswordModel model) { ModelState.Clear(); return(View(model)); }
public ChangePasswordPresenter(params object[] param) : base(param) { model = new ChangePasswordModel(); }
public async Task <Boolean> ChangePassword(ChangePasswordModel model) { var changed = await userRepository.ChangePassword(model); return(changed); }
public ActionResult ChangePassword(ChangePasswordModel model) { return(View()); }
public async Task <ActionResult <bool> > ChangePassword([FromBody] ChangePasswordModel model) { return(await this.ExecuteWithOkResponse(async() => await _profileService.ChangePassword(model))); }
//method to change the password public async Task <IdentityResult> ChangePasswordAsync(ChangePasswordModel changePassword) { var user = await _userManager.FindByIdAsync(_userService.GetUserId()); return(await _userManager.ChangePasswordAsync(user, changePassword.CurrentPassword, changePassword.NewPassword)); }
public async Task <AjaxModel <NTModel> > ChangePassword([FromBody] ChangePasswordModel model) { return(await AjaxHelper.SaveAsync(m => domain.ChangePassword(model), SecurityMessages.ChangePasswordSuccess)); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (model.NewPassword.IsNullOrWhiteSpace()) { throw new ArgumentException($"新密码不能为 Null 或空白", nameof(model.NewPassword)); } if (model.NewPassword2.IsNullOrWhiteSpace()) { throw new ArgumentException($"确认密码不能为 Null 或空白", nameof(model.NewPassword2)); } if (model.NewPassword != model.NewPassword2) { throw new ArgumentException($"两次输入密码不一致", nameof(model.NewPassword)); } var set = Setting.Current; if (model.NewPassword.Length < set.MinPasswordLength) { throw new ArgumentException($"最短密码要求{set.MinPasswordLength}位", nameof(model.NewPassword)); } // SSO 登录不需要知道原密码就可以修改,原则上更相信外方,同时也避免了直接第三方登录没有设置密码的尴尬 var ssoName = Session["Cube_Sso"] as String; var requireOldPass = ssoName.IsNullOrEmpty(); if (requireOldPass) { if (model.OldPassword.IsNullOrWhiteSpace()) { throw new ArgumentException($"原密码不能为 Null 或空白", nameof(model.OldPassword)); } if (model.NewPassword == model.OldPassword) { throw new ArgumentException($"修改密码不能与原密码一致", nameof(model.NewPassword)); } } var cur = ManageProvider.User; if (cur == null) { return(RedirectToAction("Login")); } var user = XCode.Membership.User.FindByKeyForEdit(cur.ID); var oldpass2 = model.OldPassword.MD5(); if (requireOldPass && !user.Password.EqualIgnoreCase(oldpass2)) { throw new Exception("密码错误"); } // 修改密码 user.Password = model.NewPassword; user.Update(); ViewBag.StatusMessage = "修改成功!"; if (IsJsonRequest) { return(Ok(ViewBag.StatusMessage)); } return(ChangePassword()); }
public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordModel changePasswordModel, CancellationToken cancellationToken) { var status = await _authService.ChangePassword(changePasswordModel, cancellationToken); return(Ok(status)); }
public System.Web.Http.Results.OkNegotiatedContentResult <ResponseModel> ChangePassword([FromBody] ChangePasswordModel changePasswordModel) { try { SaltedHash SH = new SaltedHash(); string strHash = ""; string strSalt = ""; byte[] hash = null; byte[] salt = null; ResponseModel response = new ResponseModel(); // See if this is a temporary password if (IsTemporaryPassword(changePasswordModel) == true) { // Dont check for a valid login } else if (IsValidLogin(changePasswordModel.LoginId, changePasswordModel.OldPassword) == false) { response.Code = "error"; response.Message = "Invalid Login or Password"; return(Ok(content: response)); } SH.GetHashAndSaltString(changePasswordModel.NewPassword, out strHash, out strSalt); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); hash = encoding.GetBytes(strHash); salt = encoding.GetBytes(strSalt); SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spChangePassword"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Login_Id"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Direction = ParameterDirection.Input; parameter.Size = 50; parameter.Value = changePasswordModel.LoginId; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Hash"; parameter.SqlDbType = SqlDbType.VarBinary; parameter.Direction = ParameterDirection.Input; parameter.Size = 250; parameter.Value = hash; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Salt"; parameter.SqlDbType = SqlDbType.VarBinary; parameter.Direction = ParameterDirection.Input; parameter.Size = 250; parameter.Value = salt; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Results"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 50; parameter.Direction = ParameterDirection.Output; sqlCmd.Parameters.Add(parameter); myConnection.Open(); sqlCmd.ExecuteNonQuery(); if (parameter.Value.ToString().Equals("0")) { response.Code = "success"; response.Message = "Your Password Has Been Changed Successfully"; } else { response.Code = "error"; response.Message = "Invalid Login or Password"; } myConnection.Close(); return(Ok(content: response)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
public static bool ChangePassword(ChangePasswordModel model) { return(true); }
public Task ChangePassword(ChangePasswordModel model) { throw new System.NotImplementedException(); }
public async Task <IdentityResult> ChangePassword(ChangePasswordModel model) { var result = await _userManager.ChangePasswordAsync(model.UserID, model.CurrentPassword, model.NewPassword); return(result); }
public async Task <IActionResult> Post([FromBody] ChangePasswordModel model) { _logger.Information("START PasswordController.Post: "); // Validate the request if (model == null) { _logger.Warning("Null model"); return(BadRequest(ApiResult.InvalidRequest())); } if (model.NewPassword != model.NewPasswordVerify) { _logger.Warning("Invalid model, passwords don't match"); return(BadRequest(ApiResult.InvalidRequest())); } // Validate the model if (ModelState.IsValid == false) { _logger.Warning("Invalid model, validation failed"); return(BadRequest(ApiResult.FromModelStateErrors(ModelState))); } //BAONX // // Validate the Captcha // try // { // if (await ValidateRecaptcha(model.ReCaptcha).ConfigureAwait(false) == false) // throw new InvalidOperationException("Invalid ReCaptcha response"); // } //#pragma warning disable CA1031 // Do not catch general exception types // catch (Exception ex) //#pragma warning restore CA1031 // Do not catch general exception types // { // _logger.Warning(ex, "Invalid ReCaptcha"); // return BadRequest(ApiResult.InvalidCaptcha()); // } var result = new ApiResult(); try { //BAONX //if (_options.MinimumDistance > 0 && // _passwordChangeProvider.MeasureNewPasswordDistance(model.CurrentPassword, model.NewPassword) < _options.MinimumDistance) //{ // result.Errors.Add(new ApiErrorItem(ApiErrorCode.MinimumDistance)); // return BadRequest(result); //} //if (_options.MinimumScore > 0 && Zxcvbn.Core.EvaluatePassword(model.NewPassword).Score < _options.MinimumScore) //{ // result.Errors.Add(new ApiErrorItem(ApiErrorCode.MinimumScore)); // return BadRequest(result); //} var resultPasswordChange = _passwordChangeProvider.PerformPasswordChange( model.Username, model.CurrentPassword, model.NewPassword); if (resultPasswordChange == null) { return(Json(result)); } result.Errors.Add(resultPasswordChange); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { _logger.Error(ex, "Failed to update password"); result.Errors.Add(new ApiErrorItem(ApiErrorCode.Generic, ex.Message)); } _logger.Warning(Json(result).ToString()); return(BadRequest(result)); }
/// <summary> /// Prepare the change password model /// </summary> /// <returns>Change password model</returns> public virtual ChangePasswordModel PrepareChangePasswordModel() { var model = new ChangePasswordModel(); return(model); }
public ActionResult ChangePassword(string option, string username) { var model = new ChangePasswordModel(option, username); return(View(model)); }
public async Task <IHttpActionResult> ChangePassword(ChangePasswordModel model) { var result = await userManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); return(Ok(result)); }
public Task <bool> ChangePassword(int userId, ChangePasswordModel model) { throw new NotImplementedException(); }
public async Task <IdentityResult> ChangePassword(ChangePasswordModel model) { var user = await db.Users.FindUser(model.UserName); return(await db.Users.ChangePassword(user.Id, model.OldPassword, model.NewPassword)); }
public async Task <ChangePasswordModel> ChangePasswordAsync(ChangePasswordModel model) { return(await _apiHelper.PostAsync(model, "api/Account/Manage/ChangePassword")); }
public ResponseModel ChangePassword(ChangePasswordModel usermodel) { #region validation if (usermodel == null || string.IsNullOrEmpty(usermodel.NewPassword) || string.IsNullOrEmpty(usermodel.UserId)) { return(new ResponseModel { Success = false, Messages = new List <string> { "Data not mapped" }, Data = usermodel }); } if (usermodel.NewPassword != usermodel.ConfirmNewPassword) { return(new ResponseModel { Success = false, Messages = new List <string> { "Password does not match" }, Data = usermodel }); } #endregion ApplicationUser user = UserManager.FindById(usermodel.UserId); if (user == null) { return(new ResponseModel { Success = false, Messages = new List <string> { "User not found" }, Data = usermodel }); } user.PasswordHash = UserManager.PasswordHasher.HashPassword(usermodel.NewPassword); var result = UserManager.Update(user); if (!result.Succeeded) { return(new ResponseModel { Success = false, Messages = new List <string> { "Failed to update password" }, Data = usermodel }); } return(new ResponseModel { Success = true, Messages = new List <string> { "Password updated" }, Data = usermodel }); }
public async Task <IActionResult> Post([FromBody] ChangePasswordModel model) { // Validate the request if (model == null) { _logger.LogWarning("Null model"); return(BadRequest(ApiResult.InvalidRequest())); } if (model.NewPassword != model.NewPasswordVerify) { _logger.LogWarning("Invalid model, passwords don't match"); return(BadRequest(ApiResult.InvalidRequest())); } // Validate the model if (ModelState.IsValid == false) { _logger.LogWarning("Invalid model, validation failed"); return(BadRequest(ApiResult.FromModelStateErrors(ModelState))); } // Validate the Captcha try { if (await ValidateRecaptcha(model.Recaptcha).ConfigureAwait(false) == false) { throw new InvalidOperationException("Invalid Recaptcha response"); } } catch (Exception ex) { _logger.LogWarning(ex, "Invalid Recaptcha"); return(BadRequest(ApiResult.InvalidCaptcha())); } var result = new ApiResult(); try { if (_options.MinimumDistance > 0 && _passwordChangeProvider.MeasureNewPasswordDistance(model.CurrentPassword, model.NewPassword) < _options.MinimumDistance) { result.Errors.Add(new ApiErrorItem(ApiErrorCode.MinimumDistance)); return(BadRequest(result)); } if (_options.MinimumScore > 0 && Core.EvaluatePassword(model.NewPassword).Score < _options.MinimumScore) { result.Errors.Add(new ApiErrorItem(ApiErrorCode.MinimumScore)); return(BadRequest(result)); } var resultPasswordChange = _passwordChangeProvider.PerformPasswordChange( model.Username, model.CurrentPassword, model.NewPassword); if (resultPasswordChange == null) { return(Json(result)); } result.Errors.Add(resultPasswordChange); } catch (Exception ex) { _logger.LogError(ex, "Failed to update password"); result.Errors.Add(new ApiErrorItem(ApiErrorCode.Generic, ex.Message)); } return(BadRequest(result)); }