public Boolean updatePass([FromBody] PasswordUpdateModel user) { if (!isValidateApiUser(user.token)) { return(false); } try { UserModel u; if ((u = db.Users.Find(user.username)) == null) { return(false); } if (u.password == user.cpass) { u.password = user.npass; db.Entry(u).State = EntityState.Modified; db.SaveChanges(); return(true); } return(false); } catch (Exception e) { Console.WriteLine(e.Message); return(false); } }
public ActionResult UpdatePassword([FromBody] PasswordUpdateModel model) { //Map userModel to entity and set id User loggedUser = (User)HttpContext.Items["User"]; if (loggedUser == null) { return(NotFound(new { message = "No user is logged" })); } try { _userService.SetNewPassword(loggedUser, model.NewPassword, model.OldPassword); } catch (RequestException ex) { if (ex.Code == UserExceptionCodes.BadPassword) { return(BadRequest(new { message = "Password doesn't meet requirements" })); } if (ex.Code == UserExceptionCodes.InvalidCredentials) { return(BadRequest(new { message = "Old password doesn't match" })); } return(BadRequest(new { message = "Unknown error" })); } return(Ok()); }
public void CanUserUpdatePasswordTest() { IMateDAO <Mate> MateDAO = new MateDAO(_connection); Mate testMate = new Mate(); testMate.FirstName = "Jessica"; testMate.LastName = "Coelho"; testMate.UserName = "******"; testMate.Password = "******"; testMate.Email = "*****@*****.**"; testMate.Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; testMate.Address = "Ordem"; testMate.Categories = new[] { Categories.FURNITURE_ASSEMBLE, Categories.TRANSPORTATION }; testMate.Rank = Ranks.MATE; testMate.Range = 20; Mate returned = MateDAO.Create(testMate); UserDAO userDAO = new UserDAO(_connection); PasswordUpdateModel newPass = new PasswordUpdateModel(); newPass.Password = "******"; newPass.OldPassword = "******"; Assert.True(userDAO.UpdatePassword(newPass, returned.Id)); _fixture.Dispose(); }
public async Task<ActionResult> UpdatePassword(PasswordUpdateModel accountUM) { try { if (!ModelState.IsValid) { return BadRequest(); } MyUser user = await _userManager.GetUserAsync(User); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, accountUM.CurrentPassword, accountUM.NewPassword); if (result.Succeeded) { return Ok(); } else { return BadRequest(result.Errors); } } else { return NotFound(); } } catch (Exception e) { return BadRequest(e.Message); } }
async Task SaveChangesEdit() { if (SelectedPassword.ApplicationId == SelectedApplicationAlias.Id && SelectedPassword.PasswordAlias == PasswordAlias.Trim() && SelectedPassword.Username == Username.Trim() && SelectedPassword.Password == Password.Trim()) { IsEditing = false; return; } int applicationId = SelectedApplicationAlias.Id; int passwordId = SelectedPassword.Id; PasswordUpdateModel passwordUpdateModel = new PasswordUpdateModel() { ApplicationId = SelectedApplicationAlias.Id, PasswordAlias = PasswordAlias.Trim(), Username = Username.Trim(), Password = Password.Trim(), Encrypted = false }; await _passwordsEndPoint.UpdatePassword(passwordId, passwordUpdateModel); await LoadPasswords(); SelectedApplication = Applications.FirstOrDefault(a => a.Id == applicationId); SelectedPassword = Passwords.FirstOrDefault(p => p.Id == passwordId); IsEditing = false; }
public async Task <bool> UpdatePassword(PasswordUpdateModel model) { var settings = new HttpSettings($"{this._url}/password", null, null, "Password updating"); var body = new HttpBody <PasswordUpdateModel>(model); return(await this._httpService.Update <PasswordUpdateModel>(settings, body)); }
public async Task UpdatePassword(int id, PasswordUpdateModel passwordUpdateModel) { using (HttpResponseMessage response = await _apiHelper.ApiClient.PutAsJsonAsync($"/api/Passwords/{id}", passwordUpdateModel)) { if (!response.IsSuccessStatusCode) { throw new Exception(response.ReasonPhrase); } } }
public IActionResult UpdatePassword(PasswordUpdateModel passwordUpdateModel) { try { int?id = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity); if (id == null) { return(Unauthorized(new ErrorMessageModel("Sem Autorização ou sem sessão inciada"))); } UserDAO userDAO = new UserDAO(_connection); bool newPass = userDAO.UpdatePassword(passwordUpdateModel, id); return(Ok(new SuccessMessageModel("Password alterada com sucesso!"))); } catch (Exception ex) { return(BadRequest(new ErrorMessageModel(ex.Message))); } }
public void UpdatePasswordForUser(int id, string userId, PasswordUpdateModel passwordUpdateModel) { string passwordOwner = GetPasswordOwner(id); if (passwordOwner != userId) { throw new Exception("Password was not found or user is unauthorized."); } var p = new { Id = id, UserId = userId, ApplicationId = passwordUpdateModel.ApplicationId, PasswordAlias = passwordUpdateModel.PasswordAlias, Username = passwordUpdateModel.Username, Password = passwordUpdateModel.Password, Encrypted = passwordUpdateModel.Encrypted }; _sql.UpdateData("dbo.spPasswordUpdate_ByUserById", p, "PMDatabase"); }
public async Task RecoverPasswordAsync(PasswordUpdateModel model) { try { await _gatewayRepository.ApiAccountsUsersPasswordPostAsync(_mapper.Map <PasswordUpdate>(model)); } catch (ApiException apiExc) { if (apiExc.StatusCode == 404) { throw new BusinessException(ErrorMessages.uknownUserHeaderText); } else { throw new TechnicalException(ErrorMessages.serverErrorText + apiExc.StatusCode); } } catch { throw; } }
public async Task <bool> UpdatePasswordAsync(PasswordUpdateModel updatePasswordModel, int userId) { User user = await userRepository.GetByIdAsync(userId); if (user is null || !await encryptionService.PasswordEqualsHashAsync( updatePasswordModel.CurrentPassword, user.PasswordHash, user.Salt)) { return(false); } HashedPassword newHashedPassword = await encryptionService.EncryptAsync( Encoding.UTF8.GetBytes(updatePasswordModel.NewPassword)); user.PasswordHash = newHashedPassword.Hash; user.Salt = newHashedPassword.Salt; await userRepository.UpdateAsync(user); await userRepository.SaveChangesAsync(); return(true); }
public bool resetPass([FromBody] PasswordUpdateModel user, [FromUri] string token) { if (!isValidateApiUser(token)) { return(false); } using (db) { try { ResetPasswordModel r = db.ResetPasswords.Find(token); if (r == null) { return(false); } if (user.username == r.username) { UserModel u = db.Users.Find(user.username); if (u == null) { return(false); } u.password = user.npass; db.Entry(u).State = EntityState.Modified; db.ResetPasswords.Remove(r); db.SaveChanges(); return(true); } return(false); } catch (Exception e) { Console.WriteLine(e.Message); return(false); } } }
/// <summary> /// Método que atualiza a password /// de um determindado utilizador /// </summary> /// <param name="newPass">Nova palavra-passe</param> /// <param name="id">Id do utilizador que pretende alterar /// a sua palavra-passe</param> /// <returns> /// True caso a password seja atualizada com sucesso /// False caso contrário /// </returns> public bool UpdatePassword(PasswordUpdateModel newPass, int?id) { User user = FindById((int)id); if (user == null) { throw new Exception("O utilizador não existe!"); } if (PasswordOperations.VerifyHash(newPass.OldPassword, user.Password, user.PasswordSalt)) { using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "UPDATE dbo.[User] " + "SET Password = @pass, PasswordSalt = @salt " + "WHERE Id = @id"; cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; var password = PasswordOperations.Encrypt(newPass.Password); cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = password.Item2; cmd.Parameters.Add("@salt", SqlDbType.NVarChar).Value = password.Item1; if (cmd.ExecuteNonQuery() == 0) { return(false); } } return(true); } else { throw new Exception("A password antiga é inválida!"); } }
// FIXME: I can fix this I think, the route to userName search wont be necessary if I can // provide user id right away from authcontext; public async Task<IdentityResult> UpdatePassword(PasswordUpdateModel model, string userName) { var user = await accountManager.FindByNameAsync(userName); return await accountManager.ChangePasswordAsync(user.Id, model.CurrentPassword, model.NewPassword); }
public void AuthController_UpdatePassword_IntegrationTest_AuthorizedServer() { //Arrange var username = "******"; RegisterModel registerModel = new RegisterModel { Title = "Mr", FullName = "SampleName", UserName = username, UserRole = "User", DialCode = "+91", PhoneNumber = "12341234", Email = "*****@*****.**", Password = "******", UserLocation = "IN", Status = "Verified", OTPExp = DateTime.UtcNow.AddMinutes(4), VerificationCode = "AQAAAAEAACcQAAAAEDpGr4+u/Oik7F6OLHd3Tr03AX+jYRRqNeo48Il9md5wcPFBl+1xpDQLkimghNMogg==" }; PasswordUpdateModel passwordUpdateModel = new PasswordUpdateModel { CurrentPassword = "******", NewPassword = "******" }; var expectedCode = "200"; var expectedMessage = "Password Changed Successfully"; //Insert test data var insert = TH.InsertRegiterModeldata(registerModel).Result; //Act var result = TH.GetAuthController().UpdatePassword(passwordUpdateModel, username) as Task <ActionResult>; var responseData = TH.DeserializedResponceData(result.Result.ToJson()); //Check updated data var updatedData = BsonSerializer.Deserialize <RegisterModel>(MH.GetSingleObject(Builders <BsonDocument> .Filter.Eq("UserName", username), "Authentication", "Authentication").Result); //Check if password is correct bool passwordMatched = false; if (passwordHasher.VerifyHashedPassword(new RegisterModel { UserName = registerModel.UserName, Password = registerModel.Password }, updatedData.Password, passwordUpdateModel.NewPassword).ToString() == "Success") { passwordMatched = true; } //Assert Assert.IsNotNull(result.Result); Assert.AreEqual(responseData.Code, expectedCode); Assert.AreEqual(responseData.Message, expectedMessage); Assert.AreEqual(updatedData.Title, registerModel.Title); Assert.AreEqual(updatedData.FullName, registerModel.FullName); Assert.AreEqual(updatedData.UserName, registerModel.UserName); Assert.AreEqual(updatedData.UserRole, registerModel.UserRole); Assert.AreEqual(updatedData.DialCode, registerModel.DialCode); Assert.AreEqual(updatedData.PhoneNumber, registerModel.PhoneNumber); Assert.AreEqual(updatedData.Email, registerModel.Email); Assert.AreEqual(updatedData.UserLocation, registerModel.UserLocation); Assert.AreEqual(updatedData.Status, registerModel.Status); Assert.AreEqual(updatedData.VerificationCode, registerModel.VerificationCode); Assert.AreEqual(passwordMatched, true); //Delete inserted test data var checkData = MH.CheckForDatas("UserName", username, null, null, "Authentication", "Authentication"); if (checkData != null) { var delete = MH.DeleteSingleObject(Builders <BsonDocument> .Filter.Eq("UserName", username), "Authentication", "Authentication"); } }
public async Task<IHttpActionResult> UpdatePassword(PasswordUpdateModel model) { return Ok(await accountContext.UpdatePassword(model, this.User.Identity.Name)); }
// FIXME: I can fix this I think, the route to userName search wont be necessary if I can // provide user id right away from authcontext; public async Task <IdentityResult> UpdatePassword(PasswordUpdateModel model, string userName) { var user = await accountManager.FindByNameAsync(userName); return(await accountManager.ChangePasswordAsync(user.Id, model.CurrentPassword, model.NewPassword)); }
public async Task <IActionResult> UpdateUserPasswordAsync([FromBody] PasswordUpdateModel updatePasswordModel) { return(this.ConvertResult( await userService.UpdatePasswordAsync(updatePasswordModel, userResolverService.GetUserId()))); }
public async Task <IHttpActionResult> UpdatePassword(PasswordUpdateModel model) { return(Ok(await accountContext.UpdatePassword(model, this.User.Identity.Name))); }
public void Put(int id, [FromBody] PasswordUpdateModel passwordUpdateModel) { string userId = User.FindFirstValue(ClaimTypes.NameIdentifier); _passwordData.UpdatePasswordForUser(id, userId, passwordUpdateModel); }
public async Task <IActionResult> UpdatePassword([FromBody] PasswordUpdateModel model) { await this._userService.UpdatePassword(model.OldPassword, model.NewPassword); return(this.Ok()); }