public async Task Edit_ReturnsTrue() { // Arrange _usersContext = _db.SeedUsersContext(); ulong id = 2; List <Users> currentUsers = _db.Users; Users current = _db.Users.FirstOrDefault(u => u.Id == id); Users updated = current.ShallowCopy(); updated.UserEmail = "*****@*****.**"; UpdatedUser updatedUser = new UpdatedUser { Id = id, UserName = updated.UserName, UserEmail = updated.UserEmail, FirstName = updated.FirstName, LastName = updated.LastName, UserPassword = "******", UserRole = updated.UserRole }; bool expected = true; // Act bool actual = await _usersContext.Edit(id, updatedUser); Users u = _db.Users.FirstOrDefault(u => u.Id == id); _db.Users = new List <Users>(currentUsers); // Assert Assert.Equal(expected, actual); Assert.Equal(updated.UserEmail, u.UserEmail); }
public async Task <UpdatedUser> UpdateAvatarAsync(string email, string avatarUrl) { var user = await _userManager.FindByEmailAsync(email); if (user == null) { throw new Exception("Coudln't find user"); } user.Avatar_Url = avatarUrl; var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { throw new Exception(string.Join(", ", result.Errors.Select(e => e.Description).ToArray())); } UpdatedUser newUser = new UpdatedUser() { avatar_url = user.Avatar_Url, coins = user.coins, exp = user.exp, UserName = user.UserName, isSuccess = true }; return(newUser); }
//Handle Button Click async void Handle_ClickedAsync(object sender, System.EventArgs e) { //Set Password variables string Password = PasswordEntry.Text; string ConfirmPassword = ConfirmPasswordEntry.Text; //If they dont match tell user if (Password != ConfirmPassword) { await DisplayAlert("Warning", "Passwords do not match, please try again", "Ok"); } else { //Set Loading Symbol LoadingSymbol.IsRunning = true; LoadingLayout.IsVisible = true; //Set User Object UpdatedUser updateUser = new UpdatedUser(); updateUser.strEmail = Application.Current.Properties["UserEmail"].ToString(); updateUser.strPassword = Password; try { //Declare Connection Settings HttpClient client = new HttpClient(); string url = "https://melbourneicewebapi.azurewebsites.net/api/UserRequests/Update_User"; var uri = new Uri(url); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var json = JsonConvert.SerializeObject(updateUser); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync(uri, content); //Test POST Request to Server, if accepted, display message and push to news page if (response.StatusCode == System.Net.HttpStatusCode.Accepted) { await DisplayAlert("Welcome", "Your password has been reset! Please now try and login with your new password!", "Ok"); await Navigation.PushAsync(new MainPage()); } //Display Connection Error else { await DisplayAlert("Warning", "Connection with the server has been stopped, please try again later", "Ok"); } } //Handle Exception catch (Exception ex) { Console.WriteLine(ex); } //Turn off Loading Symbols LoadingSymbol.IsRunning = false; LoadingLayout.IsVisible = false; } }
public CreatedUser Update(UpdatedUser updatedUser) { using (BookStoreContext context = new BookStoreContext()) { User user = context.Users.Find(updatedUser.Id); user.Password = SHA256Utils.ComputeHMAC(updatedUser.Password, user.Salt); user.ModifiedDate = DateTime.Now; context.Entry(user).State = EntityState.Modified; context.SaveChanges(); return(Mapper.Map <CreatedUser>(user)); } }
private async Task TestEditUserWithException( ulong id, bool sameUserName = false, bool sameUserEmail = false ) { // Arrange _usersContext = _db.SeedUsersContext(); List <Users> currentUsers = _db.Users; Users current = _db.Users.FirstOrDefault(u => u.Id == id); Users updated = current.ShallowCopy(); // Act switch ((sameUserName, sameUserEmail)) { case (true, false): updated.UserName = "******"; break; case (false, true): updated.UserEmail = "*****@*****.**"; break; case (true, true): updated.UserName = "******"; updated.UserEmail = "*****@*****.**"; break; default: // (false, false) break; } // UserPassword doesn't matter for the purposes of these tests UpdatedUser updatedUser = new UpdatedUser { Id = id, UserName = updated.UserName, UserEmail = updated.UserEmail, FirstName = updated.FirstName, LastName = updated.LastName, UserPassword = "******", UserRole = updated.UserRole }; // Assert await Assert.ThrowsAsync <ExistingUserException>(() => _usersContext.Edit(id, updatedUser)); }
public async Task <IActionResult> Update(UpdatedUser updatedUser) { User user = await UserManager.FindByIdAsync(updatedUser.id); if (user != null) { if (!string.IsNullOrEmpty(updatedUser.password)) { user.PasswordHash = passwordHasher.HashPassword(user, updatedUser.password); } if (!string.IsNullOrEmpty(updatedUser.Image)) { user.Image = updatedUser.Image; } if (!string.IsNullOrEmpty(updatedUser.Email)) { user.Email = updatedUser.Email; } if (!string.IsNullOrEmpty(updatedUser.password) || !string.IsNullOrEmpty(updatedUser.Email) || !string.IsNullOrEmpty(updatedUser.password) || !string.IsNullOrEmpty(updatedUser.Image)) { IdentityResult result = await UserManager.UpdateAsync(user); if (result.Succeeded) { return(Ok()); } else { return(BadRequest()); } } } else { NotFound(); } return(Ok(user)); }
public void Update(UserEntity user) { if (user == null) { throw new ArgumentNullException("user"); } Player player; if (!_playerById.TryGetValue(user.PlayerId, out player)) { player = new Player(user); _playerById.Add(player.PlayerId, player); } else { player.User = user; } UpdatedUser?.Invoke(player); }
public string Update(UpdatedUser user, int userid) { Console.WriteLine("*******!!!!!!!!********!!!!!!!!"); if (ModelState.IsValid) { PasswordHasher <User> Hasher = new PasswordHasher <User>(); User userInDB = dbContext.Users.FirstOrDefault(u => u.UserId == userid); userInDB.FirstName = user.firstName; userInDB.LastName = user.lastName; userInDB.Email = user.email; userInDB.Password = Hasher.HashPassword(userInDB, user.password); dbContext.SaveChanges(); var message = new { message = "Successfully updated user" }; return(JsonConvert.SerializeObject(message)); } else { var error = new { error = "Error modelstate is not valid." }; return(JsonConvert.SerializeObject(error)); } }
/// <summary> /// Updates an existing user /// </summary> /// <param name="id">ID of the user to be updated</param> /// <param name="user">Updated user object</param> /// <exception cref="ExistingUserException"> /// Thrown if another user has the same /// <see cref="Users.UserName"/> or /// <see cref="Users.UserEmail"/> /// as <seealso cref="user"/> /// </exception> /// <returns>Result of the operation</returns> public async Task <bool> Edit(ulong id, UpdatedUser user) { bool userUpdated = false; bool existingUserName = false; bool existingUserEmail = false; if (_context != null) { existingUserName = await _context.Users.AnyAsync(u => u.Id != user.Id && u.UserName == user.UserName); existingUserEmail = await _context.Users.AnyAsync(u => u.Id != user.Id && u.UserEmail == user.UserEmail); if (existingUserName) { throw new ExistingUserException("Username is taken"); } if (existingUserEmail) { throw new ExistingUserException("Email is taken"); } // hash/salt new password string salt = _authenticationService.GenerateSalt(); string hash = _authenticationService.HashPassword(user.UserPassword, salt); var currentUser = await _context.Users.FindAsync(user.Id); try { if (currentUser != null) { currentUser.UserName = user.UserName; currentUser.UserPasswordHash = hash; currentUser.UserPasswordSalt = salt; currentUser.FirstName = user.FirstName; currentUser.LastName = user.LastName ?? currentUser?.LastName; currentUser.UserEmail = user.UserEmail; currentUser.UserRole = user.UserRole ?? currentUser?.UserRole; currentUser.DateCreated = currentUser?.DateCreated; _context.Entry(currentUser).State = EntityState.Modified; await _context.SaveChangesAsync(); userUpdated = true; } } catch (DbUpdateConcurrencyException) { return(false); } } else { existingUserName = Users.Any(u => u.Id != user.Id && u.UserName == user.UserName); existingUserEmail = Users.Any(u => u.Id != user.Id && u.UserEmail == user.UserEmail); if (existingUserName) { throw new ExistingUserException("Username is taken"); } if (existingUserEmail) { throw new ExistingUserException("Email is taken"); } var authenticationService = new AuthenticationService( new AppSettings { Secret = "Secret1", Pepper = "Pepper1" }, this ); // hash/salt new password string salt = authenticationService.GenerateSalt(); string hash = authenticationService.HashPassword(user.UserPassword, salt); var currentUser = Users.FirstOrDefault(u => u.Id == user.Id); if (currentUser != null) { currentUser.UserName = user.UserName; currentUser.UserPasswordHash = hash; currentUser.UserPasswordSalt = salt; currentUser.FirstName = user.FirstName; currentUser.LastName = user.LastName ?? currentUser?.LastName; currentUser.UserEmail = user.UserEmail; currentUser.UserRole = user.UserRole ?? currentUser?.UserRole; currentUser.DateCreated = currentUser?.DateCreated; userUpdated = true; } } return(userUpdated); }
public async Task <IActionResult> PutUsers(ulong id, [FromBody] UpdatedUser user) { if (!_authorizationService.ValidateJWTToken(Request)) { return(Unauthorized(new { errors = new { Token = new string[] { "Invalid token" } }, status = 401 })); } if (id != user.Id) { return(BadRequest(new { errors = new { Id = new string[] { "ID sent does not match the one in the endpoint" } }, status = 400 })); } var existingUserName = await _context.Users.AnyAsync(u => u.Id != user.Id && u.UserName == user.UserName); if (existingUserName) { return(Conflict(new { errors = new { UserName = new string[] { "Username is already taken" } }, status = 409 })); } var existingEmail = await _context.Users.AnyAsync(u => u.Id != user.Id && u.UserEmail == user.UserEmail); if (existingEmail) { return(Conflict(new { errors = new { UserEmail = new string[] { "Email is already registered" } }, status = 409 })); } // hash/salt new password string salt = _authenticationService.GenerateSalt(); string hash = _authenticationService.HashPassword(user.UserPassword, salt); Users currentUser = await _context.Users.FindAsync(user.Id); try { if (currentUser != null) { currentUser.UserName = user.UserName; currentUser.UserPasswordHash = hash; currentUser.UserPasswordSalt = salt; currentUser.FirstName = user.FirstName; currentUser.LastName = user.LastName ?? currentUser?.LastName; currentUser.UserEmail = user.UserEmail; currentUser.UserRole = user.UserRole ?? currentUser?.UserRole; currentUser.DateCreated = currentUser?.DateCreated; _context.Entry(currentUser).State = EntityState.Modified; await _context.SaveChangesAsync(); // Authenticate user var authenticatedUser = await _authenticationService.Authenticate(user.UserEmail, user.UserPassword); if (authenticatedUser == null) { // User isn't registered Response.Headers.Append("Access-Control-Allow-Origin", Request.Headers["Origin"]); return(Unauthorized(new { errors = new { Authentication = new string[] { "Invalid username, email and/or password" } }, status = 401 })); } // Return 200 OK with token in cookie var existingUser = await _context.Users.Where(u => u.Id == authenticatedUser.Id).FirstOrDefaultAsync(); authenticatedUser.BaseUser = existingUser; _authorizationService.SetAuthCookie(Request, Response, authenticatedUser.Token); Response.Headers.Append("X-Authorization-Token", authenticatedUser.Token); return(Ok(existingUser.WithoutPassword())); } return(NotFound()); } catch (DbUpdateConcurrencyException) { return(StatusCode(500)); } }
public async Task <UserResult> UpdateUser(UpdatedUser updatedUser, ClaimsPrincipal claimsUser) { IEnumerable <IdentityError> validationResults = ValidationHelper.ValidateAsIdentity(updatedUser, serviceProvider); if (validationResults.Any()) { return(new UserResult(IdentityResult.Failed(validationResults.ToArray()))); } ApplicationUser?user = await userManager.FindByIdAsync(updatedUser.Id).ConfigureAwait(false); if (user == null) { return(new UserResult(IdentityResult.Failed(new IdentityError() { Code = "NOUSER", Description = "This user doesn't exist" }))); } var loggedInUser = await userManager.GetUserAsync(claimsUser).ConfigureAwait(false); // need to be logged in as either admin, or the user being updated, only admins can update representsNumberParticipants or change a user to admin if (!(claimsUser.IsInRole(AuthorizationConstants.AdminRole) || loggedInUser.Id == user.Id) || (!claimsUser.IsInRole(AuthorizationConstants.AdminRole) && (updatedUser.representsNumberParticipants != user.RepresentsNumberParticipants || updatedUser.IsAdmin))) { return(new UserResult(IdentityResult.Failed(new IdentityError() { Code = "NOPERM", Description = "You don't have permission to update this user" }))); } logger.LogInformation("Updating user"); user.Email = updatedUser.Email; user.FirstName = updatedUser.FirstName; user.LastName = updatedUser.LastName; user.RepresentsNumberParticipants = updatedUser.representsNumberParticipants; var result = await userManager.UpdateAsync(user).ConfigureAwait(false); if (updatedUser.IsAdmin) { await userManager.AddToRoleAsync(user, AuthorizationConstants.AdminRole).ConfigureAwait(false); } else { await userManager.RemoveFromRoleAsync(user, AuthorizationConstants.AdminRole).ConfigureAwait(false); } if (!result.Succeeded) { LogErrors("Error updating user", result); return(new UserResult(result)); } else { try { await newsletterService.SetSubscription(user.Email, updatedUser.IsSubscribedNewsletter).ConfigureAwait(false); } catch (Exception e) { var newsletterResult = IdentityResult.Failed(new IdentityError() { Code = "NEWSSUBCR", Description = $"Newsletter subscription failed: {e.Message}" }); LogErrors("Error updating user", newsletterResult); return(new UserResult(newsletterResult)); } logger.LogInformation("Updated user"); return(new UserResult(user, IdentityResult.Success)); } }