Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/user endpoints #245

Merged
merged 13 commits into from
Apr 17, 2024
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package lab.en2b.quizapi.commons.user;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lab.en2b.quizapi.commons.user.dtos.UserResponseDto;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
Expand All @@ -23,9 +27,37 @@ public class UserController {
* @param authentication the authentication object
* @return the response dto for the user details
*/
@Operation(summary = "Gets the user details", description = "Gets the user details for the given authentication")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved"),
@ApiResponse(responseCode = "403", description = "You are not logged in", content = @io.swagger.v3.oas.annotations.media.Content),
})
@GetMapping("/details")
public ResponseEntity<UserResponseDto> getUserDetails(Authentication authentication) {
return ResponseEntity.ok(userService.getUserDetailsByAuthentication(authentication));
}

@Operation(summary = "Gets all users", description = "Gets all users")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved"),
@ApiResponse(responseCode = "403", description = "You are not logged in", content = @io.swagger.v3.oas.annotations.media.Content),
})
@GetMapping
public ResponseEntity<List<UserResponseDto>> getUsers() {
return ResponseEntity.ok(userService.getUsers());
}

@Operation(summary = "Gets a user", description = "Gets a user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved"),
@ApiResponse(responseCode = "403", description = "You are not logged in", content = @io.swagger.v3.oas.annotations.media.Content),
})
@Parameters({
@Parameter(name = "id", description = "The id of the user to get", example = "1")
})
@GetMapping("/{id}")
public ResponseEntity<UserResponseDto> getUser(@PathVariable Long id) {
return ResponseEntity.ok(userService.getUser(id));
}

}
10 changes: 10 additions & 0 deletions api/src/main/java/lab/en2b/quizapi/commons/user/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -71,4 +73,12 @@ public User getUserByAuthentication(Authentication authentication) {
public UserResponseDto getUserDetailsByAuthentication(Authentication authentication) {
return userResponseDtoMapper.apply(getUserByAuthentication(authentication));
}

public List<UserResponseDto> getUsers() {
return userRepository.findAll().stream().map(userResponseDtoMapper).collect(Collectors.toList());
}

public UserResponseDto getUser(Long id) {
return userResponseDtoMapper.apply(userRepository.findById(id).orElseThrow());
}
}
30 changes: 28 additions & 2 deletions api/src/test/java/lab/en2b/quizapi/user/UserControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,42 @@ public class UserControllerTest {
UserService userService;

@Test
void getUserShouldReturn200() throws Exception{
void getPersonalDetailsShouldReturn200() throws Exception{
mockMvc.perform(get("/users/details")
.with(user("test").roles("user")))
.andExpect(status().isOk());
}

@Test
void getUserShouldReturn403() throws Exception{
void getPersonalDetailsShouldReturn403() throws Exception{
mockMvc.perform(get("/users/details"))
.andExpect(status().isForbidden());
}

@Test
void getUsersShouldReturn200() throws Exception{
mockMvc.perform(get("/users")
.with(user("test").roles("user")))
.andExpect(status().isOk());
}

@Test
void getUsersShouldReturn403() throws Exception{
mockMvc.perform(get("/users"))
.andExpect(status().isForbidden());
}

@Test
void getUserShouldReturn200() throws Exception{
mockMvc.perform(get("/users/1")
.with(user("test").roles("user")))
.andExpect(status().isOk());
}

@Test
void getUserShouldReturn403() throws Exception{
mockMvc.perform(get("/users/1"))
.andExpect(status().isForbidden());
}

}
58 changes: 55 additions & 3 deletions api/src/test/java/lab/en2b/quizapi/user/UserServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import org.springframework.security.core.Authentication;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

Expand All @@ -33,13 +35,16 @@ public class UserServiceTest {
@Mock
private UserRepository userRepository;

private UserResponseDtoMapper userResponseDtoMapper;

private User defaultUser;

private UserResponseDto defaultUserResponseDto;

@BeforeEach
public void setUp() {
userService = new UserService(userRepository, new UserResponseDtoMapper());
this.userResponseDtoMapper = new UserResponseDtoMapper();
userService = new UserService(userRepository, userResponseDtoMapper);
defaultUser = User.builder()
.id(1L)
.username("HordyJurtado")
Expand All @@ -55,7 +60,7 @@ public void setUp() {
}

@Test
public void getUserDetailsTest(){
public void getPersonalDetailsTest(){
Authentication authentication = mock(Authentication.class);
when(authentication.getPrincipal()).thenReturn(UserDetailsImpl.build(defaultUser));
when(userRepository.findByEmail(any())).thenReturn(Optional.of(defaultUser));
Expand All @@ -64,11 +69,58 @@ public void getUserDetailsTest(){
}

@Test
public void getUserDetailsWhenNotFound() {
public void getPersonalDetailsWhenNotFound() {
Authentication authentication = mock(Authentication.class);
when(authentication.getPrincipal()).thenReturn(UserDetailsImpl.build(defaultUser));
when(userRepository.findByEmail(any())).thenReturn(Optional.empty());
Assertions.assertThrows(NoSuchElementException.class, () -> userService.getUserDetailsByAuthentication(authentication));
}

@Test
public void getUsersTestWhenThereAreMultiplePeople(){
User defaultUser1 = User.builder()
.id(1L)
.username("HordyJurtado")
.email("[email protected]")
.password("password")
.role("ROLE_USER")
.build();
User defaultUser2 = User.builder()
.id(2L)
.username("HordyJurtado")
.email("[email protected]")
.password("password")
.role("ROLE_USER")
.build();
User defaultUser3 = User.builder()
.id(3L)
.username("HordyJurtado")
.email("[email protected]")
.password("password")
.role("ROLE_USER")
.build();
List<User> userResult = List.of(defaultUser1, defaultUser2, defaultUser3);
when(userRepository.findAll()).thenReturn(userResult);
List<UserResponseDto> result = userResult.stream().map(userResponseDtoMapper::apply).toList();
Assertions.assertEquals(result, userService.getUsers());
}

@Test
public void getUsersTestWhenThereIsNoPeople(){
when(userRepository.findAll()).thenReturn(new ArrayList<>());
Assertions.assertEquals(List.of(), userService.getUsers());
}

@Test
public void getUserTest(){
when(userRepository.findById(1L)).thenReturn(Optional.of(defaultUser));
Assertions.assertEquals(defaultUserResponseDto, userService.getUser(1L));
}

@Test
public void getUserTestWhenNotFound(){
when(userRepository.findById(1L)).thenReturn(Optional.empty());
Assertions.assertThrows(NoSuchElementException.class, () -> userService.getUser(1L));
}

}