public User Create(User user, string password) { // validation if (string.IsNullOrWhiteSpace(password)) { throw new AppException("Password is required"); } var existingUser = _userRepository.GetUserByUsername(user.Username); if (existingUser != null) { throw new AppException($"Username \"{user.Username}\" is already taken"); } UserServiceHelper.CreatePasswordHash(password, out var passwordHash, out var passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; var role = new UserRole { Role = Role.User, }; user.Role = role; _userRepository.AddUser(user, role); return(user); }
public void CreatePasswordHash_PasswordIsNull_ThrowsArgumentNullException() { var ex = Assert.Throws(typeof(ArgumentNullException), () => UserServiceHelper.CreatePasswordHash(null, out var passwordHash, out var passwordSalt)); Assert.That(ex.Message, Is.EqualTo("Value cannot be null.\r\nParameter name: password")); }
public void CreatePasswordHash_PasswordIsEmpty_ThrowsArgumentNullException() { var ex = Assert.Throws(typeof(ArgumentException), () => UserServiceHelper.CreatePasswordHash("", out var passwordHash, out var passwordSalt)); Assert.That(ex.Message, Is.EqualTo("Value cannot be empty or whitespace only string.\r\nParameter name: password")); }
public User Update(User userParam, string password = null) { var user = _userRepository.GetUserById(userParam.Id); if (user == null) { throw new AppException("User not found"); } if (userParam.Username != user.Username) { var existingUser = _userRepository.GetUserByUsername(userParam.Username); // username has changed so check if the new username is already taken if (existingUser != null) { throw new AppException("Username " + userParam.Username + " is already taken"); } } // update user properties user.FirstName = userParam.FirstName; user.LastName = userParam.LastName; user.Username = userParam.Username; // update password if it was entered if (!string.IsNullOrWhiteSpace(password)) { UserServiceHelper.CreatePasswordHash(password, out var passwordHash, out var passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; } _userRepository.UpdateUser(user); return(user); }
public void Authenticate_UserIsInDb_ReturnsUserEntity() { var user = new User { Username = "******", Role = new UserRole { Role = loggyAPI.Data.Entities.Enums.Role.Admin } }; UserServiceHelper.CreatePasswordHash("username", out var hash, out var salt); user.PasswordHash = hash; user.PasswordSalt = salt; _userRepository .Setup(x => x.GetUserByUsername("username")) .Returns(user); var result = _userService.Authenticate("username", "username", "111dafasfasfasfasfasfsd"); Assert.AreEqual(true, result != null); }
public void CreatePasswordHash_PasswordIsValid_ThrowsArgumentNullException() { UserServiceHelper.CreatePasswordHash("password", out var passwordHash, out var passwordSalt); Assert.AreEqual(64, passwordHash.Length); Assert.AreEqual(128, passwordSalt.Length); }