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 22 commits
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
@@ -0,0 +1,56 @@
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 com.github.dozermapper.core.Mapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AuthenticationService {

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

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

}

/**
* 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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,44 @@ public ProductService(
this.productRepository = productRepository;
}

/**
* 모든 상품을 조회한다.
*/
public List<Product> getProducts() {
return productRepository.findAll();
}

/**
* 상품을 조회한다.
*
* @param id 조회할 상품의 식별자
* @throws ProductNotFoundException 식별자에 해당하는 상품이 존재하지 않을 경우
* @return 식별자에 해당하는 상품
*/
public Product getProduct(Long id) {
return findProduct(id);
}


/**
* 상품을 등록한다.
*
* @param productData 등록할 상품의 정보
* @return 등록된 상품의 정보
*/
public Product createProduct(ProductData productData) {
Product product = mapper.map(productData, Product.class);
return productRepository.save(product);
}

/**
* 상품을 수정한다.
*
* @param id 수정할 상품의 식별자
* @param productData 수정할 상품의 정보
* @throws ProductNotFoundException 식별자에 해당하는 상품이 존재하지 않을 경우
* @return 수정된 상품의 정보
*/
public Product updateProduct(Long id, ProductData productData) {
Product product = findProduct(id);

Expand All @@ -45,6 +70,13 @@ public Product updateProduct(Long id, ProductData productData) {
return product;
}

/**
* 상품을 삭제한다.
*
* @param id 삭제할 상품의 식별자
* @throws ProductNotFoundException 식별자에 해당하는 상품이 존재하지 않을 경우
* @return 삭제된 상품의 정보
*/
public Product deleteProduct(Long id) {
Product product = findProduct(id);

Expand All @@ -53,6 +85,13 @@ public Product deleteProduct(Long id) {
return product;
}

/**
* 식별자에 해당하는 상품을 조회한다.
*
* @param id 조회할 상품의 식별자
* @throws ProductNotFoundException 식별자에 해당하는 상품이 존재하지 않을 경우
* @return 조회된 상품의 정보
*/
private Product findProduct(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new ProductNotFoundException(id));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ public UserService(Mapper dozerMapper, UserRepository userRepository) {
this.userRepository = userRepository;
}

/**
* 사용자를 등록한다.
*
* @param registrationData 등록할 유저의 정보
* @throws UserEmailDuplicationException 사용자의 Email이 중복되었을 경우
* @return 저장된 유저의 정보
*/
public User registerUser(UserRegistrationData registrationData) {
String email = registrationData.getEmail();
if (userRepository.existsByEmail(email)) {
Expand All @@ -32,6 +39,14 @@ public User registerUser(UserRegistrationData registrationData) {
return userRepository.save(user);
}

/**
* 사용자를 수정한다.
*
* @param id 수정할 사용자의 식별자
* @param modificationData 수정할 사용자의 정보
* @throws UserNotFoundException 식별자에 해당하는 사용자가 존재하지 않을 경우
* @return 수정된 사용자
*/
public User updateUser(Long id, UserModificationData modificationData) {
User user = findUser(id);

Expand All @@ -41,14 +56,40 @@ public User updateUser(Long id, UserModificationData modificationData) {
return user;
}

/**
* 사용자를 삭제한다.
*
* @param id 삭제할 사용자의 식별자
* @throws UserNotFoundException 식별자에 해당하는 사용자가 존재하지 않을 경우
* @return 삭제된 사용자
*/
public User deleteUser(Long id) {
User user = findUser(id);
user.destroy();
return user;
}

private User findUser(Long id) {
/**
* 사용자를 조회한다.
*
* @param id 조회할 사용자의 식별자
* @throws UserNotFoundException 식별자에 해당하는 사용자가 존재하지 않을 경우
* @return 식별자에 해당하는 사용자
*/
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
@@ -1,9 +1,11 @@
package com.codesoom.assignment.controllers;

import com.codesoom.assignment.dto.ErrorResponse;
import com.codesoom.assignment.errors.InvalidTokenException;
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 All @@ -30,4 +32,16 @@ public ErrorResponse handleUserNotFound() {
public ErrorResponse handleUserEmailIsAlreadyExisted() {
return new ErrorResponse("User's email address is already existed");
}

@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(InvalidTokenException.class)
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
@@ -0,0 +1,32 @@
package com.codesoom.assignment.controllers;

import com.codesoom.assignment.dto.ErrorResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

List<String> errors = ex.getBindingResult().getFieldErrors()
.stream()
.map(e -> String.format("[%s] %s" , e.getField() , e.getDefaultMessage()))
.collect(Collectors.toList());
ErrorResponse response = ErrorResponse.builder()
.errors(errors)
.status(HttpStatus.BAD_REQUEST)
.build();

return new ResponseEntity<>(response, response.getStatus());
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
package com.codesoom.assignment.controllers;

import com.codesoom.assignment.application.AuthenticationService;
import com.codesoom.assignment.application.ProductService;
import com.codesoom.assignment.application.UserService;
import com.codesoom.assignment.domain.Product;
import com.codesoom.assignment.dto.ProductData;
import com.codesoom.assignment.errors.InvalidTokenException;
import com.codesoom.assignment.errors.ProductNotFoundException;
import com.codesoom.assignment.errors.UserNotFoundException;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
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;
import java.util.List;
Expand All @@ -14,29 +32,66 @@
@CrossOrigin
public class ProductController {
private final ProductService productService;
private final AuthenticationService authenticationService;

public ProductController(ProductService productService) {
public ProductController(ProductService productService, AuthenticationService authenticationService) {
this.productService = productService;
this.authenticationService = authenticationService;
}

@ExceptionHandler(MissingRequestHeaderException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public void handleMissingRequestHeaderException(){

}

/**
* 모든 상품을 조회한다.
*/
@GetMapping
public List<Product> list() {
return productService.getProducts();
}

/**
* 상품을 조회한다.
*
* @param id 조회할 상품의 식별자
* @throws ProductNotFoundException 식별자에 해당하는 상품이 존재하지 않을 경우
* @return 식별자에 해당하는 상품
*/
@GetMapping("{id}")
public Product detail(@PathVariable Long id) {
return productService.getProduct(id);
}

/**
* 상품을 저장한다.
*
* @param productData 상품 저장 정보
* @param authorization Json Web Token
* @throws InvalidTokenException 유효하지 않은 토큰일 경우
* @throws UserNotFoundException 사용자가 존재하지 않을 경우
* @return 저장된 상품의 정보
*/
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Product create(
@RequestHeader("Authorization") String authorization,
@RequestBody @Valid ProductData productData
) {
authenticationService.tokenValidation(authorization);
return productService.createProduct(productData);
}

/**
* 상품을 수정한다.
*
* @param id 수정할 상품의 식별자
* @param productData 상품 수정 정보
* @throws ProductNotFoundException 식별자에 해당하는 상품이 존재하지 않을 경우
* @return 수정된 상품
*/
@PatchMapping("{id}")
public Product update(
@PathVariable Long id,
Expand All @@ -45,6 +100,12 @@ public Product update(
return productService.updateProduct(id, productData);
}

/**
* 상품을 삭제한다.
*
* @throws ProductNotFoundException 식별자에 해당하는 상품이 존재하지 않을 경우
* @param id 삭제할 상품의 식별자
*/
@DeleteMapping("{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void destroy(
Expand Down