public async Task ChangePasswordAsync(ChangeUserPasswordDto changeUserPasswordDto) { Guid userId = _currentUserService.UserId; var userEntity = await _tripFlipDbContext .Users .FirstOrDefaultAsync(user => user.Id == userId); EntityValidationHelper.ValidateEntityNotNull( userEntity, ErrorConstants.UserNotFound); bool passwordIsVerified = PasswordHasherHelper.VerifyPassword( changeUserPasswordDto.OldPassword, userEntity.PasswordHash); if (!passwordIsVerified) { throw new ArgumentException(ErrorConstants.PasswordNotVerified); } string newHashedPassword = PasswordHasherHelper.HashPassword( changeUserPasswordDto.NewPassword); userEntity.PasswordHash = newHashedPassword; await _tripFlipDbContext.SaveChangesAsync(); }
public async Task <ActionResult <BaseResponse <UserDTO> > > Put(int id, [FromBody] UserDTO user) { try { if (!ModelState.IsValid) { return(CreateResponse <UserDTO>(false, null, GetModelStateErrors())); } var users = await _userRepo.Get(u => u.Id == id, tracking : false); if (users == null || users.Length == 0) { return(CreateResponse <UserDTO>(false, null, "User not found")); } if (!string.IsNullOrEmpty(user.Password)) { user.Password = PasswordHasherHelper.ComputePassword(user.Password); } user.Id = id; user.Roles = await GetRoles(user); var dao = _mapper.Map <User>(user); _userRepo.Update(dao); await _userRepo.SaveAsync(); return(CreateResponse(true, _mapper.Map <UserDTO>(dao))); } catch (Exception ex) { return(CreateResponse <UserDTO>(false, null, ex.Message)); } }
public async Task <AuthorizedUserViewModel> RegisterAsync(UserRegisterViewModel userRegisterViewModel) { if (userRegisterViewModel.Password != userRegisterViewModel.PasswordConfirmation) { throw new ArgumentException(); } var userEntity = _mapper.Map <UserEntity>(userRegisterViewModel); userEntity.PasswordHash = PasswordHasherHelper.HashPassword(userRegisterViewModel.Password); await _context.Users.AddAsync(userEntity); await _context.SaveChangesAsync(); var loginViewModel = new UserLoginViewModel() { Login = userRegisterViewModel.Login, Password = userRegisterViewModel.Password }; var authorizedUserViewModel = await LoginAsync(loginViewModel); return(authorizedUserViewModel); }
public async Task ChangePasswordAsync_GivenValidData_Successful() { // Arrange. Seed(TripFlipDbContext, ValidUser); CurrentUserService = CreateCurrentUserService(ValidUser.Id, ValidUser.Email); var jwtConfiguration = CreateJwtConfiguration(); var userService = new UserService( mapper: Mapper, tripFlipDbContext: TripFlipDbContext, jwtConfiguration: jwtConfiguration, currentUserService: CurrentUserService, environment: null, mailService: null, mailServiceConfiguration: null); var correctOldPassword = "******"; var changePasswordDto = GetChangeUserPasswordDto(oldPassword: correctOldPassword); var correctNewPassword = "******"; // Act. await userService.ChangePasswordAsync(changePasswordDto); var user = await TripFlipDbContext.Users.FindAsync(ValidUser.Id); var passwordVerified = PasswordHasherHelper.VerifyPassword(correctNewPassword, user.PasswordHash); // Assert. Assert.IsTrue(passwordVerified); }
public async Task <ActionResult <BaseResponse <string> > > Token([FromBody] TokenRequest request) { var users = await _userRepo.Get(u => u.Email == request.Email && PasswordHasherHelper.ComparePassword(request.Password, u.Password)); if (users != null && users.Length > 0) { //User was authenticated var _user = users.First(); //Add claims var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Email, request.Email)); if (_user.Roles.Any(r => r.Role.Name == Constants.ROLE_ADMIN)) { claims.Add(new Claim(Constants.CLAIM_IS_ADMIN_USER, "1")); } //Generate Token var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecurityKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _options.Domain, audience: _options.Domain, claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return(CreateResponse(true, new JwtSecurityTokenHandler().WriteToken(token))); } return(CreateResponse <string>(false, null, "Could not verify email and password")); }
public async Task <UserDto> RegisterAsync(RegisterUserDto registerUserDto) { bool emailIsAlreadyTaken = _tripFlipDbContext .Users .Any(user => user.Email == registerUserDto.Email); if (emailIsAlreadyTaken) { throw new ArgumentException(ErrorConstants.EmailIsTaken); } var userEntity = _mapper.Map <UserEntity>(registerUserDto); userEntity.PasswordHash = PasswordHasherHelper.HashPassword(registerUserDto.Password); await _tripFlipDbContext.Users.AddAsync(userEntity); await _tripFlipDbContext.SaveChangesAsync(); await EmailUserNotifierHelper.NotifyRegisteredUserAsync( userEntity.Email, _environment, _mailService, _mailServiceConfiguration); var userDto = _mapper.Map <UserDto>(userEntity); return(userDto); }
public async Task <AuthenticatedUserDto> AuthorizeAsync(LoginDto loginDto) { var userEntity = await _tripFlipDbContext .Users .AsNoTracking() .Include(user => user.ApplicationRoles) .ThenInclude(usersRoles => usersRoles.ApplicationRole) .FirstOrDefaultAsync(user => user.Email == loginDto.Email); EntityValidationHelper.ValidateEntityNotNull( userEntity, ErrorConstants.UserNotFound); bool isPasswordVerified = PasswordHasherHelper .VerifyPassword(loginDto.Password, userEntity.PasswordHash); if (!isPasswordVerified) { throw new ArgumentException(ErrorConstants.PasswordNotVerified); } AuthenticatedUserDto authenticatedUserDto = _mapper.Map <AuthenticatedUserDto>(userEntity); authenticatedUserDto.Token = JsonWebTokenHelper.GenerateJsonWebToken( userIncludingRoles: userEntity, issuer: _jwtConfiguration.Issuer, audience: _jwtConfiguration.Audience, secretKey: _jwtConfiguration.SecretKey, tokenLifetime: _jwtConfiguration.TokenLifetime); return(authenticatedUserDto); }
public void HashPassword_GivenNullParameter_ExceptionThrown() { // Arrange string password = null; // Act & Assert Assert.ThrowsException <ArgumentNullException>(() => PasswordHasherHelper.HashPassword(password)); }
public void HashPassword_GivenValidData_Successful() { // Arrange string password = "******"; // Act string resultPasswordHash = PasswordHasherHelper.HashPassword(password); // Assert Assert.IsFalse(string.IsNullOrWhiteSpace(resultPasswordHash)); }
public void VerifyPassword_GivenValidData_Successful() { // Arrange. var password = "******"; var passwordHash = GetPasswordHash(); // Act. var result = PasswordHasherHelper.VerifyPassword(password, passwordHash); // Assert. Assert.IsTrue(result); }
public string GenerateToken([FromBody] LoginInputDTO data) { var user = _userRepository.GetByUserName(data.UserName); var hash = PasswordHasherHelper.HashString($"{data.Password}{user.Salt}"); if (hash != user.HashPassword) { throw new UnauthorizedException(user); } return($"{user.GenerationToken()}.{user.Id}"); }
/// <summary> /// Creates a user entity with randomized password. /// </summary> /// <param name="email">Email to create user with.</param> /// <returns>Created user entity.</returns> private UserEntity CreateUserEntityWithRandomPassword(string email) { var password = PasswordGeneratorHelper.GeneratePassword(useLowercase: true, useUppercase: true, useNumbers: true, useSpecial: true, passwordSize: 50); var passwordHash = PasswordHasherHelper.HashPassword(password); return(new UserEntity() { Email = email, PasswordHash = passwordHash, ApplicationRoles = new List <ApplicationUserRoleEntity>() }); }
public async Task <ActionResult <BaseResponse <UserDTO> > > Post([FromBody] UserDTO user) { try { if (!ModelState.IsValid) { return(CreateResponse <UserDTO>(false, null, GetModelStateErrors())); } user.Password = PasswordHasherHelper.ComputePassword(user.Password); user.Roles = await GetRoles(user); var dao = _mapper.Map <User>(user); _userRepo.Add(dao); await _userRepo.SaveAsync(); return(CreateResponse(true, _mapper.Map <UserDTO>(dao))); } catch (Exception ex) { return(CreateResponse <UserDTO>(false, null, ex.Message)); } }
public async Task <AuthorizedUserViewModel> LoginAsync(UserLoginViewModel userLoginViewModel) { var userEntity = await _context.Users .AsNoTracking() .FirstOrDefaultAsync(u => u.Login == userLoginViewModel.Login); bool isPasswordVerified = PasswordHasherHelper .VerifyPassword(userLoginViewModel.Password, userEntity.PasswordHash); if (!isPasswordVerified) { throw new ArgumentException(); } var token = JsonWebTokenHelper.GenerateJsonWebToken(userEntity.Id, userEntity.Login); var authorizedUserViewModel = new AuthorizedUserViewModel() { JwtToken = token, Email = userEntity.Login }; return(authorizedUserViewModel); }
public void SetPassword(string password) { HashedPassword = PasswordHasherHelper.HashPassword(password); }
/// <summary> /// Initializes the database the first time with initial data /// </summary> public static async Task Initialize(ApiContext context) { try { await context.Database.MigrateAsync(); } catch { } if (!context.Roles.Any()) { await context.Roles.AddAsync(new Role { Id = Constants.ROLE_ADMIN_ID, Name = Constants.ROLE_ADMIN }); await context.Roles.AddAsync(new Role { Id = Constants.ROLE_USER_ID, Name = Constants.ROLE_USER }); await context.SaveChangesAsync(); } if (!context.Users.Any()) { var adminRole = await context.Roles.FirstOrDefaultAsync(r => r.Id == Constants.ROLE_ADMIN_ID); var userRole = await context.Roles.FirstOrDefaultAsync(r => r.Id == Constants.ROLE_USER_ID); await context.Users.AddAsync(new User { Name = "David Admin", Surname = "Lorenzo", Password = PasswordHasherHelper.ComputePassword("David123"), Email = "*****@*****.**", Roles = new List <UserRole> { new UserRole { Role = adminRole } } }); await context.Users.AddAsync(new User { Name = "David User", Surname = "Lorenzo", Password = PasswordHasherHelper.ComputePassword("David123"), Email = "*****@*****.**", Roles = new List <UserRole> { new UserRole { Role = userRole } } }); await context.SaveChangesAsync(); } }
public ApplicationUserManager(IUserStore <ApplicationUser> store) : base(store) { PasswordHasher = new PasswordHasherHelper(FormsAuthPasswordFormat.MD5); }
public void SetPassword(string password) { Salt = Guid.NewGuid().ToString(); HashPassword = PasswordHasherHelper.HashString($"{password}{Salt}"); }
public bool IsPasswordEqual(string password) { return(PasswordHasherHelper.HashPassword(password) == HashedPassword); }