Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/main/java/com/heftyb/dms/users/UserDTO.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package com.heftyb.dms.users;

import com.heftyb.dms.crm.Employee;
import com.heftyb.dms.validation.ValidPassword;
import jakarta.validation.constraints.NotNull;

/**
* User data transfer object, used for mapping data from the request.
*/
public class UserDTO {
private String username;

@NotNull
@ValidPassword
private String password;
private String matchingPassword;
private String email;
Expand Down
13 changes: 7 additions & 6 deletions src/main/java/com/heftyb/dms/users/services/UserServiceImp.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ public UserServiceImp(final UserRepository userRepo,


private boolean emailExist(String email) {
List<User> matchingEmails = userRepo.findByEmailContainingIgnoreCase(email);
return !matchingEmails.isEmpty();
return userRepo.findByEmailIgnoreCase(email).isPresent();
}

@Override
Expand Down Expand Up @@ -80,7 +79,9 @@ public User registerNewUserAccount(final UserDTO userDto) {
@Override
public User getUser(String verificationToken) {
VerificationToken token = verificationTokenRepo.findByToken(verificationToken)
.orElseThrow(() -> new DataNotFoundException(String.format("", verificationToken)));
.orElseThrow(() -> new DataNotFoundException(String.format(
"Cannot find VerificationToken %s", verificationToken
)));
return token.getUser();
}

Expand Down Expand Up @@ -132,7 +133,7 @@ public VerificationToken getVerificationToken(String verificationToken) {
public VerificationToken generateNewVerificationToken(String token) {
VerificationToken newToken = verificationTokenRepo.findByToken(token).orElseThrow(
() -> new DataNotFoundException(String.format(
"VerificationToken %s can't be found!"
"VerificationToken %s can't be found!", token
))
);
newToken.updateToken(UUID.randomUUID().toString());
Expand Down Expand Up @@ -177,7 +178,7 @@ public PasswordResetToken getPasswordResetToken(String token) {

@Override
public Optional<User> getUserByPasswordResetToken(String token) {
return Optional.ofNullable(passResetRepo.findByToken(token).get().getUser());
return passResetRepo.findByToken(token).map(PasswordResetToken::getUser);
}

@Override
Expand All @@ -198,7 +199,7 @@ public void changeUserPassword(User user, String password) {

@Override
public boolean checkIfValidOldPassword(User user, String password) {
return passwordEncoder.matches(user.getPassword(), password);
return passwordEncoder.matches(password, user.getPassword());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ public void initialize(final ValidPassword arg0) {

@Override
public boolean isValid(final String password, final ConstraintValidatorContext context) {
// null is left to @NotNull, per the Bean Validation convention
if (password == null) {
return true;
}

// @formatter:off
final PasswordValidator validator = new PasswordValidator(Arrays.asList(
new LengthRule(8, 30),
Expand All @@ -29,8 +34,9 @@ public boolean isValid(final String password, final ConstraintValidatorContext c
if (result.isValid()) {
return true;
}
// context.disableDefaultConstraintViolation();
// context.buildConstraintViolationWithTemplate(Joiner.on(",").join(validator.getMessages(result))).addConstraintViolation();
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(String.join(" ", validator.getMessages(result)))
.addConstraintViolation();
return false;
}

Expand Down
62 changes: 62 additions & 0 deletions src/test/java/com/heftyb/dms/users/UserDTOValidationTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.heftyb.dms.users;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;

class UserDTOValidationTest {

private static ValidatorFactory factory;
private static Validator validator;

@BeforeAll
static void setUp() {
factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}

@AfterAll
static void tearDown() {
factory.close();
}

@ParameterizedTest
@ValueSource(strings = {"12345678", "correct-horse", "a-29-character-password-here!"})
void acceptsPasswordsBetween8And30CharactersWithoutWhitespace(String password) {
assertThat(passwordViolations(password)).isEmpty();
}

@ParameterizedTest
@ValueSource(strings = {"short", "has a space", "this-password-is-longer-than-thirty-chars"})
void rejectsPasswordsOutsideThePolicy(String password) {
assertThat(passwordViolations(password)).isNotEmpty();
}

@Test
void rejectsMissingPassword() {
assertThat(passwordViolations(null)).isNotEmpty();
}

@Test
void explainsWhichRuleFailed() {
assertThat(passwordViolations("short"))
.extracting(ConstraintViolation::getMessage)
.anyMatch(message -> message.contains("8 or more characters"));
}

private Set<ConstraintViolation<UserDTO>> passwordViolations(String password) {
UserDTO dto = new UserDTO();
dto.setPassword(password);
return validator.validateProperty(dto, "password");
}
}
125 changes: 125 additions & 0 deletions src/test/java/com/heftyb/dms/users/services/UserServiceImpTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package com.heftyb.dms.users.services;

import com.heftyb.dms.crm.Employee;
import com.heftyb.dms.crm.repositories.EmployeeRepository;
import com.heftyb.dms.exceptions.DataNotFoundException;
import com.heftyb.dms.exceptions.UserAlreadyExistException;
import com.heftyb.dms.users.Role;
import com.heftyb.dms.users.User;
import com.heftyb.dms.users.UserDTO;
import com.heftyb.dms.users.repositories.RoleRepository;
import com.heftyb.dms.users.repositories.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

@SpringBootTest
@ActiveProfiles("test")
@Transactional
class UserServiceImpTest {

private static final String PASSWORD = "correct-horse";

@Autowired
private UserService userService;

@Autowired
private UserRepository userRepo;

@Autowired
private EmployeeRepository employeeRepo;

@Autowired
private RoleRepository roleRepo;

@Autowired
private PasswordEncoder passwordEncoder;

@BeforeEach
void createUserRole() {
roleRepo.save(new Role("USER"));
}

@Test
void oldPasswordCheckAcceptsCurrentPassword() {
User sam = existingUser("sam", "sam@example.com");

assertThat(userService.checkIfValidOldPassword(sam, PASSWORD)).isTrue();
}

@Test
void oldPasswordCheckRejectsWrongPassword() {
User sam = existingUser("sam", "sam@example.com");

assertThat(userService.checkIfValidOldPassword(sam, "wrong-horse")).isFalse();
}

@Test
void registrationAllowsEmailContainedInAnExistingOne() {
existingUser("sam", "sam@example.com");

User am = userService.registerNewUserAccount(registration("am", "am@example.com"));

assertThat(am.getEmail()).isEqualTo("am@example.com");
}

@Test
void registrationRejectsDuplicateEmailIgnoringCase() {
existingUser("sam", "sam@example.com");

assertThatThrownBy(() -> userService.registerNewUserAccount(registration("sam2", "SAM@example.com")))
.isInstanceOf(UserAlreadyExistException.class);
}

@Test
void unknownPasswordResetTokenYieldsEmpty() {
assertThat(userService.getUserByPasswordResetToken("no-such-token")).isEmpty();
}

@Test
void knownPasswordResetTokenYieldsItsUser() {
User sam = existingUser("sam", "sam@example.com");
userService.createPasswordResetTokenForUser(sam, "reset-123");

assertThat(userService.getUserByPasswordResetToken("reset-123"))
.map(User::getId)
.contains(sam.getId());
}

@Test
void unknownVerificationTokenErrorNamesTheToken() {
assertThatThrownBy(() -> userService.getUser("no-such-token"))
.isInstanceOf(DataNotFoundException.class)
.hasMessageContaining("no-such-token");
}

@Test
void regeneratingUnknownVerificationTokenThrowsNotFound() {
assertThatThrownBy(() -> userService.generateNewVerificationToken("no-such-token"))
.isInstanceOf(DataNotFoundException.class)
.hasMessageContaining("no-such-token");
}

private User existingUser(String username, String email) {
return userRepo.save(new User(username, passwordEncoder.encode(PASSWORD), email, employee()));
}

private UserDTO registration(String username, String email) {
return new UserDTO(username, PASSWORD, PASSWORD, email, employee());
}

private Employee employee() {
Employee e = new Employee();
e.setFirstName("Sam");
e.setLastName("Ortiz");
e.setPreferredName("Sam");
return employeeRepo.save(e);
}
}
Loading