public async Task <ActionResult <UULResponse> > ChangePassword(UserUpdatePasswordDTO userPwdsDTO) { if (!userPwdsDTO.isValid(out var msg)) { return(Error.ProfileValidationFailed.CreateErrorResponse(_logger, "ChangePassword", new Exception(msg))); } UULResponse response; try { var userInfoDTO = await AuthenticateUserOrThrow(userPwdsDTO.toLoginInfoDTO()); var user = await UserDao.GetUserByDetailsOrThrow(_context, userInfoDTO.Login, userInfoDTO.ApartmentCode); var salt = SecHelper.CreateSalt(); user.Salt = salt; user.Hash = SecHelper.SaltAndHashPwd(userPwdsDTO.NewPwd, salt); _context.Users.Update(user); await _context.SaveChangesAsync(); var tokenString = SecHelper.GenerateJSONWebToken(userInfoDTO.Login, userInfoDTO.ApartmentCode, _config); var habitants = await _context.Habitants.Where(h => h.User.ID == user.ID).Select(h => new HabitantDTO(h)).ToListAsync(); response = new UULResponse() { Success = true, Message = tokenString, Data = new UserInfoDTO(user, habitants) }; } catch (UserProfileNotFoundException e) { response = Error.ProfileNotFound.CreateErrorResponse(_logger, "ChangePassword", e); } catch (AuthException e) { response = Error.AuthFailed.CreateErrorResponse(_logger, "ChangePassword", e); } catch (Exception e) { response = Error.ProfileChangePwdFailed.CreateErrorResponse(_logger, "ChangePassword", e); } return(response); }
public static User AddFromDto(UULContext context, NewUserDTO newUser) { var salt = SecHelper.CreateSalt(); var habitant = new Habitant(newUser); context.Habitants.Add(habitant); var userToSave = new User { Login = newUser.Login, IsActivated = false, CreatedAt = DateOperations.Now(), Hash = SecHelper.SaltAndHashPwd(newUser.Pwd, salt), Salt = salt, ApartmentCode = newUser.ApartmentCode, Habitants = new List <Habitant>() { habitant } }; context.Users.Add(userToSave); return(userToSave); }
private async Task <UserInfoDTO> AuthenticateUserOrThrow(UserLoginInfoDTO loginInfoDTO) { var stored = await UserDao.GetUserByDetailsOrThrow(_context, loginInfoDTO.Login, loginInfoDTO.ApartmentCode); var saltedAndHashedPwd = SecHelper.SaltAndHashPwd(loginInfoDTO.Pwd, stored.Salt); if (saltedAndHashedPwd != stored.Hash) { throw new AuthException("Wrong credentials"); } return(new UserInfoDTO() { ApartmentCode = loginInfoDTO.ApartmentCode, Login = loginInfoDTO.Login }); }