Skip to content

Commit

Permalink
Merge pull request #38 from gdesiato/validators-branch
Browse files Browse the repository at this point in the history
added user and authentication dto validators
  • Loading branch information
gdesiato authored Oct 7, 2024
2 parents 6595d21 + 4397bbc commit e6efe1e
Show file tree
Hide file tree
Showing 13 changed files with 325 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.desiato.puresynth.dtos.*;
import com.desiato.puresynth.services.AuthenticationService;
import com.desiato.puresynth.services.UserService;
import com.desiato.puresynth.validators.AuthenticationRequestValidator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
Expand All @@ -18,10 +19,14 @@
public class LoginController {

private final AuthenticationService authenticationService;
private final AuthenticationRequestValidator validator;

@PostMapping
public ResponseEntity<LoginResponseDTO> authenticateUser(
@RequestBody AuthenticationRequestDTO requestDTO) {

validator.validate(requestDTO);

PureSynthToken pureSynthToken = authenticationService.authenticate(requestDTO);
return ResponseEntity.ok(new LoginResponseDTO(pureSynthToken.value(), "success"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.desiato.puresynth.models.User;
import com.desiato.puresynth.services.SessionService;
import com.desiato.puresynth.services.UserService;
import com.desiato.puresynth.validators.UserRequestValidator;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -20,6 +21,7 @@ public class UserController {

private final UserService userService;
private final SessionService sessionService;
private final UserRequestValidator validator;
private final UserMapper dtoMapper;

@GetMapping("/me")
Expand All @@ -42,6 +44,8 @@ public ResponseEntity<UserResponseDTO> getUserById(@PathVariable Long id) {
@PostMapping
public ResponseEntity<UserResponseDTO> createUser(@RequestBody UserRequestDTO userRequestDTO) {

validator.validate(userRequestDTO);

User createdUser = userService.createUser(userRequestDTO.email(), userRequestDTO.password());

UserResponseDTO userResponseDTO = dtoMapper.toDTO(createdUser);
Expand All @@ -53,6 +57,8 @@ public ResponseEntity<UserResponseDTO> updateUser(
@PathVariable Long id,
@RequestBody UserRequestDTO userRequestDTO) {

validator.validate(userRequestDTO);

User updatedUser = userService.updateUser(id, userRequestDTO);

UserResponseDTO userResponseDto = dtoMapper.toDTO(updatedUser);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.desiato.puresynth.exceptions;

public record ErrorMessage(String message) {
public ErrorMessage {
if (message == null || message.isBlank()) {
throw new IllegalArgumentException("Error message cannot be null or blank");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

Expand All @@ -32,4 +34,11 @@ public ResponseEntity<ErrorLoginResponseDTO> handleInvalidTokenException(
public ResponseEntity<String> handleEntityNotFoundException(EntityNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}

@ExceptionHandler(ValidationException.class)
public ResponseEntity<Object> handleValidationException(ValidationException ex) {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(Map.of("errors", ex.getErrorMessages()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.desiato.puresynth.exceptions;


import java.util.List;

public class ValidationException extends RuntimeException {

private final List<ErrorMessage> errorMessages;

public ValidationException(List<ErrorMessage> errorMessages) {
super("Validation failed");
this.errorMessages = errorMessages;
}

public List<ErrorMessage> getErrorMessages() {
return errorMessages;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.desiato.puresynth.validators;

import com.desiato.puresynth.exceptions.ErrorMessage;
import com.desiato.puresynth.exceptions.ValidationException;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractValidator<T> {

protected abstract void validate(T request, List<ErrorMessage> errorMessages);

public void validate(T request) {
List<ErrorMessage> errorMessages = new ArrayList<>();
validate(request, errorMessages);

if (!errorMessages.isEmpty()) {
throw new ValidationException(errorMessages);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.desiato.puresynth.validators;

import com.desiato.puresynth.dtos.AuthenticationRequestDTO;
import com.desiato.puresynth.exceptions.ErrorMessage;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AuthenticationRequestValidator extends AbstractValidator<AuthenticationRequestDTO> {

@Override
protected void validate(AuthenticationRequestDTO request, List<ErrorMessage> errorMessages) {

if (request.email() == null || request.email().isBlank()) {
errorMessages.add(new ErrorMessage("Email cannot be blank."));
} else if (!request.email().contains("@")) {
errorMessages.add(new ErrorMessage("Invalid email format."));
}

if (request.password() == null || request.password().isBlank()) {
errorMessages.add(new ErrorMessage("Password cannot be blank."));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.desiato.puresynth.validators;

import com.desiato.puresynth.dtos.UserRequestDTO;
import com.desiato.puresynth.exceptions.ErrorMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class UserRequestValidator extends AbstractValidator<UserRequestDTO> {

@Override
protected void validate(UserRequestDTO userRequestDTO, List<ErrorMessage> errorMessages) {

if (userRequestDTO.email() != null) {
if (userRequestDTO.email().isBlank()) {
errorMessages.add(new ErrorMessage("Email cannot be blank."));
} else if (!userRequestDTO.email().contains("@")) {
errorMessages.add(new ErrorMessage("Invalid email format."));
}
} else {
errorMessages.add(new ErrorMessage("Email cannot be null."));
}

if (userRequestDTO.password() != null && !userRequestDTO.password().isBlank()) {
log.info("Password is valid");
} else if (userRequestDTO.password() == null) {
errorMessages.add(new ErrorMessage("Password cannot be null."));
} else {
errorMessages.add(new ErrorMessage("Password cannot be blank."));
}
}
}
1 change: 1 addition & 0 deletions src/test/java/com/desiato/puresynth/BaseTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.desiato.puresynth.services.AuthenticationService;
import com.desiato.puresynth.services.SessionService;
import com.desiato.puresynth.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
package com.desiato.puresynth.controllers;

import com.desiato.puresynth.BaseTest;
import com.jayway.jsonpath.JsonPath;
import com.desiato.puresynth.dtos.AuthenticatedUser;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;


class LoginControllerTest extends BaseTest {

private String uniqueEmail;
private String validPassword;
private String invalidPassword;
private AuthenticatedUser authenticatedUser;


@BeforeEach
void setUp() throws Exception {

authenticatedUser = testAuthenticationHelper.createAndAuthenticateUser();

uniqueEmail = testAuthenticationHelper.generateUniqueEmail();
validPassword = "password123";
invalidPassword = "invalidPassword";

userService.createUser(uniqueEmail, validPassword);
}

@Test
void authenticateUser_WhenPasswordIsInvalid_ShouldReturnUnauthorized() throws Exception {
String uniqueEmail = testAuthenticationHelper.generateUniqueEmail();
String validPassword = "password123";
userService.createUser(uniqueEmail, validPassword);

String invalidPassword = "invalidPassword";
String json = """
{
"email": "%s",
Expand All @@ -32,60 +43,31 @@ void authenticateUser_WhenPasswordIsInvalid_ShouldReturnUnauthorized() throws Ex
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.message").value("Authentication failed. Please check your credentials and try again."));
.andExpect(jsonPath("$.message")
.value("Authentication failed. Please check your credentials and try again."));
}

@Test
void authenticateUser_WhenCredentialsAreValid_ShouldAuthenticateSuccessfully() throws Exception {
String uniqueEmail = testAuthenticationHelper.generateUniqueEmail();
String password = "password123";

userService.createUser(uniqueEmail, password);

String loginJson = String.format("""
{
"email": "%s",
"password": "%s"
}
""", uniqueEmail, password);
""", uniqueEmail, validPassword);

MvcResult loginResult = mockMvc.perform(post("/api/login")
mockMvc.perform(post("/api/login")
.contentType(MediaType.APPLICATION_JSON)
.content(loginJson))
.andExpect(status().isOk())
.andExpect(jsonPath("$.authToken").exists())
.andReturn();

String token = JsonPath.parse(loginResult.getResponse().getContentAsString()).read("$.authToken", String.class);
assertNotNull(token, "Authentication token is missing or invalid");
.andExpect(jsonPath("$.authToken").exists());
}

@Test
void accessProtectedEndpoint_WithValidToken_ShouldAllowAccess() throws Exception {
// Step 1: Create a valid user and authenticate
String uniqueEmail = testAuthenticationHelper.generateUniqueEmail();
String password = "password123";
userService.createUser(uniqueEmail, password);

String loginJson = String.format("""
{
"email": "%s",
"password": "%s"
}
""", uniqueEmail, password);

MvcResult loginResult = mockMvc.perform(post("/api/login")
.contentType(MediaType.APPLICATION_JSON)
.content(loginJson))
.andExpect(status().isOk())
.andExpect(jsonPath("$.authToken").exists())
.andReturn();

String token = JsonPath.parse(loginResult.getResponse().getContentAsString()).read("$.authToken", String.class);

// Step 2: Access a protected endpoint using the valid token
mockMvc.perform(get("/api/user/me")
.header("authToken", token))
.header("authToken", authenticatedUser.pureSynthToken().value()))
.andExpect(status().isOk());
}

Expand Down
Loading

0 comments on commit e6efe1e

Please sign in to comment.