public async Task <IActionResult> ChangePassword([Required, FromBody] PasswordUpdate passwords) { var email = GetCurrentUserEmailAddress(); await _userOperations.UpdateUserPassword(email, passwords); return(NoContent()); }
public async Task <IActionResult> UpdatePasword([FromBody] PasswordUpdate password) { if (password == null) { return(BadRequest()); } // getting the user id var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (currentUserId != password.UserId) { return(Unauthorized()); } var newPass = _mapper.Map <Password>(password); newPass.Updated = DateTime.Now; var ok = await _repo.UpdatePassword(newPass); if (!ok) { return(BadRequest("Password cannot be updated")); } if (await _repo.SaveAll()) { return(StatusCode(204)); } return(BadRequest("Server error")); }
public IHttpActionResult UpdateUserPassword(PasswordUpdate pwd) { var userName = User.Identity.Name; repo_.UpdatePassword(userName, pwd.Password); return Ok(); } // UserDetails
public async Task <IdentityResult> ChangePassword(PasswordUpdate update) { if (update == null) { _logger.LogWarning("AccountUpdate is null"); throw new ArgumentNullException(nameof(update)); } var pw1 = update.CurrentPassword; var pw2 = update.NewPassword; if (update == null || string.IsNullOrEmpty(pw1) || string.IsNullOrEmpty(pw2)) { _logger.LogWarning("One or more passwords missing"); throw new MissingInformationException("Missing password update"); } _logger.LogInformation("Attempting to load user"); var user = await _userManager.FindByIdAsync(update.UserId); if (user == null) { _logger.LogWarning("Unable to locate user: {Id}", update.UserId); throw new UserNotFoundException($"Unable to locate user: {update.UserId}"); } _logger.LogInformation("Changing password"); var(oldPassword, newPassword) = update; return(await _userManager.ChangePasswordAsync(user, oldPassword, newPassword)); }
public async Task UpdatePassword(PasswordUpdate passwordUpdate) { var daoUser = await GetUser(passwordUpdate.Email); var emailToken = daoUser.EmailTokens .FirstOrDefault(x => x.Token == passwordUpdate.Token && x.TokenType == DaoEmailToken.Type.Password); if (emailToken == null || emailToken.ExpirationDate < TimeService.UtcNow) { throw new ResourceGoneException("token_invalid_or_expired"); } using (var transaction = Context.Database.BeginTransaction()) { try { var previousPassword = daoUser.Password; daoUser.Password = Hasher.GetHash(passwordUpdate.Password); if (previousPassword != daoUser.Password && await Context.SaveChangesAsync() != 1) { throw new DatabaseException("password_not_saved"); } Context.EmailTokens.Remove(emailToken); if (await Context.SaveChangesAsync() != 1) { throw new DatabaseException("token_deletion_failed"); } var model = new InformationViewModel() { Title = Localizer.GetString(daoUser.Lang, LocalizationResource.EMAIL_PASSWORDCHANGED_SUBJECT), PreHeader = Localizer.GetString(daoUser.Lang, LocalizationResource.EMAIL_PASSWORDCHANGED_PREHEADER), Hero = Localizer.GetString(daoUser.Lang, LocalizationResource.EMAIL_PASSWORDCHANGED_HERO), Greeting = Localizer.GetString(daoUser.Lang, LocalizationResource.EMAIL_CASUAL_BODY_GREETING, daoUser.DisplayName), Intro = Localizer.GetString(daoUser.Lang, LocalizationResource.EMAIL_PASSWORDCHANGED_BODY_INTRO), EmailDisclaimer = Localizer.GetString(daoUser.Lang, LocalizationResource.EMAIL_PASSWORDCHANGED_BODY_DISCLAIMER), Cheers = Localizer.GetString(daoUser.Lang, LocalizationResource.EMAIL_CASUAL_BODY_CHEERS), MShareTeam = Localizer.GetString(daoUser.Lang, LocalizationResource.MSHARE_TEAM), SiteBaseUrl = $"{UriConf.URIForEndUsers}" }; var htmlBody = await Renderer.RenderViewToStringAsync($"/Views/Emails/Confirmation/InformationHtml.cshtml", model); await EmailService.SendMailAsync(MimeKit.Text.TextFormat.Html, daoUser.DisplayName, daoUser.Email, Localizer.GetString(daoUser.Lang, LocalizationResource.EMAIL_PASSWORDCHANGED_SUBJECT), htmlBody); transaction.Commit(); } catch { transaction.Rollback(); throw; } } }
public IActionResult PasswordUpdate(PasswordUpdate passwordUpdate) { var result = _authService.PasswordUpdate(passwordUpdate); if (result.Success) { return(Ok(result)); } return(BadRequest(result.Message)); }
public async Task <ActionResult <PasswordUpdate> > UpdatePassword([FromBody] PasswordUpdate passwordUpdateModel, [FromHeader] string authorization) { try { passwordUpdateModel = await _authenticationService.UpdatePassword(UserUtilities.UserIdFromAuth(authorization), passwordUpdateModel.OldPassword, passwordUpdateModel.NewPassword); } catch (Exception e) { return(BadRequest(e.Message)); } return(Ok(passwordUpdateModel)); }
public async Task UpdatePassword(PasswordUpdate passwordUpdate) { var user = await _context.Users .Include(x => x.EmailTokens) .FirstOrDefaultAsync(x => x.Email == passwordUpdate.Email); if (user == null) { throw new Exceptions.ResourceNotFoundException("user"); } var emailToken = user.EmailTokens.FirstOrDefault(y => y.Token == passwordUpdate.Token && y.TokenType == DaoEmailToken.Type.Password); if (emailToken == null) { throw new Exceptions.ResourceGoneException("token"); } if (emailToken.ExpirationDate < _timeService.UtcNow) { throw new Exceptions.BusinessException("token_expired"); } using (var transaction = _context.Database.BeginTransaction()){ try{ var previousPassword = user.Password; user.Password = Hasher.GetHash(passwordUpdate.Password); if (previousPassword != user.Password && await _context.SaveChangesAsync() != 1) { throw new Exceptions.DatabaseException("password_not_saved"); } _context.EmailTokens.Remove(emailToken); if (await _context.SaveChangesAsync() != 1) { throw new Exceptions.DatabaseException("token_deletion_failed"); } await _emailService.SendMailAsync(MimeKit.Text.TextFormat.Text, user.DisplayName, user.Email, "Jelszó változtatás", $"A mai napon jelszava megváltoztatásra került!"); transaction.Commit(); } catch { transaction.Rollback(); throw; } } }
public async Task ChangePassword_ChangeSuccessful_Returns204() { // Arrange var update = new PasswordUpdate ("UserIdBob", "TotallyHashedPassword123!", "SuperCoolNewPassword123!").ToJson(); // Act var response = await _client.PatchAsync("api/users/change-password", update); // Assert response.StatusCode.Should().Be(HttpStatusCode.NoContent); }
public IHttpActionResult UpdateOrganisationStaffMember(Guid id, Guid staffId, PasswordUpdate update) { if (!ModelState.IsValid) return badModelState(); if (staffId != update.Id) return BadRequest("Bad Staff Member Id"); try { repo_.UpdatePassword(update.LoginId, update.Password); return Ok(); } catch (Exception e) { return BadRequest(e.Message); } } // UpdateOrganisationStaffMember
public IActionResult ForgotPassword(PasswordUpdate pw) { var email = pw.Email; var npw_bytes = System.Text.Encoding.ASCII.GetBytes(pw.ForgotPassword); if (_dbContext.Database.ExecuteSqlInterpolated($"UPDATE MesahUser SET UserPw = HASHBYTES('SHA1', {npw_bytes}) WHERE Email ={email}") == 1) { ViewData["Msg"] = "Password Successfully Updated!"; } else { ViewData["Msg"] = "Failed to update password!"; } return(View()); }
public async Task <IActionResult> ChangePassword(PasswordUpdate update) { try { await _userService.ChangePassword(update); } catch (UserNotFoundException ex) { return(NotFound(ex.Message)); } catch (Exception ex) { return(BadRequest(ex.Message)); } return(NoContent()); }
public ActionResult PasswordRecovery(PasswordUpdate model) { if (String.IsNullOrEmpty(model.login)) { ErrorMessage("Вы не указали eMail"); return(View(model)); } var user = DB.Account.FirstOrDefault(x => x.Login == model.login && x.TypeUser == (SByte)TypeUsers.ProducerUser); // пользователь не найден, отсылаем на домашнюю с ошибкой if (user == null) { ErrorMessage($"Пользователь с email {model.login} не найден, обращайтесь на {ConfigurationManager.AppSettings["MailFrom"]}"); return(View(model)); } // если новый или активный: отсылаем новый пароль на почту if (user.EnabledEnum == UserStatus.New || user.EnabledEnum == UserStatus.Active) { var password = GetRandomPassword(); user.Password = Md5HashHelper.GetHash(password); user.PasswordUpdated = DateTime.Now; DB.Entry(user).State = EntityState.Modified; DB.SaveChanges(); Mails.SendPasswordRecoveryMessage(user, password); SuccessMessage($"Новый пароль отправлен на ваш email {model.login}"); } // если заблокирован else if (user.EnabledEnum == UserStatus.Blocked) { ErrorMessage($"Ваша учетная запись заблокирована, обращайтесь на {ConfigurationManager.AppSettings["MailFrom"]}"); } // если запросивший регистрацию else if (user.EnabledEnum == UserStatus.Request) { SuccessMessage($"Ваша заявка на регистрацию еще не рассмотрена, обращайтесь на {ConfigurationManager.AppSettings["MailFrom"]}"); } return(Redirect("~")); }
public async Task UpdateUserPassword(string email, PasswordUpdate passwordUpdate) { _userValidator.ValidatePassword(passwordUpdate.OldPassword); _userValidator.ValidatePassword(passwordUpdate.NewPassword); var user = await _userRepository.SelectByKey(email); if (!_passwordGuard.IsUserPasswordValid(user.HashedPassword, passwordUpdate.OldPassword)) { throw new UnauthorizedAccessException("The current password was incorrect"); } var newPasswordHash = _passwordGuard.GeneratePasswordHash(passwordUpdate.NewPassword); var userWithUpdatedPassword = user.UpdatePasswordHash(newPasswordHash); _userValidator.Validate(userWithUpdatedPassword); await _userRepository.Update(userWithUpdatedPassword); }
public IActionResult ChangePassword(PasswordUpdate pw) { var userid = User.FindFirst(ClaimTypes.NameIdentifier).Value; //var npw_bytes = System.Text.Encoding.ASCII.GetBytes(pw.NewPassword); //var cpw_bytes = System.Text.Encoding.ASCII.GetBytes(pw.CurrentPassword); //if (_dbContext.Database.ExecuteSqlInterpolated($"UPDATE MesahUser SET UserPw = HASHBYTES('SHA1', {npw_bytes}) WHERE UserId={userid} AND UserPw = HASHBYTES('SHA1', {cpw_bytes})") == 1) string sql = @"UPDATE MesahUser SET UserPw = HASHBYTES('SHA1', '{1}') WHERE UserId= '{0}' AND UserPw = HASHBYTES('SHA1', '{2}')"; if (DBUtl.ExecSQL(sql, userid, pw.NewPassword, pw.CurrentPassword) == 1) { ViewData["Msg"] = "Password Successfully Updated!"; } else { ViewData["Msg"] = "Failed to update password!"; } return(View()); }
public AuthenticationControllerShould() { _mockConfig = new Mock <IConfiguration>(); _repository = new Mock <IUserRepository>(); _tokenManager = new Mock <ITokenManager>(); _logger = new Mock <ILogger <AuthenticationController> >(); _userMapping = new Mock <IUserMappings>(); _updatedPassword = new PasswordUpdate() { OldPassword = "******", NewPassword = "******" }; _user = new User() { FullName = "User 1", EmailAddress = "*****@*****.**", Password = "******" }; _userCreds = new UserCredentials() { EmailAddress = "*****@*****.**", Password = "******" }; _userWithoutSensitiveData = new UserWithoutSensitiveDataDto() { Id = 1, FullName = "User 1", EmailAddress = "*****@*****.**", ActiveTenantIds = { 1 }, AdminForTenants = { 1 } }; _authController = new AuthenticationController(_logger.Object, _repository.Object, _userMapping.Object, _mockConfig.Object, _tokenManager.Object); }
public IResult PasswordUpdate(PasswordUpdate passwordUpdate) { var u = _userService.GetById(passwordUpdate.UserId); if (u == null) { return(new ErrorResult(Messages.UserNotFound)); } if (!HashingHelper.VerifyPasswordHash(passwordUpdate.OldPassword, u.PasswordHash, u.PasswordSalt)) { return(new ErrorResult(Messages.ErrorPassword)); } byte[] passwordHash, passwordSalt; HashingHelper.CreatePasswordHash(passwordUpdate.NewPassword, out passwordHash, out passwordSalt); u.PasswordHash = passwordHash; u.PasswordSalt = passwordSalt; _userService.Update(u); return(new SuccessResult(Messages.PasswordUpdate)); }
public IActionResult UpdatePassword([FromBody] PasswordUpdate updatedPassword) { PasswordUpdateValidator validator = new PasswordUpdateValidator(); var results = validator.Validate(updatedPassword); var errors = results.ToString("\n"); if (errors != string.Empty) { var errorList = ErrorFormatter.FormatValidationErrors(errors); return(BadRequest(new { Errors = errorList })); } User currentUser = _repository.GetUser(User.Claims); if (currentUser == null) { return(NotFound("User could not be validated or not found for this operation")); } bool isOldPasswordMatching = _repository.ValidatePassword(updatedPassword.OldPassword, currentUser); if (!isOldPasswordMatching) { return(BadRequest("The Old password enetered does not match with the user's exisisting password.")); } try { _repository.UpdatePassword(updatedPassword.NewPassword, currentUser); return(Ok("Password updated")); } catch (Exception e) { _logger.LogError($"Something went wrong while trying to update password. Password not updated. ${e}"); } return(StatusCode(500, "Unable to update Password. Try again later")); }
public void MergeFrom(SecurityLogin other) { if (other == null) { return; } if (other.Id.Length != 0) { Id = other.Id; } if (other.Login.Length != 0) { Login = other.Login; } if (other.Password.Length != 0) { Password = other.Password; } if (other.created_ != null) { if (created_ == null) { Created = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } Created.MergeFrom(other.Created); } if (other.passwordUpdate_ != null) { if (passwordUpdate_ == null) { PasswordUpdate = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } PasswordUpdate.MergeFrom(other.PasswordUpdate); } if (other.agreementAccepted_ != null) { if (agreementAccepted_ == null) { AgreementAccepted = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } AgreementAccepted.MergeFrom(other.AgreementAccepted); } if (other.IsLocked != false) { IsLocked = other.IsLocked; } if (other.IsInactive != false) { IsInactive = other.IsInactive; } if (other.EmailAddress.Length != 0) { EmailAddress = other.EmailAddress; } if (other.PhoneNumber.Length != 0) { PhoneNumber = other.PhoneNumber; } if (other.FullName.Length != 0) { FullName = other.FullName; } if (other.PrefferredLanguage.Length != 0) { PrefferredLanguage = other.PrefferredLanguage; } if (other.ForceChangePassword != false) { ForceChangePassword = other.ForceChangePassword; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); }
public override int GetHashCode() { int hash = 1; if (Id.Length != 0) { hash ^= Id.GetHashCode(); } if (Login.Length != 0) { hash ^= Login.GetHashCode(); } if (Password.Length != 0) { hash ^= Password.GetHashCode(); } if (created_ != null) { hash ^= Created.GetHashCode(); } if (passwordUpdate_ != null) { hash ^= PasswordUpdate.GetHashCode(); } if (agreementAccepted_ != null) { hash ^= AgreementAccepted.GetHashCode(); } if (IsLocked != false) { hash ^= IsLocked.GetHashCode(); } if (IsInactive != false) { hash ^= IsInactive.GetHashCode(); } if (EmailAddress.Length != 0) { hash ^= EmailAddress.GetHashCode(); } if (PhoneNumber.Length != 0) { hash ^= PhoneNumber.GetHashCode(); } if (FullName.Length != 0) { hash ^= FullName.GetHashCode(); } if (PrefferredLanguage.Length != 0) { hash ^= PrefferredLanguage.GetHashCode(); } if (ForceChangePassword != false) { hash ^= ForceChangePassword.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public ActionResult PasswordRecovery() { var model = new PasswordUpdate(); return(View(model)); }
//密码修改 private void mniPasswordChange_Click(object sender, EventArgs e) { var pu = new PasswordUpdate(); pu.Show(); }
public bool UpdatePassword(PasswordUpdate passwordUpdate) { return(_repo.UpdatePassword(passwordUpdate)); }