From 11df304487d95ebedc479c3da381ddfb82642a52 Mon Sep 17 00:00:00 2001 From: annabelle-baltes Date: Tue, 13 Oct 2026 20:04:59 -0700 Subject: [PATCH 1/5] Implemented User GET, PATCH, DELETE API routes --- api/build.gradle | 3 + .../edu/csumb/cst438/api/SecurityConfig.java | 47 +++++ .../cst438/api/controller/UserController.java | 100 ++++++++++ .../edu/csumb/cst438/api/entity/User.java | 12 ++ .../api/record/UserRoleUpdateRequest.java | 8 + .../cst438/api/repository/UserRepository.java | 29 +++ .../csumb/cst438/api/service/UserService.java | 101 ++++++++++ .../csumb/cst438/api/UserControllerTest.java | 173 ++++++++++++++++++ .../edu/csumb/cst438/api/UserServiceTest.java | 135 ++++++++++++++ 9 files changed, 608 insertions(+) create mode 100644 api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java create mode 100644 api/src/main/java/edu/csumb/cst438/api/controller/UserController.java create mode 100644 api/src/main/java/edu/csumb/cst438/api/record/UserRoleUpdateRequest.java create mode 100644 api/src/main/java/edu/csumb/cst438/api/repository/UserRepository.java create mode 100644 api/src/main/java/edu/csumb/cst438/api/service/UserService.java create mode 100644 api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java create mode 100644 api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java diff --git a/api/build.gradle b/api/build.gradle index 55edbfb..1843c51 100644 --- a/api/build.gradle +++ b/api/build.gradle @@ -30,12 +30,15 @@ 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' runtimeOnly 'com.h2database:h2' runtimeOnly 'org.postgresql:postgresql' testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test' 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..f486a34 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java @@ -0,0 +1,47 @@ +package edu.csumb.cst438.api; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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.SecurityFilterChain; + +/** + * 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) throws Exception{ + http + .csrf(csrf -> csrf.disable()) + .headers(headers -> + headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) + .authorizeHttpRequests(auth -> auth + .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() + ) + .httpBasic(Customizer.withDefaults()); + 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..8c1ff84 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java @@ -0,0 +1,100 @@ +package edu.csumb.cst438.api.controller; + +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.UserRoleUpdateRequest; +import edu.csumb.cst438.api.service.UserService; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.security.Principal; +import java.util.List; +import java.util.Optional; + +/** + * 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) + * @return Ok with users unless the one calling it isn't an Admin + */ + @GetMapping + public ResponseEntity> getAllUsers(@RequestParam(defaultValue = "0") int page){ + List users = userService.getAllUsers(page); + return ResponseEntity.ok(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){ + Optional user = userService.getUserById(userId); + return user.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + } + + /** + * 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, @RequestBody UserRoleUpdateRequest request){ + User 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){ + String name = principal.getName(); + User user = userService.getUserByName(name); + 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){ + String name = principal.getName(); + User user = userService.getUserByName(name); + userService.deleteUser(user.getId()); + 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/record/UserRoleUpdateRequest.java b/api/src/main/java/edu/csumb/cst438/api/record/UserRoleUpdateRequest.java new file mode 100644 index 0000000..d0872ae --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/UserRoleUpdateRequest.java @@ -0,0 +1,8 @@ +package edu.csumb.cst438.api.record; + +/** + * For updating the user role in PATCH + * @param role user role + */ +public record UserRoleUpdateRequest(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..87d051d --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/repository/UserRepository.java @@ -0,0 +1,29 @@ +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); +} 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..ef78367 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/service/UserService.java @@ -0,0 +1,101 @@ +package edu.csumb.cst438.api.service; + +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.repository.UserRepository; +import jakarta.persistence.EntityNotFoundException; +import jakarta.transaction.Transactional; +import org.jspecify.annotations.NonNull; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +/** + * Methods that are ran in the controller, does a lot of the work. + */ +@Service +public class UserService implements UserDetailsService { + private final UserRepository userRepository; + + /** + * Constructor for UserService + * @param userRepository the repository class + */ + public UserService(UserRepository userRepository){ + this.userRepository = userRepository; + } + + /** + * Should allow spring security to authenticate users based on our database + * @param username user display name + * @return user details + * @throws UsernameNotFoundException if user not found + */ + @Override + public UserDetails loadUserByUsername(@NonNull String username) throws UsernameNotFoundException{ + User user = userRepository.findByDisplayName(username) + .orElseThrow(() -> new UsernameNotFoundException("No user named " + username)); + return org.springframework.security.core.userdetails.User + .withUsername(user.getDisplayName()) + .password(user.getEmail()) + .roles(user.getRole()) + .build(); + } + + /** + * Gives a list of all the users by page + * @param page an int of page (starts at 0) + * @return a list of users + */ + public List getAllUsers(int page){ + int size = 20; + Pageable pageable = PageRequest.of(page, size); + return userRepository.findUsersInPage(pageable); + } + + /** + * Gives a user by ID + * @param id the user ID + * @return the user + */ + public Optional getUserById(Long id){ + return userRepository.findById(id); + } + + /** + * Deletes a user by ID + * @param id the user ID + */ + public void deleteUser(Long 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 User patchUser(Long id, String role){ + User user = userRepository.findById(id) + .orElseThrow(() -> new EntityNotFoundException("No user found with id " + id)); + user.changeRole(role); + return userRepository.save(user); + } + + /** + * Gets user by display name + * @param name the display name + * @return the user + */ + public User getUserByName(String name){ + return userRepository.findByDisplayName(name) + .orElseThrow(() -> new EntityNotFoundException("No user named " + name)); + } +} 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..b8ba190 --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java @@ -0,0 +1,173 @@ +package edu.csumb.cst438.api; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import edu.csumb.cst438.api.controller.UserController; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.service.UserService; +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.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.Optional; + +/** + * 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{ + mockMvc.perform(get("/api/v1/users")) + .andExpect(status().isOk()); + } + + /** + * 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{ + User mockUser = new User("email@gmail.com", "newName", "USER"); + when(userService.getUserById(1L)).thenReturn(Optional.of(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{ + User mockUser = new User("email@gmail.com", "newName", "ADMIN"); + when(userService.patchUser(1L, "ADMIN")).thenReturn(mockUser); + + mockMvc.perform(patch("/api/v1/users/1") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"role\":\"ADMIN\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.role").value("ADMIN")); + } + + /** + * 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{ + User mockUser = new User("email@gmail.com", "newName", "USER"); + when(userService.getUserById(1L)).thenReturn(Optional.of(mockUser)); + mockMvc.perform(delete("/api/v1/users/1")) + .andExpect(status().isNoContent()); + } + + + /** + * 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{ + User mockUser = new User("email@gmail.com", "newName", "USER"); + 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{ + User mockUser = new User("email@gmail.com", "newName", "USER"); + when(userService.getUserById(1L)).thenReturn(Optional.of(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{ + User mockUser = new User("email@gmail.com", "newName", "ADMIN"); + when(userService.patchUser(1L, "ADMIN")).thenReturn(mockUser); + + mockMvc.perform(patch("/api/v1/users/1") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"role\":\"ADMIN\"}")) + .andExpect(status().isForbidden()); + } + + /** + * 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{ + User mockUser = new User("email@gmail.com", "newName", "USER"); + when(userService.getUserById(1L)).thenReturn(Optional.of(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(roles = "USER") + void testGETLoggedInUser() throws Exception{ + User mockUser = new User("email@gmail.com", "user", "USER"); + when(userService.getUserByName("user")).thenReturn(mockUser); + 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(roles = "USER") + void testDELETELoggedInUser() throws Exception{ + User mockUser = new User("email@gmail.com", "user", "USER"); + when(userService.getUserByName("user")).thenReturn(mockUser); + mockMvc.perform(delete("/api/v1/users/me")) + .andExpect(status().isNoContent()); + } +} 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..60446d8 --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java @@ -0,0 +1,135 @@ +package edu.csumb.cst438.api; + +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.repository.UserRepository; +import edu.csumb.cst438.api.service.UserService; +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.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * 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.findByDisplayName("newUser")).thenReturn(Optional.of(mockUser)); + + User result = userService.getUserByName("newUser"); + assertNotNull(result); + assertEquals("newUser", result.getDisplayName()); + assertEquals("email@gmail.com", result.getEmail()); + Mockito.verify(userRepository, Mockito.times(1)).findByDisplayName("newUser"); + } + + /** + * Tests getAllUsers + */ + @Test + void testGetAllUsers(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + User mockUser2 = new User("gmail@gmail.com", "newerUser", "USER"); + Mockito.when(userRepository.findUsersInPage(PageRequest.of(0, 20))).thenReturn(List.of(mockUser, mockUser2)); + + List result = userService.getAllUsers(0); + assertNotNull(result); + assertTrue(result.contains(mockUser)); + assertTrue(result.contains(mockUser2)); + Mockito.verify(userRepository, Mockito.times(1)).findUsersInPage(PageRequest.of(0, 20)); + } + + /** + * Tests getUserById + */ + @Test + void testGetUserById(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser)); + + Optional result = userService.getUserById(1L); + assertNotNull(result); + assertEquals("newUser", result.get().getDisplayName()); + assertEquals("email@gmail.com", result.get().getEmail()); + Mockito.verify(userRepository, Mockito.times(1)).findById(1L); + } + + /** + * Tests deleteUser + */ + @Test + void testDeleteUserById(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + + 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)); + + mockUser = userService.patchUser(1L, "ADMIN"); + Optional result = userService.getUserById(1L); + assertNotNull(result); + assertEquals("newUser", result.get().getDisplayName()); + assertEquals("ADMIN", result.get().getRole()); + } + + /** + * Tests LoadUserByUsername + */ + @Test + void testLoadUserByUsername(){ + User mockUser = new User("email@gmail.com", "newUser", "USER"); + Mockito.when(userRepository.findByDisplayName("newUser")).thenReturn(Optional.of(mockUser)); + + UserDetails details = userService.loadUserByUsername("newUser"); + + assertEquals("newUser", details.getUsername()); + assertEquals("email@gmail.com", details.getPassword()); + assertTrue(details.getAuthorities().stream() + .anyMatch(a -> a.getAuthority().equals("ROLE_USER"))); + } + + /** + * Tests LoadUserByUsername to make sure that the ADMIN role is ADMIN authority + */ + @Test + void testLoadUserByUsernameMapsAdmin(){ + User mockUser = new User("email@gmail.com", "newAdmin", "ADMIN"); + Mockito.when(userRepository.findByDisplayName("newAdmin")).thenReturn(Optional.of(mockUser)); + + UserDetails details = userService.loadUserByUsername("newAdmin"); + + assertTrue(details.getAuthorities().stream() + .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))); + } +} From bc3d95304970303805c589c6245d6e38a8c86d65 Mon Sep 17 00:00:00 2001 From: annabelle-baltes Date: Wed, 14 Oct 2026 23:24:56 -0700 Subject: [PATCH 2/5] Changes have been made So sorry for the wait :( --- .../edu/csumb/cst438/api/SecurityConfig.java | 20 ++- .../cst438/api/controller/UserController.java | 24 ++-- .../errorHandling/GlobalExceptionHandler.java | 133 ++++++++++++++++++ .../cst438/api/record/UserResponseDTO.java | 8 ++ .../api/record/UserRoleUpdateRequest.java | 8 +- .../cst438/api/repository/UserRepository.java | 2 + .../csumb/cst438/api/service/UserService.java | 53 +++---- api/src/main/resources/application.yaml | 6 +- .../csumb/cst438/api/UserControllerTest.java | 133 +++++++++++++++--- .../edu/csumb/cst438/api/UserServiceTest.java | 85 +++++++---- 10 files changed, 379 insertions(+), 93 deletions(-) create mode 100644 api/src/main/java/edu/csumb/cst438/api/errorHandling/GlobalExceptionHandler.java create mode 100644 api/src/main/java/edu/csumb/cst438/api/record/UserResponseDTO.java diff --git a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java index f486a34..559876e 100644 --- a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java +++ b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java @@ -1,14 +1,19 @@ 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 @@ -27,7 +32,16 @@ public class SecurityConfig { * @throws Exception if there's an exception */ @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{ + 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 -> @@ -41,7 +55,9 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .requestMatchers(HttpMethod.DELETE, "/api/v1/users/{userid}").hasRole("ADMIN") .anyRequest().authenticated() ) - .httpBasic(Customizer.withDefaults()); + .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 index 8c1ff84..ebf7b23 100644 --- a/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java +++ b/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java @@ -1,9 +1,13 @@ package edu.csumb.cst438.api.controller; import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.UserResponseDTO; import edu.csumb.cst438.api.record.UserRoleUpdateRequest; import edu.csumb.cst438.api.service.UserService; import jakarta.persistence.EntityNotFoundException; +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.*; @@ -34,9 +38,9 @@ public UserController(UserService userService){ * @return Ok with users unless the one calling it isn't an Admin */ @GetMapping - public ResponseEntity> getAllUsers(@RequestParam(defaultValue = "0") int page){ - List users = userService.getAllUsers(page); - return ResponseEntity.ok(users); + public ResponseEntity> getAllUsers(@RequestParam(defaultValue = "0") int page){ + Page users = userService.getAllUsers(page); + return ResponseEntity.ok(new PagedModel<>(users)); } /** @@ -45,9 +49,9 @@ public ResponseEntity> getAllUsers(@RequestParam(defaultValue = "0") * @return Ok with user unless the one calling it isn't an Admin */ @GetMapping("/{userId}") - public ResponseEntity getUserById(@PathVariable Long userId){ - Optional user = userService.getUserById(userId); - return user.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + public ResponseEntity getUserById(@PathVariable Long userId){ + UserResponseDTO user = userService.getUserById(userId); + return ResponseEntity.ok(user); } /** @@ -68,7 +72,7 @@ public ResponseEntity deleteUser(@PathVariable Long userId){ * @return Ok with user unless the one calling it isn't an Admin */ @PatchMapping("/{userId}") - public ResponseEntity patchUser(@PathVariable Long userId, @RequestBody UserRoleUpdateRequest request){ + public ResponseEntity patchUser(@PathVariable Long userId, @Valid @RequestBody UserRoleUpdateRequest request){ User updatedUser = userService.patchUser(userId, request.role()); return ResponseEntity.ok(updatedUser); } @@ -80,8 +84,7 @@ public ResponseEntity patchUser(@PathVariable Long userId, @RequestBody Us */ @GetMapping("/me") public ResponseEntity getCurrentUser(Principal principal){ - String name = principal.getName(); - User user = userService.getUserByName(name); + User user = userService.getUserByEmail(principal.getName()); return ResponseEntity.ok(user); } @@ -92,8 +95,7 @@ public ResponseEntity getCurrentUser(Principal principal){ */ @DeleteMapping("/me") public ResponseEntity deleteCurrentUser(Principal principal){ - String name = principal.getName(); - User user = userService.getUserByName(name); + User user = userService.getUserByEmail(principal.getName()); userService.deleteUser(user.getId()); return ResponseEntity.noContent().build(); } 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 index d0872ae..b384bd5 100644 --- a/api/src/main/java/edu/csumb/cst438/api/record/UserRoleUpdateRequest.java +++ b/api/src/main/java/edu/csumb/cst438/api/record/UserRoleUpdateRequest.java @@ -1,8 +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(String 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 index 87d051d..1520366 100644 --- a/api/src/main/java/edu/csumb/cst438/api/repository/UserRepository.java +++ b/api/src/main/java/edu/csumb/cst438/api/repository/UserRepository.java @@ -26,4 +26,6 @@ public interface UserRepository extends JpaRepository { */ @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 index ef78367..79fcd36 100644 --- a/api/src/main/java/edu/csumb/cst438/api/service/UserService.java +++ b/api/src/main/java/edu/csumb/cst438/api/service/UserService.java @@ -1,10 +1,12 @@ 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.jspecify.annotations.NonNull; +import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.security.core.userdetails.UserDetails; @@ -19,7 +21,7 @@ * Methods that are ran in the controller, does a lot of the work. */ @Service -public class UserService implements UserDetailsService { +public class UserService { private final UserRepository userRepository; /** @@ -31,31 +33,26 @@ public UserService(UserRepository userRepository){ } /** - * Should allow spring security to authenticate users based on our database - * @param username user display name - * @return user details - * @throws UsernameNotFoundException if user not found + * Gets user by email for future oauth stuff + * @param email user email + * @return the user */ - @Override - public UserDetails loadUserByUsername(@NonNull String username) throws UsernameNotFoundException{ - User user = userRepository.findByDisplayName(username) - .orElseThrow(() -> new UsernameNotFoundException("No user named " + username)); - return org.springframework.security.core.userdetails.User - .withUsername(user.getDisplayName()) - .password(user.getEmail()) - .roles(user.getRole()) - .build(); + public User getUserByEmail(String email){ + return userRepository.findByEmail(email) + .orElseThrow(() -> new EntityNotFoundException("No user found for the authenticated account")); } /** * Gives a list of all the users by page * @param page an int of page (starts at 0) * @return a list of users + * @throws IllegalArgumentException if page index isn't <= 0 */ - public List getAllUsers(int page){ - int size = 20; - Pageable pageable = PageRequest.of(page, size); - return userRepository.findUsersInPage(pageable); + public Page getAllUsers(int page){ + if (page < 0) { + throw new IllegalArgumentException("Page index must be 0 or greater"); + } + return userRepository.findAll(PageRequest.of(page, 20)); } /** @@ -63,8 +60,14 @@ public List getAllUsers(int page){ * @param id the user ID * @return the user */ - public Optional getUserById(Long id){ - return userRepository.findById(id); + public UserResponseDTO getUserById(Long id){ + Optional user = userRepository.findById(id); + return new UserResponseDTO( + user.get().getId(), + user.get().getEmail(), + user.get().getDisplayName(), + user.get().getRole() + ); } /** @@ -88,14 +91,4 @@ public User patchUser(Long id, String role){ user.changeRole(role); return userRepository.save(user); } - - /** - * Gets user by display name - * @param name the display name - * @return the user - */ - public User getUserByName(String name){ - return userRepository.findByDisplayName(name) - .orElseThrow(() -> new EntityNotFoundException("No user named " + name)); - } } diff --git a/api/src/main/resources/application.yaml b/api/src/main/resources/application.yaml index e14c857..306c6c0 100644 --- a/api/src/main/resources/application.yaml +++ b/api/src/main/resources/application.yaml @@ -12,4 +12,8 @@ spring: database-platform: org.hibernate.dialect.PostgreSQLDialect hibernate: ddl-auto: update - 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/UserControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java index b8ba190..63a3010 100644 --- a/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java @@ -1,23 +1,28 @@ package edu.csumb.cst438.api; -import static org.mockito.Mockito.when; +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.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +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 lombok.With; 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; import java.util.Optional; /** @@ -42,8 +47,13 @@ public class UserControllerTest { @Test @WithMockUser(roles = "ADMIN") void testGETUsersWAdmin() throws Exception{ + User mockUser = new User("email@gmail.com", "newName", "USER"); + when(userService.getAllUsers(0)).thenReturn(new PageImpl<>(List.of(mockUser))); mockMvc.perform(get("/api/v1/users")) - .andExpect(status().isOk()); + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content[0].email").value("email@gmail.com")) + .andExpect(jsonPath("$.page.totalElements").value(1)) + .andExpect(jsonPath("$.page.number").value(0)); } /** @@ -53,8 +63,8 @@ void testGETUsersWAdmin() throws Exception{ @Test @WithMockUser(roles = "ADMIN") void testGETUserIdWAdmin() throws Exception{ - User mockUser = new User("email@gmail.com", "newName", "USER"); - when(userService.getUserById(1L)).thenReturn(Optional.of(mockUser)); + 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()); } @@ -76,6 +86,92 @@ void testPATCHUserWAdmin() throws Exception{ .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 @@ -83,8 +179,8 @@ void testPATCHUserWAdmin() throws Exception{ @Test @WithMockUser(roles = "ADMIN") void testDELETEUserIdWAdmin() throws Exception{ - User mockUser = new User("email@gmail.com", "newName", "USER"); - when(userService.getUserById(1L)).thenReturn(Optional.of(mockUser)); + 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()); } @@ -97,7 +193,6 @@ void testDELETEUserIdWAdmin() throws Exception{ @Test @WithMockUser(roles = "USER") void testGETUsersWUser() throws Exception{ - User mockUser = new User("email@gmail.com", "newName", "USER"); mockMvc.perform(get("/api/v1/users")) .andExpect(status().isForbidden()); } @@ -109,8 +204,8 @@ void testGETUsersWUser() throws Exception{ @Test @WithMockUser(roles = "USER") void testGETUserIdWUser() throws Exception{ - User mockUser = new User("email@gmail.com", "newName", "USER"); - when(userService.getUserById(1L)).thenReturn(Optional.of(mockUser)); + 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()); } @@ -138,8 +233,8 @@ void testPATCHUserWUser() throws Exception{ @Test @WithMockUser(roles = "USER") void testDELETEUserIdWUser() throws Exception{ - User mockUser = new User("email@gmail.com", "newName", "USER"); - when(userService.getUserById(1L)).thenReturn(Optional.of(mockUser)); + 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()); } @@ -149,10 +244,10 @@ void testDELETEUserIdWUser() throws Exception{ * @throws Exception if there is an exception */ @Test - @WithMockUser(roles = "USER") + @WithMockUser(username = "email@gmail.com", roles = "USER") void testGETLoggedInUser() throws Exception{ User mockUser = new User("email@gmail.com", "user", "USER"); - when(userService.getUserByName("user")).thenReturn(mockUser); + when(userService.getUserByEmail("email@gmail.com")).thenReturn(mockUser); mockMvc.perform(get("/api/v1/users/me")) .andExpect(status().isOk()) .andExpect(jsonPath("$.email").value("email@gmail.com")); @@ -163,11 +258,13 @@ void testGETLoggedInUser() throws Exception{ * @throws Exception if there is an exception */ @Test - @WithMockUser(roles = "USER") + @WithMockUser(username = "email@gmail.com", roles = "USER") void testDELETELoggedInUser() throws Exception{ - User mockUser = new User("email@gmail.com", "user", "USER"); - when(userService.getUserByName("user")).thenReturn(mockUser); + User mockUser = mock(User.class); + when(mockUser.getId()).thenReturn(1L); + when(userService.getUserByEmail("email@gmail.com")).thenReturn(mockUser); 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 index 60446d8..e135bf1 100644 --- a/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java @@ -1,14 +1,18 @@ package edu.csumb.cst438.api; 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 org.springframework.data.domain.Pageable; import org.springframework.security.core.userdetails.UserDetails; @@ -17,6 +21,8 @@ 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 @@ -37,13 +43,13 @@ public class UserServiceTest { @Test void testGetUserByUsername(){ User mockUser = new User("email@gmail.com", "newUser", "USER"); - Mockito.when(userRepository.findByDisplayName("newUser")).thenReturn(Optional.of(mockUser)); + Mockito.when(userRepository.findByEmail("email@gmail.com")).thenReturn(Optional.of(mockUser)); - User result = userService.getUserByName("newUser"); + User result = userService.getUserByEmail("email@gmail.com"); assertNotNull(result); assertEquals("newUser", result.getDisplayName()); assertEquals("email@gmail.com", result.getEmail()); - Mockito.verify(userRepository, Mockito.times(1)).findByDisplayName("newUser"); + Mockito.verify(userRepository, Mockito.times(1)).findByEmail("email@gmail.com"); } /** @@ -53,13 +59,27 @@ void testGetUserByUsername(){ void testGetAllUsers(){ User mockUser = new User("email@gmail.com", "newUser", "USER"); User mockUser2 = new User("gmail@gmail.com", "newerUser", "USER"); - Mockito.when(userRepository.findUsersInPage(PageRequest.of(0, 20))).thenReturn(List.of(mockUser, mockUser2)); + Page page = new PageImpl<>(List.of(mockUser, mockUser2)); + Mockito.when(userRepository.findAll(PageRequest.of(0, 20))).thenReturn(page); - List result = userService.getAllUsers(0); + Page result = userService.getAllUsers(0); assertNotNull(result); - assertTrue(result.contains(mockUser)); - assertTrue(result.contains(mockUser2)); - Mockito.verify(userRepository, Mockito.times(1)).findUsersInPage(PageRequest.of(0, 20)); + assertTrue(result.getContent().contains(mockUser)); + assertTrue(result.getContent().contains(mockUser2)); + Mockito.verify(userRepository, Mockito.times(1)).findAll(PageRequest.of(0, 20)); + } + + /** + * Tests getAllUsers + */ + @Test + void testgetAllUsersWNeg() { + IllegalArgumentException ex = assertThrows( + IllegalArgumentException.class, + () -> userService.getAllUsers(-1)); + + assertEquals("Page index must be 0 or greater", ex.getMessage()); + verifyNoInteractions(userRepository); } /** @@ -70,10 +90,10 @@ void testGetUserById(){ User mockUser = new User("email@gmail.com", "newUser", "USER"); Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser)); - Optional result = userService.getUserById(1L); + UserResponseDTO result = userService.getUserById(1L); assertNotNull(result); - assertEquals("newUser", result.get().getDisplayName()); - assertEquals("email@gmail.com", result.get().getEmail()); +// assertEquals("newUser", result.get().getDisplayName()); +// assertEquals("email@gmail.com", result.get().getEmail()); Mockito.verify(userRepository, Mockito.times(1)).findById(1L); } @@ -95,12 +115,23 @@ void testDeleteUserById(){ void testPatchUser(){ User mockUser = new User("email@gmail.com", "newUser", "USER"); Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser)); + Mockito.when(userRepository.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); mockUser = userService.patchUser(1L, "ADMIN"); - Optional result = userService.getUserById(1L); - assertNotNull(result); - assertEquals("newUser", result.get().getDisplayName()); - assertEquals("ADMIN", result.get().getRole()); + UserResponseDTO result = userService.getUserById(1L); + assertEquals("ADMIN", result.role()); + Mockito.verify(userRepository).save(mockUser); + } + + /** + * 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()); } /** @@ -109,27 +140,21 @@ void testPatchUser(){ @Test void testLoadUserByUsername(){ User mockUser = new User("email@gmail.com", "newUser", "USER"); - Mockito.when(userRepository.findByDisplayName("newUser")).thenReturn(Optional.of(mockUser)); + Mockito.when(userRepository.findByEmail("email@gmail.com")).thenReturn(Optional.of(mockUser)); - UserDetails details = userService.loadUserByUsername("newUser"); + User result = userService.getUserByEmail("email@gmail.com"); - assertEquals("newUser", details.getUsername()); - assertEquals("email@gmail.com", details.getPassword()); - assertTrue(details.getAuthorities().stream() - .anyMatch(a -> a.getAuthority().equals("ROLE_USER"))); + assertEquals("newUser", result.getDisplayName()); + assertEquals("email@gmail.com", result.getEmail()); + Mockito.verify(userRepository, Mockito.times(1)).findByEmail("email@gmail.com"); } /** - * Tests LoadUserByUsername to make sure that the ADMIN role is ADMIN authority + * Tests get user when email isn't found */ @Test - void testLoadUserByUsernameMapsAdmin(){ - User mockUser = new User("email@gmail.com", "newAdmin", "ADMIN"); - Mockito.when(userRepository.findByDisplayName("newAdmin")).thenReturn(Optional.of(mockUser)); - - UserDetails details = userService.loadUserByUsername("newAdmin"); - - assertTrue(details.getAuthorities().stream() - .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))); + void testGetUserByEmailNotFound(){ + Mockito.when(userRepository.findByEmail("no@gmail.com")).thenReturn(Optional.empty()); + assertThrows(EntityNotFoundException.class, () -> userService.getUserByEmail("no@gmail.com")); } } From efb311fe4c9483c28b20df10ae1ad2b207ff7c4a Mon Sep 17 00:00:00 2001 From: annabelle-baltes Date: Sat, 17 Oct 2026 23:14:40 -0700 Subject: [PATCH 3/5] More changes have been made Hopefully most problems are fixed --- .../cst438/api/controller/UserController.java | 20 ++--- .../csumb/cst438/api/service/UserService.java | 51 ++++++++----- .../csumb/cst438/api/UserControllerTest.java | 17 ++--- .../edu/csumb/cst438/api/UserServiceTest.java | 74 ++++++++++--------- 4 files changed, 86 insertions(+), 76 deletions(-) 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 index ebf7b23..6222c29 100644 --- a/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java +++ b/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java @@ -1,10 +1,8 @@ package edu.csumb.cst438.api.controller; -import edu.csumb.cst438.api.entity.User; import edu.csumb.cst438.api.record.UserResponseDTO; import edu.csumb.cst438.api.record.UserRoleUpdateRequest; import edu.csumb.cst438.api.service.UserService; -import jakarta.persistence.EntityNotFoundException; import jakarta.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.web.PagedModel; @@ -12,8 +10,6 @@ import org.springframework.web.bind.annotation.*; import java.security.Principal; -import java.util.List; -import java.util.Optional; /** * The home of the API routes and what they do @@ -38,8 +34,8 @@ public UserController(UserService userService){ * @return Ok with users unless the one calling it isn't an Admin */ @GetMapping - public ResponseEntity> getAllUsers(@RequestParam(defaultValue = "0") int page){ - Page users = userService.getAllUsers(page); + public ResponseEntity> getAllUsers(@RequestParam(defaultValue = "0") int page){ + Page users = userService.getAllUsers(page); return ResponseEntity.ok(new PagedModel<>(users)); } @@ -72,8 +68,8 @@ public ResponseEntity deleteUser(@PathVariable Long userId){ * @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){ - User updatedUser = userService.patchUser(userId, request.role()); + public ResponseEntity patchUser(@PathVariable Long userId, @Valid @RequestBody UserRoleUpdateRequest request){ + UserResponseDTO updatedUser = userService.patchUser(userId, request.role()); return ResponseEntity.ok(updatedUser); } @@ -83,8 +79,8 @@ public ResponseEntity patchUser(@PathVariable Long userId, @Valid @Request * @return Ok with user unless the one calling it isn't the current user */ @GetMapping("/me") - public ResponseEntity getCurrentUser(Principal principal){ - User user = userService.getUserByEmail(principal.getName()); + public ResponseEntity getCurrentUser(Principal principal){ + UserResponseDTO user = userService.getUserByEmail(principal.getName()); return ResponseEntity.ok(user); } @@ -95,8 +91,8 @@ public ResponseEntity getCurrentUser(Principal principal){ */ @DeleteMapping("/me") public ResponseEntity deleteCurrentUser(Principal principal){ - User user = userService.getUserByEmail(principal.getName()); - userService.deleteUser(user.getId()); + 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/service/UserService.java b/api/src/main/java/edu/csumb/cst438/api/service/UserService.java index 79fcd36..2a5dec6 100644 --- a/api/src/main/java/edu/csumb/cst438/api/service/UserService.java +++ b/api/src/main/java/edu/csumb/cst438/api/service/UserService.java @@ -5,18 +5,10 @@ import edu.csumb.cst438.api.repository.UserRepository; import jakarta.persistence.EntityNotFoundException; import jakarta.transaction.Transactional; -import org.jspecify.annotations.NonNull; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Optional; - /** * Methods that are ran in the controller, does a lot of the work. */ @@ -37,22 +29,34 @@ public UserService(UserRepository userRepository){ * @param email user email * @return the user */ - public User getUserByEmail(String email){ - return userRepository.findByEmail(email) + 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) * @return a list of users - * @throws IllegalArgumentException if page index isn't <= 0 + * @throws IllegalArgumentException if page index is < 0 */ - public Page getAllUsers(int page){ + public Page getAllUsers(int page){ if (page < 0) { throw new IllegalArgumentException("Page index must be 0 or greater"); } - return userRepository.findAll(PageRequest.of(page, 20)); + return userRepository.findAll(PageRequest.of(page, 20)) + .map(user -> new UserResponseDTO( + user.getId(), + user.getEmail(), + user.getDisplayName(), + user.getRole() + )); } /** @@ -61,12 +65,14 @@ public Page getAllUsers(int page){ * @return the user */ public UserResponseDTO getUserById(Long id){ - Optional user = userRepository.findById(id); + User user = userRepository.findById(id) + .orElseThrow(() -> + new EntityNotFoundException("No user found with id " + id)); return new UserResponseDTO( - user.get().getId(), - user.get().getEmail(), - user.get().getDisplayName(), - user.get().getRole() + user.getId(), + user.getEmail(), + user.getDisplayName(), + user.getRole() ); } @@ -85,10 +91,15 @@ public void deleteUser(Long id){ * @return the updated user */ @Transactional - public User patchUser(Long id, String role){ + 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 userRepository.save(user); + return new UserResponseDTO( + user.getId(), + user.getEmail(), + user.getDisplayName(), + user.getRole() + ); } } diff --git a/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java index 63a3010..c504da8 100644 --- a/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java @@ -10,7 +10,6 @@ import edu.csumb.cst438.api.record.UserResponseDTO; import edu.csumb.cst438.api.service.UserService; import jakarta.persistence.EntityNotFoundException; -import lombok.With; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; @@ -23,7 +22,6 @@ import org.springframework.test.web.servlet.MockMvc; import java.util.List; -import java.util.Optional; /** * Tests the UserController.java API routes @@ -47,7 +45,7 @@ public class UserControllerTest { @Test @WithMockUser(roles = "ADMIN") void testGETUsersWAdmin() throws Exception{ - User mockUser = new User("email@gmail.com", "newName", "USER"); + UserResponseDTO mockUser = new UserResponseDTO(1L, "email@gmail.com", "newName", "USER"); when(userService.getAllUsers(0)).thenReturn(new PageImpl<>(List.of(mockUser))); mockMvc.perform(get("/api/v1/users")) .andExpect(status().isOk()) @@ -76,8 +74,7 @@ void testGETUserIdWAdmin() throws Exception{ @Test @WithMockUser(roles = "ADMIN") void testPATCHUserWAdmin() throws Exception{ - User mockUser = new User("email@gmail.com", "newName", "ADMIN"); - when(userService.patchUser(1L, "ADMIN")).thenReturn(mockUser); + 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) @@ -183,6 +180,7 @@ void testDELETEUserIdWAdmin() throws Exception{ when(userService.getUserById(1L)).thenReturn(mockUser); mockMvc.perform(delete("/api/v1/users/1")) .andExpect(status().isNoContent()); + verify(userService).deleteUser(1L); } @@ -217,13 +215,11 @@ void testGETUserIdWUser() throws Exception{ @Test @WithMockUser(roles = "USER") void testPATCHUserWUser() throws Exception{ - User mockUser = new User("email@gmail.com", "newName", "ADMIN"); - when(userService.patchUser(1L, "ADMIN")).thenReturn(mockUser); - mockMvc.perform(patch("/api/v1/users/1") .contentType(MediaType.APPLICATION_JSON) .content("{\"role\":\"ADMIN\"}")) .andExpect(status().isForbidden()); + verifyNoInteractions(userService); } /** @@ -246,8 +242,7 @@ void testDELETEUserIdWUser() throws Exception{ @Test @WithMockUser(username = "email@gmail.com", roles = "USER") void testGETLoggedInUser() throws Exception{ - User mockUser = new User("email@gmail.com", "user", "USER"); - when(userService.getUserByEmail("email@gmail.com")).thenReturn(mockUser); + 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")); @@ -262,7 +257,7 @@ void testGETLoggedInUser() throws Exception{ void testDELETELoggedInUser() throws Exception{ User mockUser = mock(User.class); when(mockUser.getId()).thenReturn(1L); - when(userService.getUserByEmail("email@gmail.com")).thenReturn(mockUser); + 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 index e135bf1..bd42bef 100644 --- a/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java @@ -1,5 +1,6 @@ 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; @@ -14,8 +15,6 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.security.core.userdetails.UserDetails; import java.util.List; import java.util.Optional; @@ -26,7 +25,6 @@ /** * Tests methods in UserService class - * * Disclaimer: also assisted by AI */ @ExtendWith(MockitoExtension.class) @@ -45,10 +43,10 @@ void testGetUserByUsername(){ User mockUser = new User("email@gmail.com", "newUser", "USER"); Mockito.when(userRepository.findByEmail("email@gmail.com")).thenReturn(Optional.of(mockUser)); - User result = userService.getUserByEmail("email@gmail.com"); + UserResponseDTO result = userService.getUserByEmail("email@gmail.com"); assertNotNull(result); - assertEquals("newUser", result.getDisplayName()); - assertEquals("email@gmail.com", result.getEmail()); + assertEquals("newUser", result.displayName()); + assertEquals("email@gmail.com", result.email()); Mockito.verify(userRepository, Mockito.times(1)).findByEmail("email@gmail.com"); } @@ -62,10 +60,11 @@ void testGetAllUsers(){ Page page = new PageImpl<>(List.of(mockUser, mockUser2)); Mockito.when(userRepository.findAll(PageRequest.of(0, 20))).thenReturn(page); - Page result = userService.getAllUsers(0); - assertNotNull(result); - assertTrue(result.getContent().contains(mockUser)); - assertTrue(result.getContent().contains(mockUser2)); + Page result = userService.getAllUsers(0); + + 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, 20)); } @@ -92,18 +91,42 @@ void testGetUserById(){ UserResponseDTO result = userService.getUserById(1L); assertNotNull(result); -// assertEquals("newUser", result.get().getDisplayName()); -// assertEquals("email@gmail.com", result.get().getEmail()); + 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"); - userService.deleteUser(1L); Mockito.verify(userRepository, Mockito.times(1)).deleteById(1L); } @@ -115,12 +138,12 @@ void testDeleteUserById(){ void testPatchUser(){ User mockUser = new User("email@gmail.com", "newUser", "USER"); Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser)); - Mockito.when(userRepository.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); - mockUser = userService.patchUser(1L, "ADMIN"); - UserResponseDTO result = userService.getUserById(1L); + UserResponseDTO result = userService.patchUser(1L, "ADMIN"); + assertEquals("ADMIN", result.role()); - Mockito.verify(userRepository).save(mockUser); + assertEquals("email@gmail.com", result.email()); + assertEquals("newUser", result.displayName()); } /** @@ -134,21 +157,6 @@ void testPatchUserNotFound(){ Mockito.verify(userRepository, Mockito.never()).save(any()); } - /** - * Tests LoadUserByUsername - */ - @Test - void testLoadUserByUsername(){ - User mockUser = new User("email@gmail.com", "newUser", "USER"); - Mockito.when(userRepository.findByEmail("email@gmail.com")).thenReturn(Optional.of(mockUser)); - - User result = userService.getUserByEmail("email@gmail.com"); - - assertEquals("newUser", result.getDisplayName()); - assertEquals("email@gmail.com", result.getEmail()); - Mockito.verify(userRepository, Mockito.times(1)).findByEmail("email@gmail.com"); - } - /** * Tests get user when email isn't found */ From 4b67de4ab9448febe28a674d06456a1a41d62455 Mon Sep 17 00:00:00 2001 From: annabelle-baltes Date: Sun, 18 Oct 2026 16:13:29 -0700 Subject: [PATCH 4/5] Even more changes have been made --- .../cst438/api/controller/UserController.java | 5 ++- .../csumb/cst438/api/service/UserService.java | 10 ++++- .../csumb/cst438/api/UserControllerTest.java | 2 +- .../edu/csumb/cst438/api/UserServiceTest.java | 38 ++++++++++++++++--- 4 files changed, 45 insertions(+), 10 deletions(-) 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 index 6222c29..c0c2d9c 100644 --- a/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java +++ b/api/src/main/java/edu/csumb/cst438/api/controller/UserController.java @@ -31,11 +31,12 @@ public UserController(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){ - Page users = userService.getAllUsers(page); + 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)); } 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 index 2a5dec6..fd2cfc8 100644 --- a/api/src/main/java/edu/csumb/cst438/api/service/UserService.java +++ b/api/src/main/java/edu/csumb/cst438/api/service/UserService.java @@ -43,14 +43,18 @@ public UserResponseDTO getUserByEmail(String email){ /** * 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){ + public Page getAllUsers(int page, int size){ if (page < 0) { throw new IllegalArgumentException("Page index must be 0 or greater"); } - return userRepository.findAll(PageRequest.of(page, 20)) + 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(), @@ -81,6 +85,8 @@ public UserResponseDTO getUserById(Long 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); } diff --git a/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java index c504da8..a6f1102 100644 --- a/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/UserControllerTest.java @@ -46,7 +46,7 @@ public class UserControllerTest { @WithMockUser(roles = "ADMIN") void testGETUsersWAdmin() throws Exception{ UserResponseDTO mockUser = new UserResponseDTO(1L, "email@gmail.com", "newName", "USER"); - when(userService.getAllUsers(0)).thenReturn(new PageImpl<>(List.of(mockUser))); + 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")) diff --git a/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java index bd42bef..aaa74f0 100644 --- a/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/UserServiceTest.java @@ -58,29 +58,55 @@ 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, 20))).thenReturn(page); + Mockito.when(userRepository.findAll(PageRequest.of(0, 2))).thenReturn(page); - Page result = userService.getAllUsers(0); + 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, 20)); + Mockito.verify(userRepository, Mockito.times(1)).findAll(PageRequest.of(0, 2)); } /** - * Tests getAllUsers + * Tests getAllUsers with negative page */ @Test void testgetAllUsersWNeg() { IllegalArgumentException ex = assertThrows( IllegalArgumentException.class, - () -> userService.getAllUsers(-1)); + () -> 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 */ @@ -127,6 +153,8 @@ void testGetUserByIdWithStuff(){ */ @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); } From f8100a65c0bfe1c955ecf58eebfd9be0770661fd Mon Sep 17 00:00:00 2001 From: annabelle-baltes Date: Sun, 18 Oct 2026 17:04:03 -0700 Subject: [PATCH 5/5] Small fixes --- .../edu/csumb/cst438/api/SecurityConfig.java | 5 ++++ .../cst438/api/MealPlanControllerTest.java | 25 +++++++++++++------ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java index 559876e..c34e866 100644 --- a/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java +++ b/api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java @@ -47,6 +47,11 @@ public SecurityFilterChain securityFilterChain( .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") 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))