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

6주차 과제 - 로그인 구현하기 #70

Merged
merged 28 commits into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
50766c1
Controller , Service 주석 작성
jdalma Sep 5, 2022
6974c98
SessionController login메소드 추가
jdalma Sep 13, 2022
3f6ec78
jwtUtil 추가
jdalma Sep 13, 2022
e500054
InvalidTokenException advice 추가
jdalma Sep 13, 2022
a3bb4f6
상품 등록 시 JWT 및 사용자 확인
jdalma Sep 13, 2022
6caff11
findUser public으로 변경
jdalma Sep 13, 2022
c32ae97
ProductController 테스트 코드 작성
jdalma Sep 13, 2022
df8f01e
JwtUtil 테스트 코드 작성
jdalma Sep 13, 2022
a1ecba0
JwtUtil null 체크 숨기기
jdalma Sep 14, 2022
93ff275
JwtUtil 주석, 테스트 코드 추가
jdalma Sep 14, 2022
2c04eae
ddl-auto create로 수정
jdalma Sep 14, 2022
90f9e60
ProductController 테스트 코드 수정
jdalma Sep 14, 2022
a8d90b9
JwtUtil 테스트 코드 수정
jdalma Sep 14, 2022
05db189
AuthenticationService tokenValidation메소드 추가
JwtUtil 메소드 추가 및 수정
jdalma Sep 14, 2022
7efccfe
decode메소드 검증 부분 수정
jdalma Sep 15, 2022
c833de7
JwtUtil.encode() 테스트 코드 수정
jdalma Sep 15, 2022
c793d25
Session 응답 DTO 추가
jdalma Sep 15, 2022
7930ef9
Session spec 사용자 이메일 수정
jdalma Sep 15, 2022
a64d3c4
로그인 시 사용자 email , password를 확인하여 사용자 검증 및 JWT 반환 추가
jdalma Sep 15, 2022
324f9db
final 선언 및 스코프 줄이기
jdalma Sep 16, 2022
042eaaa
빈 검증 실패 시 에러 메시지 추가
jdalma Sep 16, 2022
ea2588a
수정 및 ExceptionHandler 테스트 코드 추가
jdalma Sep 16, 2022
0699e11
JwtUtil decode 유효성 검사 수정
jdalma Sep 17, 2022
1f1b99f
Product 경로 인증 인터셉터 추가
jdalma Sep 17, 2022
1888b60
UserLoginValidator 임시 추가
jdalma Sep 17, 2022
522ac8f
Update app/src/main/java/com/codesoom/assignment/application/Authenti…
jdalma Sep 18, 2022
7760d3f
AuthenticationService 구현 숨기기
jdalma Sep 18, 2022
5cb2b86
인터페이스 추가
jdalma Sep 18, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package com.codesoom.assignment.application;

import com.codesoom.assignment.domain.User;
import com.codesoom.assignment.dto.UserLoginData;
import com.codesoom.assignment.errors.InvalidTokenException;
import com.codesoom.assignment.errors.UserNotFoundException;
import com.codesoom.assignment.errors.WrongPasswordException;
import com.codesoom.assignment.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import com.github.dozermapper.core.Mapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

