반응형
인턴 업무와 세션쪽이 관계가 있어서 여기서 부터 듣고 있다.
48. 48. 인증 - 1 /49. 49. 인증 - 2
-> 세션을 이용한 인증으로 로그인 처리하기
=> accessToken
package kr.co.fastcampus.eatgo.application;
public class EmailNotExistedException extends RuntimeException {
EmailNotExistedException(String email) {
super("Email is not registered: " + email);
}
}
package kr.co.fastcampus.eatgo.application; public class EmailExistedException extends RuntimeException { EmailExistedException(String email) { super("Email is already registered: " + email); } }
package kr.co.fastcampus.eatgo.interfaces;
import kr.co.fastcampus.eatgo.application.EmailNotExistedException;
import kr.co.fastcampus.eatgo.application.PasswordWrongException;
import kr.co.fastcampus.eatgo.application.UserService;
import kr.co.fastcampus.eatgo.domain.User;
import kr.co.fastcampus.eatgo.utils.JwtUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.core.StringContains.containsString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(SessionController.class)
public class SessionControllerTests {
@Autowired
MockMvc mvc;
@MockBean
private JwtUtil jwtUtil;
@MockBean
private UserService userService;
@Test
public void createWithValidAttributes() throws Exception {
Long id = 1004L;
String email = "tester@example.com";
String name = "Tester";
String password = "test";
User mockUser = User.builder().id(id).name(name).level(1L).build();
given(userService.authenticate(email, password)).willReturn(mockUser);
given(jwtUtil.createToken(id, name, null))
.willReturn("header.payload.signature");
mvc.perform(post("/session")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"tester@example.com\",\"password\":\"test\"}"))
.andExpect(status().isCreated())
.andExpect(header().string("location", "/session"))
.andExpect(content().string(
containsString("{\"accessToken\":\"header.payload.signature\"}")
));
verify(userService).authenticate(eq(email), eq(password));
}
@Test
public void createRestaurantOwner() throws Exception {
Long id = 1004L;
String email = "tester@example.com";
String name = "Tester";
String password = "test";
User mockUser = User.builder()
.id(id)
.name(name)
.level(50L)
.restaurantId(369L)
.build();
given(userService.authenticate(email, password)).willReturn(mockUser);
given(jwtUtil.createToken(id, name, 369L))
.willReturn("header.payload.signature");
mvc.perform(post("/session")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"tester@example.com\",\"password\":\"test\"}"))
.andExpect(status().isCreated())
.andExpect(header().string("location", "/session"))
.andExpect(content().string(
containsString("{\"accessToken\":\"header.payload.signature\"}")
));
verify(userService).authenticate(eq(email), eq(password));
}
@Test
public void createWithNotExistedEmail() throws Exception {
given(userService.authenticate("x@example.com", "test"))
.willThrow(EmailNotExistedException.class);
mvc.perform(post("/session")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"x@example.com\",\"password\":\"test\"}"))
.andExpect(status().isBadRequest());
verify(userService).authenticate(eq("x@example.com"), eq("test"));
}
@Test
public void createWithWrongPassword() throws Exception {
given(userService.authenticate("tester@example.com", "x"))
.willThrow(PasswordWrongException.class);
mvc.perform(post("/session")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\":\"tester@example.com\",\"password\":\"x\"}"))
.andExpect(status().isBadRequest());
verify(userService).authenticate(eq("tester@example.com"), eq("x"));
}
}
package kr.co.fastcampus.eatgo.interfaces;
import kr.co.fastcampus.eatgo.application.UserService;
import kr.co.fastcampus.eatgo.domain.User;
import kr.co.fastcampus.eatgo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
import java.net.URISyntaxException;
@CrossOrigin
@RestController
public class SessionController {
@Autowired
private JwtUtil jwtUtil;
@Autowired
private UserService userService;
@PostMapping("/session")
public ResponseEntity<SessionResponseDto> create(
@RequestBody SessionRequestDto resource
) throws URISyntaxException {
String email = resource.getEmail();
String password = resource.getPassword();
User user = userService.authenticate(email, password);
String accessToken = jwtUtil.createToken(
user.getId(),
user.getName(),
user.isRestaurantOwner() ? user.getRestaurantId() : null);
String url = "/session";
return ResponseEntity.created(new URI(url)).body(
SessionResponseDto.builder()
.accessToken(accessToken)
.build());
}
}
자바 인강이 듣고 싶다면 =>https://bit.ly/3ilMbIO
반응형
'스프링, 자바' 카테고리의 다른 글
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 40회차 미션 (0) | 2020.09.18 |
---|---|
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 39회차 미션 (0) | 2020.09.17 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 37회차 미션 (0) | 2020.09.15 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 36회차 미션 (0) | 2020.09.14 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 35회차 미션 (0) | 2020.09.13 |