private NewPassword HashPassword(NewPassword np) { HashAlgorithm hashAlg = null; try { hashAlg = new SHA256CryptoServiceProvider(); byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(np.GetSaltPassword()); byte[] bytHash = hashAlg.ComputeHash(bytValue); np.SaltedHashedPassword = Convert.ToBase64String(bytHash); } catch (Exception e) { throw e; } finally { if (hashAlg != null) { hashAlg.Clear(); hashAlg.Dispose(); hashAlg = null; } } return(np); }
private async Task SavePassword() { //Check if any field is empty if (string.IsNullOrWhiteSpace(OldPassword) || string.IsNullOrWhiteSpace(NewPassword) || string.IsNullOrWhiteSpace(ConfirmedPassword)) { ErrorField = "One or more fields are empty"; } //Check if OldPassword is equals to UserPassword else if (!OldPassword.Equals(Application.Current.Properties["Password"])) { ErrorField = "Old password is not correct"; } //Check if NewPassword and ConfirmedPassword are equals else if (!NewPassword.Equals(ConfirmedPassword)) { ErrorField = "Old and new password do not match"; } //If everything is correct else if (NewPassword.Equals(ConfirmedPassword)) { //Try to save if (await App.loginService.ChangePassword(OldPassword, NewPassword)) { ErrorField = "Password successfully changed"; } else { ErrorField = "An error has occured, please try again"; } } }
/// <summary> /// Returns true if UserPasswordChangeSubmit instances are equal /// </summary> /// <param name="other">Instance of UserPasswordChangeSubmit to be compared</param> /// <returns>Boolean</returns> public bool Equals(UserPasswordChangeSubmit other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( Uuid == other.Uuid || Uuid != null && Uuid.Equals(other.Uuid) ) && ( NewPassword == other.NewPassword || NewPassword != null && NewPassword.Equals(other.NewPassword) ) && ( NewPasswordConfirmed == other.NewPasswordConfirmed || NewPasswordConfirmed != null && NewPasswordConfirmed.Equals(other.NewPasswordConfirmed) ) && ( OldPassword == other.OldPassword || OldPassword != null && OldPassword.Equals(other.OldPassword) )); }
private void EditAccountOk() { try { if (CheckFields()) { if (accountService.SetChangesAsync(new AccountServiceReference.Person { Email = Email, Phone = Phone, UserName = UserName }, Account.GetInstace().Session).Result) { Account.GetInstace().Email = Email; Account.GetInstace().Phone = Phone; Account.GetInstace().UserName = UserName; } if (!OldPassword.Equals(string.Empty) && !NewPassword.Equals(string.Empty)) { accountService.ChangePasswordAsync(Convert.ToBase64String(Hash.GenerateHash(Encoding.UTF8.GetBytes(OldPassword))), Convert.ToBase64String(Hash.GenerateHash(Encoding.UTF8.GetBytes(NewPassword))), Account.GetInstace().Session); } } } catch (Exception e) { ErrorMessage = e.Message; } }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { var results = new List <ValidationResult>(); if (NewPassword.Any(char.IsUpper) == false) { results.Add(new ValidationResult("Password must contain at least one upper-case letter", new List <string> { "NewPassword" })); } if (NewPassword.Any(char.IsLower) == false) { results.Add(new ValidationResult("Password must contain at least one lower-case letter", new List <string> { "NewPassword" })); } if (NewPassword.Any(char.IsDigit) == false) { results.Add(new ValidationResult("Password must contain at least one digit", new List <string> { "NewPassword" })); } return(results); }
private bool IsStrongPassword() { if (!NewPassword.Any(char.IsUpper)) return false; if (!NewPassword.Any(char.IsNumber)) return false; if (NewPassword.Length < 8) return false; return true; }
public bool ProcessUserRegistration(string encodedUser, string encodedEmail, string encodedPass) { IMemberShipData msd = null; bool userAdded = false; try { msd = new Data(Utilities.GetDbSetting()); string decodedUser = Utilities.DecodeClientBase64String(encodedUser); string decodedEmail = Utilities.DecodeClientBase64String(encodedEmail); string decodedPass = Utilities.DecodeClientBase64String(encodedPass); //LogParameters(); if (Utilities.ValidUserToRegistration(decodedUser, decodedEmail, decodedPass)) { Password p = new Password(); NewPassword np = p.GetPassword(decodedPass); userAdded = msd.AddUser(decodedUser, decodedEmail, np.SaltedHashedPassword, np.Salt); } } catch (Exception e) { msd.LogMsg("Error: " + e.Message + ", trace: " + e.StackTrace.ToString()); } return(userAdded); }
public bool ProcessUserRegistration(string encodedUser, string encodedEmail, string encodedPass) { IMemberShipData msd = new Data(Utility.GetAppSetting(BucketListConstants.DB_CONN)); bool userAdded = false; try { string decodedUser = Utility.DecodeClientBase64String(encodedUser); string decodedEmail = Utility.DecodeClientBase64String(encodedEmail); string decodedPass = Utility.DecodeClientBase64String(encodedPass); IList <string> parameters = new List <string>(); parameters.Add(decodedUser); parameters.Add(decodedEmail); CommonCode.Log(msd, null, "ProcessUserRegistration", parameters); Password p = new Password(); NewPassword np = p.GetPassword(decodedPass); userAdded = msd.AddUser(decodedUser, decodedEmail, np.SaltedHashedPassword, np.Salt); } catch (Exception e) { msd.LogMsg("Error: " + e.Message + ", trace: " + e.StackTrace.ToString()); } return(userAdded); }
private string ValidatePassword(string NewPassword) { Random rand = new Random(); List <int> nonSelectedIndexes = new List <int>(Enumerable.Range(0, NewPassword.Length)); if (!NewPassword.Any(x => char.IsDigit(x))) { //does not contain digit char[] pass = NewPassword.ToCharArray(); int pos = nonSelectedIndexes[rand.Next(nonSelectedIndexes.Count)]; nonSelectedIndexes.Remove(pos); pass[pos] = Convert.ToChar(rand.Next(10) + '0'); NewPassword = new string(pass); } if (!NewPassword.Any(x => char.IsLower(x))) { //does not contain lower char[] pass = NewPassword.ToCharArray(); int pos = nonSelectedIndexes[rand.Next(nonSelectedIndexes.Count)]; nonSelectedIndexes.Remove(pos); pass[pos] = Convert.ToChar(rand.Next(26) + 'a'); NewPassword = new string(pass); } if (!NewPassword.Any(x => char.IsUpper(x))) { //does not contain upper char[] pass = NewPassword.ToCharArray(); int pos = nonSelectedIndexes[rand.Next(nonSelectedIndexes.Count)]; nonSelectedIndexes.Remove(pos); pass[pos] = Convert.ToChar(rand.Next(26) + 'A'); NewPassword = new string(pass); } return(NewPassword); }
public override string Validate(string propertyName) { if (!DoValidation) { return(null); } switch (propertyName) { case nameof(NewPassword): if (NewPassword.IsNullOrWhiteSpace()) { return(string.Format(Constants.FieldMustBeFilledMessageFormat, nameof(NewPassword))); } else if (!NewPassword.IsLengthBetween(5, 32)) { return(string.Format(Constants.LengthErrorMessageFormat, nameof(NewPassword), 5, 32)); } break; case nameof(ConfirmNewPassword): if (ConfirmNewPassword.IsNullOrWhiteSpace()) { return(string.Format(Constants.FieldMustBeFilledMessageFormat, nameof(ConfirmNewPassword))); } else if (!ConfirmNewPassword.IsLengthBetween(5, 32)) { return(string.Format(Constants.LengthErrorMessageFormat, nameof(ConfirmNewPassword), 5, 32)); } break; } return(null); }
private void CreateUserButton_Click(object sender, EventArgs e) { string digsign = Guid.NewGuid().ToString(); if (!NewName.Text.Trim().Equals("") && !NewPassword.Equals("") && !NewUsername.Text.Trim().Equals("")) { SqlConnection sqlConnection1 = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; //cmd.CommandText = "delete from dbo.BranchSubject where Branch=\'" + BranchModify.Text.Trim() + "\' and Code=\'" + SubjectModify.SelectedItem.ToString() + "\';"; cmd.CommandText = "insert dbo.Users (Name, UserName, Password, DigitalSignature) values (\'" + NewName.Text.Trim() + "\', \'" + NewUsername.Text.Trim() + "\', \'" + NewPassword.Text + "\', \'" + digsign + "\');"; cmd.Connection = sqlConnection1; sqlConnection1.Open(); try { cmd.ExecuteNonQuery(); MessageBox.Show("User Successfully Created."); NewName.Text = ""; NewPassword.Text = ""; NewUsername.Text = ""; } catch (Exception ex) { MessageBox.Show("Unable to create user."); } sqlConnection1.Close(); } else { MessageBox.Show("Please fill in all the fields."); } }
private bool CheckInputData() { bool result = true; ClearError(); if (Password.Trim() == string.Empty) { VisibleErrPassword = true; StringErrPassword = "******"; result = false; } if (NewPassword.Trim() == string.Empty) { VisibleErrNewPassword = true; StringErrNewPassword = "******"; result = false; } if (ReNewPassword.Trim() == string.Empty) { VisibleErrReNewPassword = true; StringErrReNewPassword = "******"; result = false; } if (NewPassword.Trim() != string.Empty && ReNewPassword.Trim() != string.Empty && NewPassword != ReNewPassword) { VisibleErrReNewPassword = true; StringErrReNewPassword = "******"; result = false; } return(result); }
public Task <bool> ChangePasswordAsync(NewPassword password, SearchUserResult account) { password.UserId = null; var url = string.Format(Endpoints.ChangePasswordEndpoint, account.Id); return(RequestWrapper.PostAsyncWrapper(password, url)); }
public List <int> VerifyPassword(string password = null) { if (string.IsNullOrEmpty(NewPassword) || string.IsNullOrWhiteSpace(NewPassword) || string.IsNullOrEmpty(PasswordConfirm) || string.IsNullOrWhiteSpace(PasswordConfirm)) { return new List <int> { 0 } } ; var errors = new List <int>(); if (NewPassword != PasswordConfirm) { errors.Add(1); } var lenTest = new Regex(@".{6,20}"); if (!lenTest.IsMatch(NewPassword)) { errors.Add(2); } var lowTest = new Regex(@"[a-z]+"); if (!lowTest.IsMatch(NewPassword)) { errors.Add(3); } var capTest = new Regex(@"[A-Z]+"); if (!capTest.IsMatch(NewPassword)) { errors.Add(4); } var digitTest = new Regex(@"[\d]+"); if (!digitTest.IsMatch(NewPassword)) { errors.Add(5); } if (!errors.Contains(10) && NewPassword.Contains(" ")) { errors.Add(6); } var spTest = new Regex(@"[!@#$%^&*_+\.]+"); if (!spTest.IsMatch(NewPassword)) { errors.Add(7); } return(errors); }
public ActionResult ChangePassword(NewPassword updpass) { if (ModelState.IsValid) { Person person = db.People.Find(User.Identity.Name); if (Helper.EncodePasswordMd5(updpass.oldpassWord) == person.password) { if (Helper.EncodePasswordMd5(updpass.NewpassWord) == Helper.EncodePasswordMd5(updpass.ConfirmpassWord)) { person.password = Helper.EncodePasswordMd5(updpass.ConfirmpassWord); db.Entry(person).State = EntityState.Modified; db.SaveChanges(); ViewBag.PasswordUpdateSuccess = true; } else { ModelState.AddModelError(string.Empty, "New password not matching with confirm password..!"); return(View()); } } else { ModelState.AddModelError(string.Empty, "Invalid old password..!"); return(View()); } } return(View()); }
internal void ChangePassword() { //Populate the Excel sheet GlobalDefinitions.ExcelLib.PopulateInCollections(Global.Base.ExcelPath, "SignIn"); GlobalDefinitions.wait(60); Actions builder = new Actions(Global.GlobalDefinitions.driver); builder.MoveToElement(UsernameNavigation).Build().Perform(); UsernameNavigation.Click(); GlobalDefinitions.wait(60); ChangePasswordMenu.Click(); CurrentPassword.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "CurrentPassword")); NewPassword.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "NewPassword")); ConfirmPassword.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "ConfirmPassword")); GlobalDefinitions.wait(60); Savebutton.Click(); }
private void btnUpdate_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(UserName)) { MessageBox.Show("Enter user name"); return; } if (!string.IsNullOrEmpty(OldPassword) && !string.IsNullOrEmpty(NewPassword)) { if (!NewPassword.Equals(ConfirmPassword)) { MessageBox.Show("Password not match"); return; } UsersRepository _userRepo = new UsersRepository(); Users _user = _userRepo.FindByQuery(" username = '******' AND Password = '******'").FirstOrDefault(); if (_user != null) { _user.Password = NewPassword; _userRepo.Update(_user); } else { MessageBox.Show("User Not Found"); } } else { MessageBox.Show("Enter Valid Passwords"); return; } }
public int ChangePassword(NewPassword np) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand("usp_changePassword"); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("@UserID", np.UserID)); command.Parameters.Add(new SqlParameter("@NewPassword", np.NewPasswordString)); command.Connection = connection; connection.Open(); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable table = new DataTable(); adapter.Fill(table); connection.Close(); if (table.Rows[0][0].ToString() == np.NewPasswordString) { return(1); } else { return(0); } }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } if (!NewPassword.Equals(ConfirmPassword)) { ModelState.AddModelError(string.Empty, "Confirm Password doesn't match Password."); return(Page()); } var user = await UserManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{UserManager.GetUserId(User)}'.")); } var changePasswordResult = await UserManager.ChangePasswordAsync(user, OldPassword, NewPassword); if (!changePasswordResult.Succeeded) { foreach (var error in changePasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(Page()); } await SignInManager.RefreshSignInAsync(user); return(RedirectToPage("/Account/Profile")); }
public IActionResult ResetPassword([FromBody] NewPassword newPassword) { if (!ModelState.IsValid) { return(BadRequest()); } var user = _context.userDBModels.FirstOrDefault(s => s.Email == newPassword.Email); if (user == null) { return(BadRequest(new { message = "Nie istnieje użytkownik o takim emailu" })); } user.ResetPasswordToken = TokenManager.RandomTokenString(); string resetPasswordtoken = TokenManager.GenerateResetPassToken(user.ResetPasswordToken, user.Email); _context.userDBModels.Update(user); _context.SaveChanges(); string message = $@"<p>Wysłano powiadomienie o zresetowaniu hasła</p> <p>Kliknij link aby dokończyć resetowanie</p> <p> <a href=""{ClientBaseUrl}new-password?token={resetPasswordtoken}""> link <a/> </p>"; _mailService.SendMail(newPassword.Email, "Resetowanie Hasła", message); return(Ok(new { message = "Link do zresetowania hasło został wysłany na twój e-mail" })); }
private void UpdateNewPasswordAwareTextBlock() { NewPasswordAwareMessage mes = NewPasswordAwareMessage.WhiteSpaceAware; if (NewPassword.Contains(" ")) { NewPasswordAwareTextBlockVisibility = Visibility.Visible; mes = NewPasswordAwareMessage.WhiteSpaceAware; } else if (NewPassword.Equals(CurrentUser.Password)) { NewPasswordAwareTextBlockVisibility = Visibility.Visible; mes = NewPasswordAwareMessage.SameBefore; } else if (NewPassword.Length < PharmacyDefinitions.MINIMUM_PASSWORD_LENGHT) { NewPasswordAwareTextBlockVisibility = Visibility.Visible; mes = NewPasswordAwareMessage.NotMeetLenght; } else if (NewPassword.IndexOfAny(PharmacyDefinitions.SPECIAL_CHARS_OF_PASSWORD) == -1) { NewPasswordAwareTextBlockVisibility = Visibility.Visible; mes = NewPasswordAwareMessage.WrongFormat; } else { NewPasswordAwareTextBlockVisibility = Visibility.Collapsed; } NewPasswordAwareTextBlockContent = mes.GetStringValue(); }
public ActionResult ChangePassword( [Bind(Include = "OldPassword,Password,ConfirmPassword")] NewPassword NewPasswordRequest) { if (!NewPasswordRequest.IsMatched()) { Session["error"] = "New passwords aren't matched!"; return(RedirectToAction("Index")); } var LoggedUser = Session["LoggedUser"] as User; var LoggedUserInDB = DB.Users.SingleOrDefault(u => u.Email == LoggedUser.Email); if (LoggedUser != null) { var oldHasedPassword = ComputeSha256Hash(NewPasswordRequest.OldPassword); var newHashedPassword = ComputeSha256Hash(NewPasswordRequest.Password); // if old password is same as in db if (LoggedUserInDB.Password.ToLower() == oldHasedPassword.ToLower()) { LoggedUserInDB.Password = newHashedPassword; DB.SaveChanges(); Session["success"] = "Password has been changed"; } else { Session["error"] = "Old passwords doesnt match!"; } } return(RedirectToAction("Index")); }
public void ChangePassword_Click(object sender, EventArgs e) { using (LoginService service = new LoginService()) { try { if (!NewPassword.Text.Equals(ConfirmNewPassword.Text) || NewPassword.Text.Equals(string.Empty)) { ErrorMessage.Text = ErrorMessages.PasswordsDontMatch; ErrorMessagePanel.Visible = true; } else { service.ChangePassword(Username.Text, OriginalPassword.Value, NewPassword.Text); SessionManager.InitializeSession(Username.Text, NewPassword.Text); } } catch (Exception ex) { ErrorMessage.Text = ex.Message; ErrorMessagePanel.Visible = true; NewPassword.Focus(); // May want to elimiate this. Platform.Log(LogLevel.Error, ex, "Unexpected exception changing password: {0}.", ex.Message); } } }
public async Task <ApiResult <bool> > ChangePassword(int id, NewPassword newPassword) { try { var stopwatch = Stopwatch.StartNew(); _logger.LogInformation("Change password"); newPassword.UserId = id; var result = await _userService.ChangePassword(newPassword); _logger.LogInformation("Change password complete"); stopwatch.Stop(); result.ExecutionTime = stopwatch.Elapsed.TotalMilliseconds; _logger.LogInformation($"Execution time: {result.ExecutionTime}ms"); return(result); } catch (Exception ex) { _logger.LogInformation($"Change password error: {ex}"); return(new ApiResult <bool> { Result = false, ApiCode = ApiCode.UnknownError, ErrorMessage = ex.ToString() }); } }
/// <summary> /// Returns true if SessionsModel5 instances are equal /// </summary> /// <param name="other">Instance of SessionsModel5 to be compared</param> /// <returns>Boolean</returns> public bool Equals(SessionsModel5 other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( OldPassword == other.OldPassword || OldPassword != null && OldPassword.Equals(other.OldPassword) ) && ( NewPassword == other.NewPassword || NewPassword != null && NewPassword.Equals(other.NewPassword) ) && ( Email == other.Email || Email != null && Email.Equals(other.Email) )); }
private void SetupCommands() { ChangePasswordCommand = new Command(async(e) => { if (NewPassword.Equals(ConfirmPassword)) { var bytes = Util.EncryptAes(NewPassword); string encryptedNewPassword = BitConverter.ToString(bytes); //Todo remove once password field is added on the server side //var mobileUserService = new MobileUserService(); //AppMobileUser user = new AppMobileUser(); //user.password = encryptedNewPassword; //AppMobileUser updatedUser = await mobileUserService.UpdateMobileUser(user); //update password in local database DatabaseHelper.GetInstance().ChangePassword(NewPassword); await Application.Current.MainPage.DisplayAlert("", AppConstant.SuccessPasswordChange, AppConstant.Done); await navigation.PopAsync(); } else { await Application.Current.MainPage.DisplayAlert("", AppConstant.PasswordUnmatchedError, AppConstant.Done); } }); }
private bool ValidateData() { if (string.IsNullOrEmpty(CurrentPassword)) { AlertDialog = "You must enter your Current Password"; EntryEmpty = "Red"; return(false); } if (string.IsNullOrEmpty(NewPassword) || NewPassword?.Length < 6) { AlertDialog = "You must enter your New Password"; EntryEmpty = "Red"; return(false); } if (string.IsNullOrEmpty(ConfirmPassword)) { AlertDialog = "You must enter the Password Confirmation"; EntryEmpty = "Red"; return(false); } if (!NewPassword.Equals(ConfirmPassword)) { AlertDialog = "The new password and the confirmation does not match"; EntryEmpty = "Red"; return(false); } return(true); }
protected override void OnConfirmed(CancelEventArgs e) { if (String.IsNullOrEmpty(EMail)) { e.Cancel = true; ErrorMessage = "Email Address cannot be empty."; } else if (String.IsNullOrEmpty(NewPassword) || String.IsNullOrEmpty(VerifyPassword)) { e.Cancel = true; ErrorMessage = "Passwords cannot be empty."; } else if (!NewPassword.Equals(VerifyPassword)) { e.Cancel = true; ErrorMessage = "Passwords must match."; } else { var result = provider.RegisterAccount(this.cloud, EMail, NewPassword); if (!result.Response) { ErrorMessage = result.Message; e.Cancel = true; } } }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Uuid != null) { hashCode = hashCode * 59 + Uuid.GetHashCode(); } if (NewPassword != null) { hashCode = hashCode * 59 + NewPassword.GetHashCode(); } if (NewPasswordConfirmed != null) { hashCode = hashCode * 59 + NewPasswordConfirmed.GetHashCode(); } if (OldPassword != null) { hashCode = hashCode * 59 + OldPassword.GetHashCode(); } return(hashCode); } }
public void FillChangePasswordForm(string oldPassword, string newPassword, string retypeNewPassword) { OldPassword.SendKeys(oldPassword); // Eski parolayı doldurur. NewPassword.SendKeys(newPassword); // Yeni parolayı doldurur. RetypeNewPassword.SendKeys(retypeNewPassword); // Yeni parolayı tekrar doldurur. ChangeButton.Click(); // "Şifre Değiştir" butonuna tıklar. }