Expand All @@ -12,16 +16,39 @@ public class AuthenticationService {

private final JwtUtil jwtUtil;
private final UserService userService;
private final Mapper mapper;

public AuthenticationService(JwtUtil jwtUtil, UserService userService) {
public AuthenticationService(JwtUtil jwtUtil, UserService userService , Mapper dozerMapper) {
this.jwtUtil = jwtUtil;
this.userService = userService;
this.mapper = dozerMapper;

}

public String login(){
return jwtUtil.encode(1L);
/**
* JWT 토큰을 반환한다.
*
* @param loginData 로그인 정보
* @throws UserNotFoundException 로그인 정보에 해당하는 사용자가 존재하지 않을 경우
* @throws WrongPasswordException 사용자의 패스워드 정보가 일치하지 않은 경우
* @return JWT 반환
*/
public String login(UserLoginData loginData){
User user = mapper.map(loginData , User.class);
User findUser = userService.findByEmail(user.getEmail());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
User user = mapper.map(loginData , User.class);
User findUser = userService.findByEmail(user.getEmail());
User findUser = userService.findByEmail(emailFrom(loginData));

이런식으로 메소드를 추출해본다면 어떨까요? 구현을 감추면 좀 더 가독성이 좋을 것 같아요!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

데이터를 요청하지 말고 작업을 요청해라 명심하겠습니다.

if(!findUser.authenticate(user.getPassword())){
throw new WrongPasswordException();
}
return jwtUtil.encode(findUser.getId());
}

/**
* JWT를 검증한다.
*
* @param token JWT
* @throws InvalidTokenException 토큰 정보가 null 또는 사이즈가 0이거나 첫 글자가 공백 , 유효하지 않은 토큰이라면 예외를 던진다.
* @throws UserNotFoundException 페이로드에 담긴 식별자에 해당하는 사용자가 없는 경우
*/
public void tokenValidation(String token){
Long id = jwtUtil.getUserIdFromToken(token);
userService.findUser(id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,16 @@ public User findUser(Long id) {
return userRepository.findByIdAndDeletedIsFalse(id)
.orElseThrow(() -> new UserNotFoundException(id));
}

/**
* 사용자를 조회한다.
*
* @param email 조회할 사용자의 이메일
* @throws UserNotFoundException 이메일에 해당하는 사용자가 존재하지 않을 경우
* @return 이메일에 해당하는 사용자
*/
public User findByEmail(String email){
return userRepository.findByEmail(email)
.orElseThrow(() -> new UserNotFoundException(email));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.codesoom.assignment.errors.ProductNotFoundException;
import com.codesoom.assignment.errors.UserEmailDuplicationException;
import com.codesoom.assignment.errors.UserNotFoundException;
import com.codesoom.assignment.errors.WrongPasswordException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
Expand Down Expand Up @@ -37,4 +38,10 @@ public ErrorResponse handleUserEmailIsAlreadyExisted() {
public ErrorResponse handleInvalidToken(InvalidTokenException e){
return new ErrorResponse("Invalid Token Exception" + e.getMessage());
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(WrongPasswordException.class)
public ErrorResponse handleWrongPassword(){
return new ErrorResponse("Wrong Password Exception");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@

import com.codesoom.assignment.application.AuthenticationService;
import com.codesoom.assignment.dto.SessionResponseData;
import com.codesoom.assignment.dto.UserLoginData;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
* 1. Create -> 로그인 , 토큰 반환
* 2. Read -> 세션 조회 , 유효 확인 , 세션 정보 반환
Expand All @@ -26,8 +30,8 @@ public SessionController(AuthenticationService authenticationService) {

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public SessionResponseData login(){
String accessToken = authenticationService.login();
public SessionResponseData login(@RequestBody @Valid UserLoginData loginData){
String accessToken = authenticationService.login(loginData);
return SessionResponseData.builder()
.accessToken(accessToken)
.build();
Expand Down
32 changes: 32 additions & 0 deletions app/src/main/java/com/codesoom/assignment/dto/UserLoginData.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.codesoom.assignment.dto;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.dozermapper.core.Mapping;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

@Getter
public class UserLoginData {
@NotBlank
@Size(min = 3)
@Mapping("email")
private final String email;

@NotBlank
@Size(min = 4, max = 1024)
Comment on lines +21 to +22

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

한번 경험삼아 메시지를 커스텀 해보는 것은 어떨까요?!

메시지를 커스텀하는 행위는 아주 일반적이니까요!

아니면 나아가서 커스텀 Validator를 만들어보는 겁니다!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{
    "message": null,
    "status": "BAD_REQUEST",
    "errors": [
        "[password] 크기가 4에서 1024 사이여야 합니다",
        "[email] 크기가 3에서 2147483647 사이여야 합니다"
    ]
}

일단 검증 실패 시 검증 정보를 위와 같이 반환하게 수정해봤습니다 042eaaa

커스텀 Validator는 내일 진행해보겠습니다!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

    @Size(min = 4, max = 1024, message = "")

각 유효성검증마다 메시지를 바꿀 수 있는 것이 좋지 않을까요!
또 메시지는 코드가 아닌 외부 파일로 분리하는 것도 좋은 생각일 것 같아요!

@Mapping("password")
private final String password;

@JsonCreator
public UserLoginData(@JsonProperty("email") String email,
@JsonProperty("password") String password){
this.email = email;
this.password = password;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.codesoom.assignment.errors;

public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
public UserNotFoundException(Object id) {
super("User not found: " + id);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.codesoom.assignment.errors;

public class WrongPasswordException extends RuntimeException{

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

import com.codesoom.assignment.application.AuthenticationService;
import com.codesoom.assignment.application.UserService;
import com.codesoom.assignment.domain.User;
import com.codesoom.assignment.utils.JwtUtil;
import com.github.dozermapper.core.DozerBeanMapper;
import com.github.dozermapper.core.Mapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
Expand All @@ -16,29 +17,31 @@ class AuthenticationServiceTest {

private AuthenticationService service;
private UserService userService;
private final String SECRET = "12345678901234567890123456789012";
private Mapper mapper;
private final String SECRET = "12345678901234567890123456789010";

@BeforeEach
void setUp() {
JwtUtil jwtUtil = new JwtUtil(SECRET);
userService = mock(UserService.class);
service = new AuthenticationService(jwtUtil, userService);
mapper = mock(Mapper.class);
service = new AuthenticationService(jwtUtil, userService , mapper);
}

@Nested
@DisplayName("")
class Describe_{
@DisplayName("login()")
class Describe_Login{

@Nested
@DisplayName("")
@DisplayName("파라미터에 해당하는 사용자가 존재한다면")
class Context_{

private final Long userId = 1L;

@Test
@DisplayName("")
void It_(){
String accessToken = service.login();

assertThat(accessToken).contains(".xxxx");
fail("작성 필요");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.codesoom.assignment.controllers;

import com.codesoom.assignment.application.UserService;
import com.codesoom.assignment.dto.UserRegistrationData;
import com.codesoom.assignment.utils.JwtUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
Expand All @@ -16,6 +20,7 @@
//@WebMvcTest(ProductController.class)
@SpringBootTest
@AutoConfigureMockMvc
@DisplayName("ProductController 테스트")
class ProductControllerTest {

private final String VALID_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjF9.neCsyNLzy3lQ4o2yliotWT06FwSGZagaHpKdAkjnGGw";
Expand All @@ -24,12 +29,29 @@ class ProductControllerTest {

@Autowired
private MockMvc mockMvc;
@Autowired
private UserService service;
@Autowired
private JwtUtil jwtUtil;

@BeforeEach
void setUp() {

}

long addUser(){
UserRegistrationData user = UserRegistrationData.builder()
.name("test")
.email("test@test.com")
.password("test")
.build();
return service.registerUser(user).getId();
}

void deleteUser(Long userId){
service.deleteUser(userId);
}

@Nested
@DisplayName("create()")
class Describe_Create{
Expand All @@ -55,7 +77,6 @@ void It_() throws Exception {
@DisplayName("인증 헤더의 토큰이 유효하지 않거나 공백이라면")
class Context_NullOrBlankAuthenticationHeader{


@Test
@DisplayName("권한에 대한 승인이 거부되었다는 응답 코드를 반환한다.")
void It_ThrowException() throws Exception {
Expand Down Expand Up @@ -105,14 +126,26 @@ void It_SaveProduct() throws Exception {
@DisplayName("사용자가 존재한다면")
class Context_{

private Long userId;
private String token;

@BeforeEach
void setUp() {
userId = addUser();
token = jwtUtil.encode(userId);
}

@AfterEach
void tearDown() {
deleteUser(userId);
}

@Test
@DisplayName("상품을 저장하고 자원을 생성했다는 응답코드를 반환한다.")
void It_() throws Exception {
mockMvc.perform(
post("/products")
.header("Authorization" , "Bearer " + VALID_TOKEN)
.header("Authorization" , "Bearer " + token)
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON)
.content(CONTENT)
Expand Down