diff --git a/api/build.gradle b/api/build.gradle index 18f66ab..2784c6d 100644 --- a/api/build.gradle +++ b/api/build.gradle @@ -30,6 +30,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-webmvc' + implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.1.1' runtimeOnly 'com.h2database:h2' runtimeOnly 'org.postgresql:postgresql' @@ -37,6 +38,8 @@ dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test' testImplementation 'org.springframework.boot:spring-boot-starter-validation-test' testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + + testImplementation 'org.springframework.boot:spring-boot-starter-security-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } diff --git a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java new file mode 100644 index 0000000..c34e866 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java @@ -0,0 +1,68 @@ +package edu.csumb.cst438.api; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.web.servlet.HandlerExceptionResolver; + +/** + * This class should limit specific API routes to admin only + * Idk if this will later be replaced with OAuth or something else. + * But I wanted to make sure users can't call those specific API routes. + * Also I wanted to test it. + */ +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +public class SecurityConfig { + /** + * This basically just states what routes can only be called by ADMIN + * @param http http + * @return http.build() + * @throws Exception if there's an exception + */ + @Bean + public SecurityFilterChain securityFilterChain( + HttpSecurity http, + @Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) throws Exception{ + AuthenticationEntryPoint entryPoint = (request, response, ex) -> { + response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); + resolver.resolveException(request, response, null, ex); + }; + AccessDeniedHandler deniedHandler = (request, response, ex) -> + resolver.resolveException(request, response, null, ex); + + http + .csrf(csrf -> csrf.disable()) + .headers(headers -> + headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) + .authorizeHttpRequests(auth -> auth + .requestMatchers( + "/v3/api-docs/**", + "/swagger-ui/**", + "/swagger-ui.html" + ).permitAll() + .requestMatchers(HttpMethod.GET, "/api/v1/users/me").authenticated() + .requestMatchers(HttpMethod.DELETE, "/api/v1/users/me").authenticated() + .requestMatchers(HttpMethod.GET, "/api/v1/users").hasRole("ADMIN") + .requestMatchers(HttpMethod.GET, "/api/v1/users/{userid}").hasRole("ADMIN") + .requestMatchers(HttpMethod.PATCH, "/api/v1/users/{userid}").hasRole("ADMIN") + .requestMatchers(HttpMethod.DELETE, "/api/v1/users/{userid}").hasRole("ADMIN") + .anyRequest().authenticated() + ) + .exceptionHandling(ex -> ex + .authenticationEntryPoint(entryPoint) + .accessDeniedHandler(deniedHandler)); + return http.build(); + } +} diff --git a/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java b/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java new file mode 100644 index 0000000..c0c2d9c --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java @@ -0,0 +1,99 @@ +package edu.csumb.cst438.api.controller; + +import edu.csumb.cst438.api.record.UserResponseDTO; +import edu.csumb.cst438.api.record.UserRoleUpdateRequest; +import edu.csumb.cst438.api.service.UserService; +import jakarta.validation.Valid; +import org.springframework.data.domain.Page; +import org.springframework.data.web.PagedModel; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.security.Principal; + +/** + * The home of the API routes and what they do + * Specifically for /api/v1/users and routes beyond that. + */ +@RestController +@RequestMapping("/api/v1/users") +public class UserController { + private final UserService userService; + + /** + * The constructor of UserController + * @param userService UserService instance + */ + public UserController(UserService userService){ + this.userService = userService; + } + + /** + * Call for multiple users on a single page + * @param page What page number the admin goes to (starts at 0) + * @param size What page number the admin goes to (starts at 0) + * @return Ok with users unless the one calling it isn't an Admin + */ + @GetMapping + public ResponseEntity> getAllUsers(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size){ + Page users = userService.getAllUsers(page, size); + return ResponseEntity.ok(new PagedModel<>(users)); + } + + /** + * Call for one user via ID + * @param userId the ID that's being called + * @return Ok with user unless the one calling it isn't an Admin + */ + @GetMapping("/{userId}") + public ResponseEntity getUserById(@PathVariable Long userId){ + UserResponseDTO user = userService.getUserById(userId); + return ResponseEntity.ok(user); + } + + /** + * Call to delete one user via ID + * @param userId the ID that's being called + * @return noContent unless the one calling it isn't an Admin + */ + @DeleteMapping("/{userId}") + public ResponseEntity deleteUser(@PathVariable Long userId){ + userService.deleteUser(userId); + return ResponseEntity.noContent().build(); + } + + /** + * Call to patch one user via ID and role + * @param userId the ID of the user being called + * @param request the role that it's being changed to + * @return Ok with user unless the one calling it isn't an Admin + */ + @PatchMapping("/{userId}") + public ResponseEntity patchUser(@PathVariable Long userId, @Valid @RequestBody UserRoleUpdateRequest request){ + UserResponseDTO updatedUser = userService.patchUser(userId, request.role()); + return ResponseEntity.ok(updatedUser); + } + + /** + * Call to current logged in user + * @param principal the current user + * @return Ok with user unless the one calling it isn't the current user + */ + @GetMapping("/me") + public ResponseEntity getCurrentUser(Principal principal){ + UserResponseDTO user = userService.getUserByEmail(principal.getName()); + return ResponseEntity.ok(user); + } + + /** + * Call to delete current logged in user + * @param principal the current user + * @return noContent unless the one calling it isn't the current user + */ + @DeleteMapping("/me") + public ResponseEntity deleteCurrentUser(Principal principal){ + UserResponseDTO user = userService.getUserByEmail(principal.getName()); + userService.deleteUser(user.id()); + return ResponseEntity.noContent().build(); + } +} diff --git a/api/src/main/java/edu/csumb/cst438/api/entity/User.java b/api/src/main/java/edu/csumb/cst438/api/entity/User.java index b7a91d5..5e38fdd 100644 --- a/api/src/main/java/edu/csumb/cst438/api/entity/User.java +++ b/api/src/main/java/edu/csumb/cst438/api/entity/User.java @@ -1,6 +1,9 @@ package edu.csumb.cst438.api.entity; import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import java.util.*; @@ -56,6 +59,15 @@ public User(String email, String displayName, String role) { this.role = role; } + /** + * Updates role + * Not 110% sure if there's a better way to do this... + * @param role USER / ADMIN + */ + public void changeRole(String role){ + this.role = role; + } + /** * Adds a recipe to the collection and synchronizes the user's recipe collection * diff --git a/api/src/main/java/edu/csumb/cst438/api/errorHandling/GlobalExceptionHandler.java b/api/src/main/java/edu/csumb/cst438/api/errorHandling/GlobalExceptionHandler.java new file mode 100644 index 0000000..b0c05b7 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/errorHandling/GlobalExceptionHandler.java @@ -0,0 +1,133 @@ +package edu.csumb.cst438.api.errorHandling; + +import jakarta.persistence.EntityNotFoundException; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.*; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.net.URI; +import java.util.stream.Collectors; + +/** + * Exception handler class + */ +@RestControllerAdvice +public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + /** + * Handles authentication exception + * @param ex exception + * @param request request + * @return problem + */ + @ExceptionHandler(AuthenticationException.class) + public ProblemDetail handleAuthentication(AuthenticationException ex, HttpServletRequest request) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail( + HttpStatus.UNAUTHORIZED, "Authentication is required to access this resource"); + problem.setTitle("Unauthorized"); + problem.setInstance(URI.create(request.getRequestURI())); + return problem; + } + + /** + * Handles access denied exception + * @param ex exception + * @param request request + * @return problem + */ + @ExceptionHandler(AccessDeniedException.class) + public ProblemDetail handleAccessDenied(AccessDeniedException ex, HttpServletRequest request) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail( + HttpStatus.FORBIDDEN, "You do not have permission to access this resource"); + problem.setTitle("Forbidden"); + problem.setInstance(URI.create(request.getRequestURI())); + return problem; + } + + /** + * Handles entity not found exception + * @param ex exception + * @param request request + * @return problem + */ + @ExceptionHandler(EntityNotFoundException.class) + public ProblemDetail handleEntityNotFound(EntityNotFoundException ex, HttpServletRequest request) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage()); + problem.setTitle("Not Found"); + problem.setInstance(URI.create(request.getRequestURI())); + return problem; + } + + /** + * Handles illegal argument exception + * @param ex exception + * @param request request + * @return problem + */ + @ExceptionHandler(IllegalArgumentException.class) + public ProblemDetail handleBadRequest(IllegalArgumentException ex, HttpServletRequest request) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage()); + problem.setTitle("Bad Request"); + problem.setInstance(URI.create(request.getRequestURI())); + return problem; + } + + /** + * Handles method argument not valid exception + * @param ex exception + * @param request request + * @return problem + */ + @Override + protected ResponseEntity handleMethodArgumentNotValid( + MethodArgumentNotValidException ex, HttpHeaders headers, + HttpStatusCode status, WebRequest request) { + String detail = ex.getBindingResult().getFieldErrors().stream() + .map(e -> e.getField() + ": " + e.getDefaultMessage()) + .collect(Collectors.joining("; ")); + ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, detail); + problem.setTitle("Bad Request"); + return handleExceptionInternal(ex, problem, headers, HttpStatus.BAD_REQUEST, request); + } + + /** + * Handles http message not readable exception + * @param ex exception + * @param request request + * @return problem + */ + @Override + protected ResponseEntity handleHttpMessageNotReadable( + HttpMessageNotReadableException ex, HttpHeaders headers, + HttpStatusCode status, WebRequest request) { + ProblemDetail problem = ProblemDetail.forStatusAndDetail( + HttpStatus.BAD_REQUEST, "Request body is missing or malformed"); + problem.setTitle("Bad Request"); + return handleExceptionInternal(ex, problem, headers, HttpStatus.BAD_REQUEST, request); + } + + /** + * Handles unexpected stuff + * @param ex exception + * @param request request + * @return problem + */ + @ExceptionHandler(Exception.class) + public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) { + log.error("Unhandled exception on {}", request.getRequestURI(), ex); + ProblemDetail problem = ProblemDetail.forStatusAndDetail( + HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred"); + problem.setTitle("Internal Server Error"); + problem.setInstance(URI.create(request.getRequestURI())); + return problem; + } +} diff --git a/api/src/main/java/edu/csumb/cst438/api/record/UserResponseDTO.java b/api/src/main/java/edu/csumb/cst438/api/record/UserResponseDTO.java new file mode 100644 index 0000000..3b070b5 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/UserResponseDTO.java @@ -0,0 +1,8 @@ +package edu.csumb.cst438.api.record; + +public record UserResponseDTO( + Long id, + String email, + String displayName, + String role +) {} diff --git a/api/src/main/java/edu/csumb/cst438/api/record/UserRoleUpdateRequest.java b/api/src/main/java/edu/csumb/cst438/api/record/UserRoleUpdateRequest.java new file mode 100644 index 0000000..b384bd5 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/UserRoleUpdateRequest.java @@ -0,0 +1,14 @@ +package edu.csumb.cst438.api.record; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + +/** + * For updating the user role in PATCH + * @param role user role + */ +public record UserRoleUpdateRequest( + @NotNull(message = "role is required") + @Pattern(regexp = "USER|ADMIN", message = "role must be USER or ADMIN") + String role) { +} diff --git a/api/src/main/java/edu/csumb/cst438/api/repository/UserRepository.java b/api/src/main/java/edu/csumb/cst438/api/repository/UserRepository.java new file mode 100644 index 0000000..1520366 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/repository/UserRepository.java @@ -0,0 +1,31 @@ +package edu.csumb.cst438.api.repository; + +import edu.csumb.cst438.api.entity.User; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; +import java.util.Optional; + +/** + * Interface class for the database stuff for User + */ +public interface UserRepository extends JpaRepository { + /** + * Interface to return a user by display name + * @param name the display name + * @return the user connected to the display name + */ + Optional findByDisplayName(String name); + + /** + * Interface to return a page of users + * @param pageable pageable with page number and size + * @return a list of users + */ + @Query("SELECT u FROM User u") + List findUsersInPage(Pageable pageable); + + Optional findByEmail(String email); +} diff --git a/api/src/main/java/edu/csumb/cst438/api/service/UserService.java b/api/src/main/java/edu/csumb/cst438/api/service/UserService.java new file mode 100644 index 0000000..fd2cfc8 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/service/UserService.java @@ -0,0 +1,111 @@ +package edu.csumb.cst438.api.service; + +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.UserResponseDTO; +import edu.csumb.cst438.api.repository.UserRepository; +import jakarta.persistence.EntityNotFoundException; +import jakarta.transaction.Transactional; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +/** + * Methods that are ran in the controller, does a lot of the work. + */ +@Service +public class UserService { + private final UserRepository userRepository; + + /** + * Constructor for UserService + * @param userRepository the repository class + */ + public UserService(UserRepository userRepository){ + this.userRepository = userRepository; + } + + /** + * Gets user by email for future oauth stuff + * @param email user email + * @return the user + */ + public UserResponseDTO getUserByEmail(String email){ + User user = userRepository.findByEmail(email) + .orElseThrow(() -> new EntityNotFoundException("No user found for the authenticated account")); + return new UserResponseDTO( + user.getId(), + user.getEmail(), + user.getDisplayName(), + user.getRole() + ); + } + + /** + * Gives a list of all the users by page + * @param page an int of page (starts at 0) + * @param size an int of size (default is 20) + * @return a list of users + * @throws IllegalArgumentException if page index is < 0 + */ + public Page getAllUsers(int page, int size){ + if (page < 0) { + throw new IllegalArgumentException("Page index must be 0 or greater"); + } + if (size < 1 || size > 100){ + throw new IllegalArgumentException("Page size must be between 1 and 100"); + } + return userRepository.findAll(PageRequest.of(page, size)) + .map(user -> new UserResponseDTO( + user.getId(), + user.getEmail(), + user.getDisplayName(), + user.getRole() + )); + } + + /** + * Gives a user by ID + * @param id the user ID + * @return the user + */ + public UserResponseDTO getUserById(Long id){ + User user = userRepository.findById(id) + .orElseThrow(() -> + new EntityNotFoundException("No user found with id " + id)); + return new UserResponseDTO( + user.getId(), + user.getEmail(), + user.getDisplayName(), + user.getRole() + ); + } + + /** + * Deletes a user by ID + * @param id the user ID + */ + public void deleteUser(Long id){ + userRepository.findById(id) + .orElseThrow(() -> new EntityNotFoundException("No user found with id " + id)); + userRepository.deleteById(id); + } + + /** + * Grants or revokes admin + * @param id the user ID + * @param role the role (USER/ADMIN) + * @return the updated user + */ + @Transactional + public UserResponseDTO patchUser(Long id, String role){ + User user = userRepository.findById(id) + .orElseThrow(() -> new EntityNotFoundException("No user found with id " + id)); + user.changeRole(role); + return new UserResponseDTO( + user.getId(), + user.getEmail(), + user.getDisplayName(), + user.getRole() + ); + } +} diff --git a/api/src/main/resources/application.yaml b/api/src/main/resources/application.yaml index 2b9df7e..d46cca5 100644 --- a/api/src/main/resources/application.yaml +++ b/api/src/main/resources/application.yaml @@ -18,4 +18,8 @@ spring: properties: hibernate: default_batch_fetch_size: 100 - show-sql: true \ No newline at end of file + show-sql: true + data: + web: + pageable: + serialization-mode: via_dto \ No newline at end of file diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java index 77f1f90..49c9ce9 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java @@ -6,10 +6,12 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; @@ -31,6 +33,7 @@ // TODO(#48): once Spring Security is on the classpath, use @WithMockUser("owner@example.com") // instead of .principal(...) and add a "no credentials -> 401 problem+json" test. @WebMvcTest(MealPlanController.class) +@Import(SecurityConfig.class) @ActiveProfiles("test") public class MealPlanControllerTest { private static final String EMAIL = "owner@example.com"; @@ -44,15 +47,16 @@ public class MealPlanControllerTest { private MealPlanService mealPlanService; private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { - return request.principal(USER).contentType(MediaType.APPLICATION_JSON).content(body); + return request.contentType(MediaType.APPLICATION_JSON).content(body); } @Test + @WithMockUser("owner@example.com") void listReturnsPageShape() throws Exception { when(mealPlanService.list(EMAIL, 0, 20)).thenReturn( new PageImpl<>(List.of(new MealPlanResponse(67L, WEEK, List.of())), PageRequest.of(0, 20), 1)); - mvc.perform(get("/api/v1/meal-plans").principal(USER)) + mvc.perform(get("/api/v1/meal-plans")) .andExpect(status().isOk()) .andExpect(jsonPath("$.content[0].id").value(67)) .andExpect(jsonPath("$.content[0].weekStart").value("2026-10-05")) @@ -64,18 +68,20 @@ void listReturnsPageShape() throws Exception { } @Test + @WithMockUser("owner@example.com") void listRejectsBadPaging() throws Exception { - mvc.perform(get("/api/v1/meal-plans?size=101").principal(USER)) + mvc.perform(get("/api/v1/meal-plans?size=101")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)); - mvc.perform(get("/api/v1/meal-plans?page=-1").principal(USER)) + mvc.perform(get("/api/v1/meal-plans?page=-1")) .andExpect(status().isBadRequest()); - mvc.perform(get("/api/v1/meal-plans?size=0").principal(USER)) + mvc.perform(get("/api/v1/meal-plans?size=0")) .andExpect(status().isBadRequest()); verifyNoInteractions(mealPlanService); } @Test + @WithMockUser("owner@example.com") void createReturns201WithLocation() throws Exception { when(mealPlanService.create(EMAIL, WEEK)).thenReturn(new MealPlanResponse(67L, WEEK, List.of())); @@ -86,6 +92,7 @@ void createReturns201WithLocation() throws Exception { } @Test + @WithMockUser("owner@example.com") void createRejectsMissingOrInvalidDate() throws Exception { mvc.perform(json(post("/api/v1/meal-plans"), "{}")) .andExpect(status().isBadRequest()) @@ -96,6 +103,7 @@ void createRejectsMissingOrInvalidDate() throws Exception { } @Test + @WithMockUser("owner@example.com") void updateChangesWeek() throws Exception { LocalDate next = LocalDate.of(2026, 10, 12); when(mealPlanService.update(EMAIL, 67L, next)).thenReturn(new MealPlanResponse(67L, next, List.of())); @@ -106,6 +114,7 @@ void updateChangesWeek() throws Exception { } @Test + @WithMockUser("owner@example.com") void updateRejectsEmptyOrInvalidBody() throws Exception { mvc.perform(json(patch("/api/v1/meal-plans/67"), "{}")) .andExpect(status().isBadRequest()); @@ -115,19 +124,21 @@ void updateRejectsEmptyOrInvalidBody() throws Exception { } @Test + @WithMockUser("owner@example.com") void deleteReturns204() throws Exception { - mvc.perform(delete("/api/v1/meal-plans/67").principal(USER)) + mvc.perform(delete("/api/v1/meal-plans/67")) .andExpect(status().isNoContent()) .andExpect(content().string("")); verify(mealPlanService).delete(EMAIL, 67L); } @Test + @WithMockUser("owner@example.com") void notFoundIsProblemDetails() throws Exception { when(mealPlanService.get(eq(EMAIL), any())).thenThrow( new ResponseStatusException(HttpStatus.NOT_FOUND, "Meal plan 99 not found")); - mvc.perform(get("/api/v1/meal-plans/99").principal(USER)) + mvc.perform(get("/api/v1/meal-plans/99")) .andExpect(status().isNotFound()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.status").value(404)) diff --git a/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java new file mode 100644 index 0000000..a6f1102 --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java @@ -0,0 +1,265 @@ +package edu.csumb.cst438.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import edu.csumb.cst438.api.controller.UserController; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.UserResponseDTO; +import edu.csumb.cst438.api.service.UserService; +import jakarta.persistence.EntityNotFoundException; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.data.domain.PageImpl; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +/** + * Tests the UserController.java API routes + * As well as tests what ADMIN/USER can and can't access + * Disclaimer: some of these tests were assisted with AI + */ +@WebMvcTest(UserController.class) +@Import(SecurityConfig.class) +@ActiveProfiles("test") +public class UserControllerTest { + @Autowired + private MockMvc mockMvc; + + @MockitoBean + private UserService userService; + + /** + * Tests if GET /api/v1/users works with ADMIN role + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "ADMIN") + void testGETUsersWAdmin() throws Exception{ + UserResponseDTO mockUser = new UserResponseDTO(1L, "email@gmail.com", "newName", "USER"); + when(userService.getAllUsers(0, 20)).thenReturn(new PageImpl<>(List.of(mockUser))); + mockMvc.perform(get("/api/v1/users")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content[0].email").value("email@gmail.com")) + .andExpect(jsonPath("$.page.totalElements").value(1)) + .andExpect(jsonPath("$.page.number").value(0)); + } + + /** + * Tests if GET /api/v1/users/{userId} works with ADMIN role + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "ADMIN") + void testGETUserIdWAdmin() throws Exception{ + UserResponseDTO mockUser = new UserResponseDTO(1L, "email@gmail.com", "newName", "USER"); + when(userService.getUserById(1L)).thenReturn(mockUser); + mockMvc.perform(get("/api/v1/users/1")) + .andExpect(status().isOk()); + } + + /** + * Tests if PATCH /api/v1/users/{userId} works with ADMIN role + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "ADMIN") + void testPATCHUserWAdmin() throws Exception{ + when(userService.patchUser(1L, "ADMIN")).thenReturn(new UserResponseDTO(1L, "email@gmail.com", "newName", "ADMIN")); + + mockMvc.perform(patch("/api/v1/users/1") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"role\":\"ADMIN\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.role").value("ADMIN")); + } + + /** + * Tests PATCH if the user don't exist + * @throws Exception if there's an exception + */ + @Test + @WithMockUser(roles = "ADMIN") + void testPATCHNonExistentUser() throws Exception{ + when(userService.patchUser(999L, "ADMIN")) + .thenThrow(new EntityNotFoundException("No user found with id 999")); + mockMvc.perform(patch("/api/v1/users/999") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"role\":\"ADMIN\"}")) + .andExpect(status().isNotFound()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.title").value("Not Found")) + .andExpect(jsonPath("$.status").value(404)) + .andExpect(jsonPath("$.detail").value("No user found with id 999")) + .andExpect(jsonPath("$.instance").value("/api/v1/users/999")); + } + + /** + * Tests PATCH user with an invalid role input + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "ADMIN") + void testPATCHUserInvalidRole() throws Exception{ + mockMvc.perform(patch("/api/v1/users/1") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"role\":\"ADMN\"}")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.title").value("Bad Request")) + .andExpect(jsonPath("$.status").value(400)) + .andExpect(jsonPath("$.detail").value(org.hamcrest.Matchers.containsString("role"))); + + verify(userService, never()).patchUser(any(), any()); + } + + /** + * Tests if PATCh works with a missing role input + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "ADMIN") + void testPATCHUserMissingRole() throws Exception{ + mockMvc.perform(patch("/api/v1/users/1") + .contentType(MediaType.APPLICATION_JSON) + .content("{}")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.status").value(400)); + + verify(userService, never()).patchUser(any(), any()); + } + + /** + * Tests if GET users works when you're not authenticated + * @throws Exception if there is an exception + */ + @Test + void testGETUsersUnauthenticated() throws Exception{ + mockMvc.perform(get("/api/v1/users")) + .andExpect(status().isUnauthorized()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(header().exists("WWW-Authenticate")) + .andExpect(jsonPath("$.title").value("Unauthorized")) + .andExpect(jsonPath("$.status").value(401)) + .andExpect(jsonPath("$.instance").value("/api/v1/users")); + } + + /** + * Tests if GET users works if a user does it + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "USER") + void testGETUsersWUserProblemDetails() throws Exception{ + mockMvc.perform(get("/api/v1/users")) + .andExpect(status().isForbidden()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.title").value("Forbidden")) + .andExpect(jsonPath("$.status").value(403)) + .andExpect(jsonPath("$.instance").value("/api/v1/users")); + } + + /** + * Tests if DELETE /api/v1/users/{userId} works with ADMIN role + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "ADMIN") + void testDELETEUserIdWAdmin() throws Exception{ + UserResponseDTO mockUser = new UserResponseDTO(1L, "email@gmail.com", "newName", "USER"); + when(userService.getUserById(1L)).thenReturn(mockUser); + mockMvc.perform(delete("/api/v1/users/1")) + .andExpect(status().isNoContent()); + verify(userService).deleteUser(1L); + } + + + /** + * Tests if GET /api/v1/users is successfully forbidden from USER role + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "USER") + void testGETUsersWUser() throws Exception{ + mockMvc.perform(get("/api/v1/users")) + .andExpect(status().isForbidden()); + } + + /** + * Tests if GET /api/v1/users/{userId} is successfully forbidden from USER role + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "USER") + void testGETUserIdWUser() throws Exception{ + UserResponseDTO mockUser = new UserResponseDTO(1L, "email@gmail.com", "newName", "USER"); + when(userService.getUserById(1L)).thenReturn(mockUser); + mockMvc.perform(get("/api/v1/users/1")) + .andExpect(status().isForbidden()); + } + + /** + * Tests if PATCH /api/v1/users/{userId} is successfully forbidden from USER role + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "USER") + void testPATCHUserWUser() throws Exception{ + mockMvc.perform(patch("/api/v1/users/1") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"role\":\"ADMIN\"}")) + .andExpect(status().isForbidden()); + verifyNoInteractions(userService); + } + + /** + * Tests if DELETE /api/v1/users/{userId} is successfully forbidden from USER role + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(roles = "USER") + void testDELETEUserIdWUser() throws Exception{ + UserResponseDTO mockUser = new UserResponseDTO(1L, "email@gmail.com", "newName", "USER"); + when(userService.getUserById(1L)).thenReturn(mockUser); + mockMvc.perform(delete("/api/v1/users/1")) + .andExpect(status().isForbidden()); + } + + /** + * Tests if GET api/v1/users/me is accessible from USER and returns the correct USER + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(username = "email@gmail.com", roles = "USER") + void testGETLoggedInUser() throws Exception{ + when(userService.getUserByEmail("email@gmail.com")).thenReturn(new UserResponseDTO(1L, "email@gmail.com", "user", "USER")); + mockMvc.perform(get("/api/v1/users/me")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.email").value("email@gmail.com")); + } + + /** + * Tests if DELETE api/v1/users/me is accessible from USER and returns the correct USER + * @throws Exception if there is an exception + */ + @Test + @WithMockUser(username = "email@gmail.com", roles = "USER") + void testDELETELoggedInUser() throws Exception{ + User mockUser = mock(User.class); + when(mockUser.getId()).thenReturn(1L); + when(userService.getUserByEmail("email@gmail.com")).thenReturn(new UserResponseDTO(1L, "email@gmail.com", "user", "USER")); + mockMvc.perform(delete("/api/v1/users/me")) + .andExpect(status().isNoContent()); + verify(userService).deleteUser(1L); + } +} diff --git a/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java new file mode 100644 index 0000000..aaa74f0 --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java @@ -0,0 +1,196 @@ +package edu.csumb.cst438.api; + +import edu.csumb.cst438.api.entity.Recipe; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.UserResponseDTO; +import edu.csumb.cst438.api.repository.UserRepository; +import edu.csumb.cst438.api.service.UserService; +import jakarta.persistence.EntityNotFoundException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verifyNoInteractions; + +/** + * Tests methods in UserService class + * Disclaimer: also assisted by AI + */ +@ExtendWith(MockitoExtension.class) +public class UserServiceTest { + @Mock + private UserRepository userRepository; + + @InjectMocks + private UserService userService; + + /** + * Tests getUserByName + */ + @Test + void testGetUserByUsername(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + Mockito.when(userRepository.findByEmail("email@gmail.com")).thenReturn(Optional.of(mockUser)); + + UserResponseDTO result = userService.getUserByEmail("email@gmail.com"); + assertNotNull(result); + assertEquals("newUser", result.displayName()); + assertEquals("email@gmail.com", result.email()); + Mockito.verify(userRepository, Mockito.times(1)).findByEmail("email@gmail.com"); + } + + /** + * Tests getAllUsers + */ + @Test + void testGetAllUsers(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + User mockUser2 = new User("gmail@gmail.com", "newerUser", "USER"); + Page page = new PageImpl<>(List.of(mockUser, mockUser2)); + Mockito.when(userRepository.findAll(PageRequest.of(0, 2))).thenReturn(page); + + Page result = userService.getAllUsers(0, 2); + + assertEquals(2, result.getTotalElements()); + assertEquals("email@gmail.com", result.getContent().get(0).email()); + assertEquals("gmail@gmail.com", result.getContent().get(1).email()); + Mockito.verify(userRepository, Mockito.times(1)).findAll(PageRequest.of(0, 2)); + } + + /** + * Tests getAllUsers with negative page + */ + @Test + void testgetAllUsersWNeg() { + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> userService.getAllUsers(-1, 20)); + + assertEquals("Page index must be 0 or greater", ex.getMessage()); + verifyNoInteractions(userRepository); + } + + /** + * Tests getAllUsers with negative size + */ + @Test + void testgetAllUsersWNegSize() { + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> userService.getAllUsers(0, -1)); + + assertEquals("Page size must be between 1 and 100", ex.getMessage()); + verifyNoInteractions(userRepository); + } + + /** + * Tests getAllUsers with size over 100 + */ + @Test + void testgetAllUsersWBigSize() { + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> userService.getAllUsers(0, 101)); + + assertEquals("Page size must be between 1 and 100", ex.getMessage()); + verifyNoInteractions(userRepository); + } + + /** + * Tests getUserById + */ + @Test + void testGetUserById(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser)); + + UserResponseDTO result = userService.getUserById(1L); + assertNotNull(result); + assertEquals("newUser", result.displayName()); + assertEquals("email@gmail.com", result.email()); + Mockito.verify(userRepository, Mockito.times(1)).findById(1L); + } + + /** + * Tests getUserById when the Id does not exist + */ + @Test + void testGetUserByIdNonEx(){ + Mockito.when(userRepository.findById(999L)).thenReturn(Optional.empty()); + + assertThrows(EntityNotFoundException.class, () -> userService.getUserById(999L)); + Mockito.verify(userRepository, Mockito.never()).save(any()); + } + + /** + * Tests getUserById when the user has a recipe + */ + @Test + void testGetUserByIdWithStuff(){ + User user = new User("email@gmail.com", "newUser", "USER"); + Recipe recipe = new Recipe("food", "1 food", user); + user.getRecipes().add(recipe); + Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(user)); + + UserResponseDTO result = userService.getUserById(1L); + assertEquals("email@gmail.com", result.email()); + assertEquals("USER", result.role()); + } + + /** + * Tests deleteUser + */ + @Test + void testDeleteUserById(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser)); + userService.deleteUser(1L); + Mockito.verify(userRepository, Mockito.times(1)).deleteById(1L); + } + + /** + * Tests patchUser + */ + @Test + void testPatchUser(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser)); + + UserResponseDTO result = userService.patchUser(1L, "ADMIN"); + + assertEquals("ADMIN", result.role()); + assertEquals("email@gmail.com", result.email()); + assertEquals("newUser", result.displayName()); + } + + /** + * Tests patch user when user isn't found + */ + @Test + void testPatchUserNotFound(){ + Mockito.when(userRepository.findById(999L)).thenReturn(Optional.empty()); + + assertThrows(EntityNotFoundException.class, () -> userService.patchUser(999L, "ADMIN")); + Mockito.verify(userRepository, Mockito.never()).save(any()); + } + + /** + * Tests get user when email isn't found + */ + @Test + void testGetUserByEmailNotFound(){ + Mockito.when(userRepository.findByEmail("no@gmail.com")).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> userService.getUserByEmail("no@gmail.com")); + } +}