diff --git a/build.gradle b/build.gradle index 4943187..327d2c6 100644 --- a/build.gradle +++ b/build.gradle @@ -19,6 +19,9 @@ repositories { } dependencies { + implementation 'org.springframework.boot:spring-boot-starter-aop' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation group: 'com.auth0', name: 'java-jwt', version: '4.3.0' implementation group: 'com.auth0', name: 'java-jwt', version: '4.3.0' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' diff --git a/src/main/java/shop/mtcoding/metamall/MetamallApplication.java b/src/main/java/shop/mtcoding/metamall/MetamallApplication.java index 487bb62..10d7b6a 100644 --- a/src/main/java/shop/mtcoding/metamall/MetamallApplication.java +++ b/src/main/java/shop/mtcoding/metamall/MetamallApplication.java @@ -4,14 +4,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import shop.mtcoding.metamall.model.orderproduct.OrderProduct; -import shop.mtcoding.metamall.model.orderproduct.OrderProductRepository; -import shop.mtcoding.metamall.model.ordersheet.OrderSheet; -import shop.mtcoding.metamall.model.ordersheet.OrderSheetRepository; +import shop.mtcoding.metamall.model.order.product.OrderProductRepository; +import shop.mtcoding.metamall.model.order.sheet.OrderSheetRepository; import shop.mtcoding.metamall.model.product.ProductRepository; import shop.mtcoding.metamall.model.user.User; import shop.mtcoding.metamall.model.user.UserRepository; +import java.util.Arrays; + @SpringBootApplication public class MetamallApplication { @@ -20,8 +20,10 @@ CommandLineRunner initData(UserRepository userRepository, ProductRepository prod return (args)->{ // 여기에서 save 하면 됨. // bulk Collector는 saveAll 하면 됨. - User ssar = User.builder().username("ssar").password("1234").email("ssar@nate.com").role("USER").build(); - userRepository.save(ssar); + User ssar = User.builder().username("ssar").password("1234").email("ssar@nate.com").role("USER").status(true).build(); + User seller = User.builder().username("seller").password("1234").email("seller@nate.com").role("SELLER").status(true).build(); + User admin = User.builder().username("admin").password("1234").email("admin@nate.com").role("ADMIN").status(true).build(); + userRepository.saveAll(Arrays.asList(ssar, seller, admin)); }; } diff --git a/src/main/java/shop/mtcoding/metamall/config/FilterRegisterConfig.java b/src/main/java/shop/mtcoding/metamall/config/FilterRegisterConfig.java index f5ea4db..dacc480 100644 --- a/src/main/java/shop/mtcoding/metamall/config/FilterRegisterConfig.java +++ b/src/main/java/shop/mtcoding/metamall/config/FilterRegisterConfig.java @@ -12,7 +12,11 @@ public class FilterRegisterConfig { public FilterRegistrationBean jwtVerifyFilterAdd() { FilterRegistrationBean registration = new FilterRegistrationBean<>(); registration.setFilter(new JwtVerifyFilter()); - registration.addUrlPatterns("/user/*"); + registration.addUrlPatterns("/user/*"); // 토큰 + registration.addUrlPatterns("/products/*"); // 토큰 + registration.addUrlPatterns("/orders/*"); // 토큰 + registration.addUrlPatterns("/admin/*"); // ADMIN + registration.addUrlPatterns("/seller/*"); // ADMIN, SELLER registration.setOrder(1); return registration; } diff --git a/src/main/java/shop/mtcoding/metamall/config/MyWebMvcConfig.java b/src/main/java/shop/mtcoding/metamall/config/MyWebMvcConfig.java new file mode 100644 index 0000000..7b61c2f --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/config/MyWebMvcConfig.java @@ -0,0 +1,48 @@ +package shop.mtcoding.metamall.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import shop.mtcoding.metamall.core.interceptor.MyAdminInterceptor; +import shop.mtcoding.metamall.core.interceptor.MySellerInterceptor; +import shop.mtcoding.metamall.core.resolver.MySessionArgumentResolver; + +import java.util.List; + +@Configuration +@RequiredArgsConstructor +public class MyWebMvcConfig implements WebMvcConfigurer { + + private final MyAdminInterceptor adminInterceptor; + private final MySellerInterceptor sellerInterceptor; + private final MySessionArgumentResolver mySessionArgumentResolver; + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedHeaders("*") + .allowedMethods("*") // GET, POST, PUT, DELETE (Javascript 요청 허용) + .allowedOriginPatterns("*") // 모든 IP 주소 허용 (프론트 앤드 IP만 허용하게 변경해야함. * 안됨) + .allowCredentials(true) + .exposedHeaders("Authorization"); // 옛날에는 디폴트로 브라우저에 노출되어 있었는데 지금은 아님 + } + + // AOP는 매개변수 값 확인해서 권한 비교해야할 때 사용 + // Interceptor는 세션 권한으로 체크할 때 사용 + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(adminInterceptor) + .addPathPatterns("/admin/**"); + + registry.addInterceptor(sellerInterceptor) + .addPathPatterns("/seller/**"); + } + + @Override + public void addArgumentResolvers(List resolvers) { + resolvers.add(mySessionArgumentResolver); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/config/WebMvcConfig.java b/src/main/java/shop/mtcoding/metamall/config/WebMvcConfig.java deleted file mode 100644 index 64f5d9b..0000000 --- a/src/main/java/shop/mtcoding/metamall/config/WebMvcConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package shop.mtcoding.metamall.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebMvcConfig implements WebMvcConfigurer { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedHeaders("*") - .allowedMethods("*") // GET, POST, PUT, DELETE (Javascript 요청 허용) - .allowedOriginPatterns("*") // 모든 IP 주소 허용 (프론트 앤드 IP만 허용하게 변경해야함. * 안됨) - .allowCredentials(true) - .exposedHeaders("Authorization"); // 옛날에는 디폴트로 브라우저에 노출되어 있었는데 지금은 아님 - } -} diff --git a/src/main/java/shop/mtcoding/metamall/controller/AdminController.java b/src/main/java/shop/mtcoding/metamall/controller/AdminController.java new file mode 100644 index 0000000..f8bb99f --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/AdminController.java @@ -0,0 +1,37 @@ +package shop.mtcoding.metamall.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; +import shop.mtcoding.metamall.core.exception.Exception400; +import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.user.UserRequest; +import shop.mtcoding.metamall.model.user.User; +import shop.mtcoding.metamall.model.user.UserRepository; + +import javax.validation.Valid; + +/** + * 권한 변경 + */ +@RequiredArgsConstructor +@RestController +public class AdminController { + private final UserRepository userRepository; + + @Transactional // 트랜잭션이 시작되지 않으면 강제로 em.flush() 를 할 수 없고, 더티체킹도 할 수 없다. (원래는 서비스에서) + @PutMapping("/admin/user/{id}/role") + public ResponseEntity updateRole(@PathVariable Long id, @RequestBody @Valid UserRequest.RoleUpdateDTO roleUpdateDTO, Errors errors) { + User userPS = userRepository.findById(id) + .orElseThrow(() -> new Exception400("id", "해당 유저를 찾을 수 없습니다.")); + userPS.updateRole(roleUpdateDTO.getRole()); + + ResponseDto responseDto = new ResponseDto<>(); + return ResponseEntity.ok().body(responseDto); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/controller/OrderController.java b/src/main/java/shop/mtcoding/metamall/controller/OrderController.java new file mode 100644 index 0000000..2c88540 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/OrderController.java @@ -0,0 +1,146 @@ +package shop.mtcoding.metamall.controller; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.*; +import shop.mtcoding.metamall.core.annotation.MySessionStore; +import shop.mtcoding.metamall.core.exception.Exception400; +import shop.mtcoding.metamall.core.exception.Exception403; +import shop.mtcoding.metamall.core.session.SessionUser; +import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.order.OrderRequest; +import shop.mtcoding.metamall.model.order.product.OrderProduct; +import shop.mtcoding.metamall.model.order.product.OrderProductRepository; +import shop.mtcoding.metamall.model.order.sheet.OrderSheet; +import shop.mtcoding.metamall.model.order.sheet.OrderSheetRepository; +import shop.mtcoding.metamall.model.product.Product; +import shop.mtcoding.metamall.model.product.ProductRepository; +import shop.mtcoding.metamall.model.user.User; +import shop.mtcoding.metamall.model.user.UserRepository; + +import javax.validation.Valid; +import java.util.List; + +/** + * 주문하기(고객), 주문목록보기(고객), 주문목록보기(판매자), 주문취소하기(고객), 주문취소하기(판매자) + */ +@Slf4j +@RestController +@RequiredArgsConstructor +public class OrderController { + + private final OrderProductRepository orderProductRepository; + private final OrderSheetRepository orderSheetRepository; + private final ProductRepository productRepository; + private final UserRepository userRepository; + + @Transactional + @PostMapping("/orders") + public ResponseEntity save( + @RequestBody @Valid OrderRequest.SaveDTO saveDTO, Errors errors, + @MySessionStore SessionUser sessionUser) { + // 1. 세션값으로 유저 찾기 + User userPS = userRepository.findById(sessionUser.getId()) + .orElseThrow( + () -> new Exception400("id", "해당 유저를 찾을 수 없습니다.") + ); + + // 2. 상품 찾기 + List productListPS = + productRepository.findAllById(saveDTO.getIds()); + + // 3. 주문 상품 + List orderProductListPS = saveDTO.toEntity(productListPS); + + // 4. 주문서 만들기 + Integer totalPrice = orderProductListPS.stream().mapToInt((orderProduct) -> orderProduct.getOrderPrice()).sum(); + OrderSheet orderSheet = OrderSheet.builder() + .user(userPS) + .totalPrice(totalPrice) + .build(); + OrderSheet orderSheetPS = orderSheetRepository.save(orderSheet); + + // 5. 주문서에 상품추가하고 재고 감소하기 + orderProductListPS.stream().forEach( + (orderProductPS) -> { + orderSheet.addOrderProduct(orderProductPS); + orderProductPS.getProduct().updateQty(orderProductPS.getCount()); + } + ); + + // 6. 응답하기 + ResponseDto responseDto = new ResponseDto<>().data(orderSheet); + return ResponseEntity.ok().body(responseDto); + } + + // 유저 주문서 조회 + @GetMapping("/orders") + public ResponseEntity findByUserId(@MySessionStore SessionUser sessionUser) { + List orderSheetListPS = orderSheetRepository.findByUserId(sessionUser.getId()); + ResponseDto responseDto = new ResponseDto<>().data(orderSheetListPS); + return ResponseEntity.ok().body(responseDto); + } + + // 그림 설명 필요!! + // 배달의 민족은 하나의 판매자에게서만 주문을 할 수 있다. (다른 판매자의 상품이 담기면, 하나만 담을 수 있게 로직이 변한다) + // 쇼핑몰은 여러 판매자에게서 주문을 할 수 있다. + + // 판매자 주문서 조회 + @GetMapping("/seller/orders") + public ResponseEntity findBySellerId() { + // 판매자는 한명이기 때문에 orderProductRepository.findAll() 해도된다. + List orderSheetListPS = orderSheetRepository.findAll(); + ResponseDto responseDto = new ResponseDto<>().data(orderSheetListPS); + return ResponseEntity.ok().body(responseDto); + } + + // 유저 주문 취소 + @DeleteMapping("/orders/{id") + public ResponseEntity delete(@PathVariable Long id, @MySessionStore SessionUser sessionUser) { + // 1. 주문서 찾기 + OrderSheet orderSheetPS = orderSheetRepository.findById(id).orElseThrow( + () -> new Exception400("id", "해당 주문을 찾을 수 없습니다.") + ); + + // 2. 해당 주문서의 주인 여부 확인 + if (!orderSheetPS.getUser().getId().equals(sessionUser.getId())) { + throw new Exception403("권한이 없습니다."); + } + + // 3. 재고 변경하기 + orderSheetPS.getOrderProductList().stream().forEach(orderProduct -> { + orderProduct.getProduct().rollbackQty(orderProduct.getCount()); + }); + + // 4. 주문서 삭제하기 (casecade 옵션) + orderSheetRepository.delete(orderSheetPS); + + // 5. 응답하기 + ResponseDto responseDto = new ResponseDto<>(); + return ResponseEntity.ok().body(responseDto); + } + + // 판매자 주문 취소 + @DeleteMapping("/seller/orders/{id") + public ResponseEntity deleteSeller(@PathVariable Long id) { + // 1. 주문서 찾기 + OrderSheet orderSheetPS = orderSheetRepository.findById(id).orElseThrow( + () -> new Exception400("id", "해당 주문을 찾을 수 없습니다.") + ); + + // 2. 재고 변경하기 + orderSheetPS.getOrderProductList().stream().forEach(orderProduct -> { + orderProduct.getProduct().rollbackQty(orderProduct.getCount()); + }); + + // 3. 주문서 삭제하기 (casecade 옵션) + orderSheetRepository.delete(orderSheetPS); + + // 4. 응답하기 + ResponseDto responseDto = new ResponseDto<>(); + return ResponseEntity.ok().body(responseDto); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/controller/ProductController.java b/src/main/java/shop/mtcoding/metamall/controller/ProductController.java new file mode 100644 index 0000000..e4e9a27 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/ProductController.java @@ -0,0 +1,128 @@ +package shop.mtcoding.metamall.controller; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.*; +import shop.mtcoding.metamall.core.annotation.MySessionStore; +import shop.mtcoding.metamall.core.exception.Exception400; +import shop.mtcoding.metamall.core.session.SessionUser; +import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.product.ProductRequest; +import shop.mtcoding.metamall.model.product.Product; +import shop.mtcoding.metamall.model.product.ProductRepository; +import shop.mtcoding.metamall.model.user.User; +import shop.mtcoding.metamall.model.user.UserRepository; + +import javax.servlet.http.HttpSession; +import javax.validation.Valid; + +/** + * 상품등록, 상품목록보기, 상품상세보기, 상품수정하기, 상품삭제하기 + */ +@Slf4j +@RestController +@RequiredArgsConstructor +public class ProductController { + + private final ProductRepository productRepository; + private final UserRepository userRepository; + private final HttpSession session; + + // 인터셉터가 판매자인지 권한체크를 할 것이니까!! + @PostMapping("/seller/products") + public ResponseEntity save( + @RequestBody @Valid ProductRequest.SaveDTO saveDTO, Errors errors, + @MySessionStore SessionUser sessionUser) { + + // 1. 인증 + + // 2. 판매자 권한 + + // 3. 유효성 검사 통과 +// if (errors.hasErrors()) { +// throw new +// } + + // 4. 판매자가 존재 여부 확인 + + // 5. 상품 등록 + + // 6. 응답 + + + // 1. 판매자 찾기 + User sellerPS = userRepository.findById(sessionUser.getId()) + .orElseThrow( + () -> new Exception400("id", "판매자를 찾을 수 없습니다.") + ); + + // 2. 상품 등록하기 + Product productPS = productRepository.save(saveDTO.toEntity(sellerPS)); + ResponseDto responseDto = new ResponseDto<>().data(productPS); + return ResponseEntity.ok(responseDto); + } + + // http://localhost:8080/products?page=1 + @GetMapping("/products") + public ResponseEntity findAll(@PageableDefault(size = 10, page = 0, direction = Sort.Direction.DESC) Pageable pageable) { + // 1. 상품 찾기 + Page productPagePS = productRepository.findAll(pageable); + + // 2. 응답하기 + ResponseDto responseDto = new ResponseDto<>().data(productPagePS); + return ResponseEntity.ok(responseDto); + } + + @GetMapping("/products/{id}") + public ResponseEntity findById(@PathVariable Long id) { + // 1. 상품 찾기 + Product productPS = productRepository.findById(id).orElseThrow(() -> { + throw new Exception400("id", "해당 상품을 찾을 수 없습니다."); + }); + + // 2. 응답하기 + ResponseDto responseDto = new ResponseDto<>().data(productPS); + return ResponseEntity.ok(responseDto); + } + + @Transactional // 더티체킹 하고 싶다면 붙이기!! + @PutMapping("/seller/products/{id}") + public ResponseEntity update(@PathVariable Long id, + @RequestBody @Valid ProductRequest.UpdateDTO updateDTO, + Errors errors) { + // 1. 상품 찾기 + Product productPS = productRepository.findById(id).orElseThrow(() -> { + throw new Exception400("id", "해당 상품을 찾을 수 없습니다."); + }); + + // 2. Update 더티체킹 + productPS.update(updateDTO.getName(), updateDTO.getPrice(), updateDTO.getQty()); + + // em.flush(); // controller 레이어에서 작동 안함!! (거부) + // productRepository.save(productPS); // em.merge() 가 실행됨 + + // 3. 응답하기 + ResponseDto responseDto = new ResponseDto<>().data(productPS); + return ResponseEntity.ok(responseDto); + } // 종료시에 트랜잭션 종료 - 변경감지 -> flush + + @DeleteMapping("/seller/products/{id}") + public ResponseEntity deleteById(@PathVariable Long id) { + + // productRepository.deleteById(id); // 잠깐 delete하는 동안 DB에 락이 걸려서, 다른 쓰레드는 이 시간동안 insert, update, delete 못함 + + Product productPS = productRepository.findById(id).orElseThrow(() -> { + throw new Exception400("id", "해당 상품을 찾을 수 없습니다."); + }); + productRepository.delete(productPS); + ResponseDto responseDto = new ResponseDto<>().data(productPS); + return ResponseEntity.ok(responseDto); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/controller/UserController.java b/src/main/java/shop/mtcoding/metamall/controller/UserController.java index ddfee94..1a5e01a 100644 --- a/src/main/java/shop/mtcoding/metamall/controller/UserController.java +++ b/src/main/java/shop/mtcoding/metamall/controller/UserController.java @@ -2,13 +2,13 @@ import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; +import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; import shop.mtcoding.metamall.core.exception.Exception400; import shop.mtcoding.metamall.core.exception.Exception401; import shop.mtcoding.metamall.core.jwt.JwtProvider; import shop.mtcoding.metamall.dto.ResponseDto; import shop.mtcoding.metamall.dto.user.UserRequest; -import shop.mtcoding.metamall.dto.user.UserResponse; import shop.mtcoding.metamall.model.log.login.LoginLog; import shop.mtcoding.metamall.model.log.login.LoginLogRepository; import shop.mtcoding.metamall.model.user.User; @@ -16,6 +16,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import javax.validation.Valid; import java.time.LocalDateTime; import java.util.Optional; @@ -27,15 +28,27 @@ public class UserController { private final LoginLogRepository loginLogRepository; private final HttpSession session; + // 핵심 로직 + @PostMapping("/join") + public ResponseEntity join(@RequestBody @Valid UserRequest.JoinDTO joinDTO, Errors errors) { + User userPS = userRepository.save(joinDTO.toEntity()); + // RestAPI는 insert, update, select 된 모든 데이터를 응답해줘야 한다. + ResponseDto responseDto = new ResponseDto<>().data(userPS); + return ResponseEntity.ok(responseDto); + } + @PostMapping("/login") - public ResponseEntity login(@RequestBody UserRequest.LoginDto loginDto, HttpServletRequest request) { - Optional userOP = userRepository.findByUsername(loginDto.getUsername()); + public ResponseEntity login( + @RequestBody @Valid UserRequest.LoginDTO loginDTO, + Errors errors, + HttpServletRequest request) { + Optional userOP = userRepository.findByUsername(loginDTO.getUsername()); if (userOP.isPresent()) { // 1. 유저 정보 꺼내기 User loginUser = userOP.get(); // 2. 패스워드 검증하기 - if(!loginUser.getPassword().equals(loginDto.getPassword())){ + if(!loginUser.getPassword().equals(loginDTO.getPassword())){ throw new Exception401("인증되지 않았습니다"); } @@ -57,7 +70,8 @@ public ResponseEntity login(@RequestBody UserRequest.LoginDto loginDto, HttpS ResponseDto responseDto = new ResponseDto<>().data(loginUser); return ResponseEntity.ok().header(JwtProvider.HEADER, jwt).body(responseDto); } else { - throw new Exception400("유저네임 혹은 아이디가 잘못되었습니다"); + // checkpoint + throw new Exception400("", "유저네임 혹은 아이디가 잘못되었습니다"); } } } diff --git a/src/main/java/shop/mtcoding/metamall/core/advice/MyErrorLogAdvice.java b/src/main/java/shop/mtcoding/metamall/core/advice/MyErrorLogAdvice.java new file mode 100644 index 0000000..821aa5a --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyErrorLogAdvice.java @@ -0,0 +1,43 @@ +package shop.mtcoding.metamall.core.advice; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.stereotype.Component; +import shop.mtcoding.metamall.core.session.SessionUser; +import shop.mtcoding.metamall.model.log.error.ErrorLog; +import shop.mtcoding.metamall.model.log.error.ErrorLogRepository; + +import javax.servlet.http.HttpSession; + +@Aspect +@Component +@RequiredArgsConstructor +@Slf4j +public class MyErrorLogAdvice { + + private final HttpSession session; + private final ErrorLogRepository errorLogRepository; + + @Pointcut("@annotation(shop.mtcoding.metamall.core.annotation.MyErrorLogRecord)") + public void myErrorLog() {} + + @Before("myErrorLog()") + public void errorLogAdvice(JoinPoint jp) { + Object[] args = jp.getArgs(); + + for (Object arg : args) { + if (arg instanceof Exception) { + Exception e = (Exception) arg; + SessionUser sessionUser = (SessionUser) session.getAttribute("sessionUser"); + if (sessionUser != null) { + ErrorLog errorLog = ErrorLog.builder().userId(sessionUser.getId()).msg(e.getMessage()).build(); + errorLogRepository.save(errorLog); + } + } + } + } +} diff --git a/src/main/java/shop/mtcoding/metamall/core/advice/MyExceptionAdvice.java b/src/main/java/shop/mtcoding/metamall/core/advice/MyExceptionAdvice.java index 50ebee2..736ee80 100644 --- a/src/main/java/shop/mtcoding/metamall/core/advice/MyExceptionAdvice.java +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyExceptionAdvice.java @@ -2,41 +2,60 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.NoHandlerFoundException; +import shop.mtcoding.metamall.core.annotation.MyErrorLogRecord; import shop.mtcoding.metamall.core.exception.*; +import shop.mtcoding.metamall.dto.ResponseDto; import shop.mtcoding.metamall.model.log.error.ErrorLogRepository; @Slf4j -@RequiredArgsConstructor @RestControllerAdvice public class MyExceptionAdvice { - private final ErrorLogRepository errorLogRepository; - + @MyErrorLogRecord @ExceptionHandler(Exception400.class) public ResponseEntity badRequest(Exception400 e){ + // trace -> debug -> info -> warn -> error + log.debug("디버그 : " + e.getMessage()); + log.info("인포 : " + e.getMessage()); + log.warn("경고 : " + e.getMessage()); + log.error("에러 : " + e.getMessage()); return new ResponseEntity<>(e.body(), e.status()); } + @MyErrorLogRecord @ExceptionHandler(Exception401.class) public ResponseEntity unAuthorized(Exception401 e){ + log.debug("디버그 : " + e.getMessage()); return new ResponseEntity<>(e.body(), e.status()); } + @MyErrorLogRecord @ExceptionHandler(Exception403.class) public ResponseEntity forbidden(Exception403 e){ + log.debug("디버그 : " + e.getMessage()); return new ResponseEntity<>(e.body(), e.status()); } - @ExceptionHandler(Exception404.class) - public ResponseEntity notFound(Exception404 e){ - return new ResponseEntity<>(e.body(), e.status()); + @MyErrorLogRecord + @ExceptionHandler(NoHandlerFoundException.class) + public ResponseEntity notFound(NoHandlerFoundException e) { + log.debug("디버그 : " + e.getMessage()); + ResponseDto responseDto = new ResponseDto<>(); + responseDto.fail(HttpStatus.NOT_FOUND, "notFound", e.getMessage()); + return new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND); } - @ExceptionHandler(Exception500.class) - public ResponseEntity serverError(Exception500 e){ - return new ResponseEntity<>(e.body(), e.status()); + // 나머지 모든 예외는 이 친구에게 다 걸러진다. + @MyErrorLogRecord + @ExceptionHandler(Exception.class) + public ResponseEntity exception(Exception e) { + ResponseDto responseDto = new ResponseDto<>(); + responseDto.fail(HttpStatus.INTERNAL_SERVER_ERROR, "unknownServerError", e.getMessage()); + return new ResponseEntity<>(responseDto, HttpStatus.INTERNAL_SERVER_ERROR); } } diff --git a/src/main/java/shop/mtcoding/metamall/core/advice/MySameUserIdAdvice.java b/src/main/java/shop/mtcoding/metamall/core/advice/MySameUserIdAdvice.java new file mode 100644 index 0000000..ee47cff --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MySameUserIdAdvice.java @@ -0,0 +1,5 @@ +package shop.mtcoding.metamall.core.advice; + +// 쓸일 없다. +public class MySameUserIdAdvice { +} diff --git a/src/main/java/shop/mtcoding/metamall/core/advice/MyValidAdvice.java b/src/main/java/shop/mtcoding/metamall/core/advice/MyValidAdvice.java new file mode 100644 index 0000000..13fa259 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyValidAdvice.java @@ -0,0 +1,45 @@ +package shop.mtcoding.metamall.core.advice; + +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import shop.mtcoding.metamall.core.exception.Exception400; +import shop.mtcoding.metamall.core.session.SessionUser; +import shop.mtcoding.metamall.model.log.error.ErrorLog; +import shop.mtcoding.metamall.model.log.error.ErrorLogRepository; + +import javax.servlet.http.HttpSession; + +@Aspect +@Component +public class MyValidAdvice { + + @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)") + public void postMapping() {} + + @Pointcut("@annotation(org.springframework.web.bind.annotation.PutMapping)") + public void putMapping() {} + + @Before("postMapping() || putMapping()") + public void validationAdvice(JoinPoint jp) { + Object[] args = jp.getArgs(); + + for (Object arg : args) { + if (arg instanceof Errors) { + Errors errors = (Errors) arg; + + if (errors.hasErrors()) { + throw new Exception400( + errors.getFieldErrors().get(0).getField(), + errors.getFieldErrors().get(0).getDefaultMessage() + ); + } + } + } + } + +} diff --git a/src/main/java/shop/mtcoding/metamall/core/annotation/MyErrorLogRecord.java b/src/main/java/shop/mtcoding/metamall/core/annotation/MyErrorLogRecord.java new file mode 100644 index 0000000..6c8ae48 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/annotation/MyErrorLogRecord.java @@ -0,0 +1,11 @@ +package shop.mtcoding.metamall.core.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface MyErrorLogRecord { +} diff --git a/src/main/java/shop/mtcoding/metamall/core/annotation/MySameUserIdCheck.java b/src/main/java/shop/mtcoding/metamall/core/annotation/MySameUserIdCheck.java new file mode 100644 index 0000000..6562ec1 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/annotation/MySameUserIdCheck.java @@ -0,0 +1,11 @@ +package shop.mtcoding.metamall.core.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface MySameUserIdCheck { +} diff --git a/src/main/java/shop/mtcoding/metamall/core/annotation/MySessionStore.java b/src/main/java/shop/mtcoding/metamall/core/annotation/MySessionStore.java new file mode 100644 index 0000000..8cebe68 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/annotation/MySessionStore.java @@ -0,0 +1,12 @@ +package shop.mtcoding.metamall.core.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +// 세션값을 자동 주입해준다. +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface MySessionStore { +} diff --git a/src/main/java/shop/mtcoding/metamall/core/exception/Exception400.java b/src/main/java/shop/mtcoding/metamall/core/exception/Exception400.java index d1b5fec..8dda935 100644 --- a/src/main/java/shop/mtcoding/metamall/core/exception/Exception400.java +++ b/src/main/java/shop/mtcoding/metamall/core/exception/Exception400.java @@ -3,18 +3,28 @@ import lombok.Getter; import org.springframework.http.HttpStatus; import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.ValidDto; +// username = fgkjdfogijerlgkj +// "username" : "유저네임이 너무 길어요." -// 유효성 실패 +// 유효성 실패(잘못된 메서드 요청), 잘못된 파라메터 요청(Pathvariable) @Getter public class Exception400 extends RuntimeException { - public Exception400(String message) { - super(message); + + private String key; + private String value; + + public Exception400(String key, String value) { + super(value); + this.key = key; + this.value = value; } public ResponseDto body(){ - ResponseDto responseDto = new ResponseDto<>(); - responseDto.fail(HttpStatus.BAD_REQUEST, "badRequest", getMessage()); + ResponseDto responseDto = new ResponseDto<>(); + ValidDto validDto = new ValidDto(key, value); + responseDto.fail(HttpStatus.BAD_REQUEST, "badRequest", validDto); return responseDto; } diff --git a/src/main/java/shop/mtcoding/metamall/core/exception/Exception404.java b/src/main/java/shop/mtcoding/metamall/core/exception/Exception404.java deleted file mode 100644 index c20b64f..0000000 --- a/src/main/java/shop/mtcoding/metamall/core/exception/Exception404.java +++ /dev/null @@ -1,24 +0,0 @@ -package shop.mtcoding.metamall.core.exception; - -import lombok.Getter; -import org.springframework.http.HttpStatus; -import shop.mtcoding.metamall.dto.ResponseDto; - - -// 리소스 없음 -@Getter -public class Exception404 extends RuntimeException { - public Exception404(String message) { - super(message); - } - - public ResponseDto body(){ - ResponseDto responseDto = new ResponseDto<>(); - responseDto.fail(HttpStatus.NOT_FOUND, "notFound", getMessage()); - return responseDto; - } - - public HttpStatus status(){ - return HttpStatus.NOT_FOUND; - } -} \ No newline at end of file diff --git a/src/main/java/shop/mtcoding/metamall/core/exception/Exception500.java b/src/main/java/shop/mtcoding/metamall/core/exception/Exception500.java deleted file mode 100644 index d3d4468..0000000 --- a/src/main/java/shop/mtcoding/metamall/core/exception/Exception500.java +++ /dev/null @@ -1,24 +0,0 @@ -package shop.mtcoding.metamall.core.exception; - -import lombok.Getter; -import org.springframework.http.HttpStatus; -import shop.mtcoding.metamall.dto.ResponseDto; - - -// 서버 에러 -@Getter -public class Exception500 extends RuntimeException { - public Exception500(String message) { - super(message); - } - - public ResponseDto body(){ - ResponseDto responseDto = new ResponseDto<>(); - responseDto.fail(HttpStatus.INTERNAL_SERVER_ERROR, "serverError", getMessage()); - return responseDto; - } - - public HttpStatus status(){ - return HttpStatus.INTERNAL_SERVER_ERROR; - } -} \ No newline at end of file diff --git a/src/main/java/shop/mtcoding/metamall/core/filter/JwtVerifyFilter.java b/src/main/java/shop/mtcoding/metamall/core/filter/JwtVerifyFilter.java index 870bf93..e191939 100644 --- a/src/main/java/shop/mtcoding/metamall/core/filter/JwtVerifyFilter.java +++ b/src/main/java/shop/mtcoding/metamall/core/filter/JwtVerifyFilter.java @@ -7,8 +7,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.HttpStatus; import shop.mtcoding.metamall.core.exception.Exception400; +import shop.mtcoding.metamall.core.exception.Exception401; import shop.mtcoding.metamall.core.jwt.JwtProvider; -import shop.mtcoding.metamall.core.session.LoginUser; +import shop.mtcoding.metamall.core.session.SessionUser; +import shop.mtcoding.metamall.core.util.MyFilterResponseUtil; import shop.mtcoding.metamall.dto.ResponseDto; import javax.servlet.*; @@ -17,6 +19,7 @@ import javax.servlet.http.HttpSession; import java.io.IOException; +// 인증 체크 public class JwtVerifyFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { @@ -24,35 +27,27 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String prefixJwt = req.getHeader(JwtProvider.HEADER); + if(prefixJwt == null){ - error(resp, new Exception400("토큰이 전달되지 않았습니다")); + MyFilterResponseUtil.badRequest(resp, new Exception400("authorization", "토큰이 전달되지 않았습니다.")); return; } String jwt = prefixJwt.replace(JwtProvider.TOKEN_PREFIX, ""); try { DecodedJWT decodedJWT = JwtProvider.verify(jwt); - int id = decodedJWT.getClaim("id").asInt(); + Long id = decodedJWT.getClaim("id").asLong(); String role = decodedJWT.getClaim("role").asString(); // 세션을 사용하는 이유는 권한처리를 하기 위해서이다. HttpSession session = req.getSession(); - LoginUser loginUser = LoginUser.builder().id(id).role(role).build(); - session.setAttribute("loginUser", loginUser); + SessionUser sessionUser = SessionUser.builder().id(id).role(role).build(); + session.setAttribute("sessionUser", sessionUser); chain.doFilter(req, resp); }catch (SignatureVerificationException sve){ - error(resp, sve); + MyFilterResponseUtil.unAuthorized(resp, sve); }catch (TokenExpiredException tee){ - error(resp, tee); - } - } + MyFilterResponseUtil.unAuthorized(resp, tee); - private void error(HttpServletResponse resp, Exception e) throws IOException { - resp.setStatus(401); - resp.setContentType("application/json; charset=utf-8"); - ResponseDto responseDto = new ResponseDto<>().fail(HttpStatus.UNAUTHORIZED, "인증 안됨", e.getMessage()); - ObjectMapper om = new ObjectMapper(); - String responseBody = om.writeValueAsString(responseDto); - resp.getWriter().println(responseBody); + } } - } diff --git a/src/main/java/shop/mtcoding/metamall/core/interceptor/MyAdminInterceptor.java b/src/main/java/shop/mtcoding/metamall/core/interceptor/MyAdminInterceptor.java new file mode 100644 index 0000000..08d74de --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/interceptor/MyAdminInterceptor.java @@ -0,0 +1,25 @@ +package shop.mtcoding.metamall.core.interceptor; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerInterceptor; +import shop.mtcoding.metamall.core.exception.Exception403; +import shop.mtcoding.metamall.core.session.SessionUser; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +@Configuration +public class MyAdminInterceptor implements HandlerInterceptor { + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + HttpSession session = request.getSession(); + SessionUser sessionUser = (SessionUser) session.getAttribute("sessionUser"); + + if (sessionUser.getRole().equals("ADMIN")) { + return true; + } else { + throw new Exception403("권한이 없습니다"); + } + } +} diff --git a/src/main/java/shop/mtcoding/metamall/core/interceptor/MySellerInterceptor.java b/src/main/java/shop/mtcoding/metamall/core/interceptor/MySellerInterceptor.java new file mode 100644 index 0000000..fc930e0 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/interceptor/MySellerInterceptor.java @@ -0,0 +1,26 @@ +package shop.mtcoding.metamall.core.interceptor; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerInterceptor; +import shop.mtcoding.metamall.core.exception.Exception403; +import shop.mtcoding.metamall.core.session.SessionUser; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +@Configuration +public class MySellerInterceptor implements HandlerInterceptor { + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + + HttpSession session = request.getSession(); + SessionUser sessionUser = (SessionUser) session.getAttribute("sessionUser"); + + if (sessionUser.getRole().equals("SELLER") || sessionUser.getRole().equals("ADMIN")) { + return true; + } else { + throw new Exception403("권한이 없습니다"); + } + } +} diff --git a/src/main/java/shop/mtcoding/metamall/core/resolver/MySessionArgumentResolver.java b/src/main/java/shop/mtcoding/metamall/core/resolver/MySessionArgumentResolver.java new file mode 100644 index 0000000..8b87161 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/resolver/MySessionArgumentResolver.java @@ -0,0 +1,32 @@ +package shop.mtcoding.metamall.core.resolver; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.MethodParameter; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; +import shop.mtcoding.metamall.core.annotation.MySessionStore; +import shop.mtcoding.metamall.core.session.SessionUser; + +import javax.servlet.http.HttpSession; + +@Configuration +@RequiredArgsConstructor +public class MySessionArgumentResolver implements HandlerMethodArgumentResolver { + + private final HttpSession session; + + @Override + public boolean supportsParameter(MethodParameter parameter) { + boolean check1 = parameter.getParameterAnnotation(MySessionStore.class) != null; + boolean check2 = SessionUser.class.equals(parameter.getParameterType()); + return check1 && check2; + } + + @Override + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { + return session.getAttribute("sessionUser"); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/core/session/LoginUser.java b/src/main/java/shop/mtcoding/metamall/core/session/SessionUser.java similarity index 66% rename from src/main/java/shop/mtcoding/metamall/core/session/LoginUser.java rename to src/main/java/shop/mtcoding/metamall/core/session/SessionUser.java index 59f402c..20b138b 100644 --- a/src/main/java/shop/mtcoding/metamall/core/session/LoginUser.java +++ b/src/main/java/shop/mtcoding/metamall/core/session/SessionUser.java @@ -4,12 +4,12 @@ import lombok.Getter; @Getter -public class LoginUser { - private Integer id; +public class SessionUser { + private Long id; private String role; @Builder - public LoginUser(Integer id, String role) { + public SessionUser(Long id, String role) { this.id = id; this.role = role; } diff --git a/src/main/java/shop/mtcoding/metamall/util/MyDateUtil.java b/src/main/java/shop/mtcoding/metamall/core/util/MyDateUtil.java similarity index 86% rename from src/main/java/shop/mtcoding/metamall/util/MyDateUtil.java rename to src/main/java/shop/mtcoding/metamall/core/util/MyDateUtil.java index 42ba271..3f92cf6 100644 --- a/src/main/java/shop/mtcoding/metamall/util/MyDateUtil.java +++ b/src/main/java/shop/mtcoding/metamall/core/util/MyDateUtil.java @@ -1,4 +1,4 @@ -package shop.mtcoding.metamall.util; +package shop.mtcoding.metamall.core.util; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; diff --git a/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java b/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java new file mode 100644 index 0000000..7c7f783 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java @@ -0,0 +1,42 @@ +package shop.mtcoding.metamall.core.util; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.HttpStatus; +import shop.mtcoding.metamall.core.exception.Exception400; +import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.ValidDto; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +// Filter는 예외 핸들러로 처리 못한다. +public class MyFilterResponseUtil { + + public static void badRequest(HttpServletResponse resp, Exception400 e) throws IOException { + resp.setStatus(400); + resp.setContentType("application/json; charset=utf-8"); + ValidDto validDto = new ValidDto(e.getKey(), e.getValue()); + ResponseDto responseDto = new ResponseDto<>().fail(HttpStatus.BAD_REQUEST, "badRequest", validDto); + ObjectMapper om = new ObjectMapper(); + String responseBody = om.writeValueAsString(responseDto); + resp.getWriter().println(responseBody); + } + + public static void unAuthorized(HttpServletResponse resp, Exception e) throws IOException { + resp.setStatus(401); + resp.setContentType("application/json; charset=utf-8"); + ResponseDto responseDto = new ResponseDto<>().fail(HttpStatus.UNAUTHORIZED, "unAuthorized", e.getMessage()); + ObjectMapper om = new ObjectMapper(); + String responseBody = om.writeValueAsString(responseDto); + resp.getWriter().println(responseBody); + } + + public static void forbidden(HttpServletResponse resp, Exception e) throws IOException { + resp.setStatus(403); + resp.setContentType("application/json; charset=utf-8"); + ResponseDto responseDto = new ResponseDto<>().fail(HttpStatus.FORBIDDEN, "forbiden", e.getMessage()); + ObjectMapper om = new ObjectMapper(); + String responseBody = om.writeValueAsString(responseDto); + resp.getWriter().println(responseBody); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java b/src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java index 7f190c6..d343121 100644 --- a/src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java +++ b/src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java @@ -9,17 +9,20 @@ public class ResponseDto { private String msg; // 에러시에 의미 있음. ex) badRequest private T data; // 에러시에는 구체적인 에러 내용 ex) username이 입력되지 않았습니다 + // delete 요청 - 성공 public ResponseDto(){ this.status = HttpStatus.OK.value(); this.msg = "성공"; this.data = null; } + // get, post, put - 성공 public ResponseDto data(T data){ this.data = data; // 응답할 데이터 바디 return this; } + // 4가지 요청에 대한 실패 public ResponseDto fail(HttpStatus httpStatus, String msg, T data){ this.status = httpStatus.value(); this.msg = msg; // 에러 제목 diff --git a/src/main/java/shop/mtcoding/metamall/dto/ValidDto.java b/src/main/java/shop/mtcoding/metamall/dto/ValidDto.java new file mode 100644 index 0000000..3edf7b3 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/ValidDto.java @@ -0,0 +1,13 @@ +package shop.mtcoding.metamall.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class ValidDto { + private String key; + private String value; +} diff --git a/src/main/java/shop/mtcoding/metamall/dto/order/OrderRequest.java b/src/main/java/shop/mtcoding/metamall/dto/order/OrderRequest.java new file mode 100644 index 0000000..5efbef5 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/order/OrderRequest.java @@ -0,0 +1,51 @@ +package shop.mtcoding.metamall.dto.order; + +import lombok.Getter; +import lombok.Setter; +import shop.mtcoding.metamall.model.order.product.OrderProduct; +import shop.mtcoding.metamall.model.product.Product; + +import java.util.List; +import java.util.stream.Collectors; + +public class OrderRequest { + @Getter + @Setter + public static class SaveDTO { + + private List orderProducts; + + @Getter + @Setter + public static class OrderProductDTO { + private Long productId; + private Integer count; + } + + // 1. request 요청으로 들어온 product id만 리스트로 뽑아내기 + public List getIds() { + return orderProducts.stream().map((orderProduct) -> orderProduct.getProductId()).collect(Collectors.toList()); + } + + // 3. 주문 상품 리스트 만들어 내기 + public List toEntity(List products) { // 2. getIds() 로 뽑아낸 번호로 상품 리스트 찾아내서 주입하기 + + // 4. request 요청으로 들어온 DTO에 count 값이 필요해서 stream() 두번 돌렸음. 주문 상품 금액을 만들어 내야 해서!! + return orderProducts.stream() + // 5. map은 다시 collect로 수집해야 하기 때문에, flatMap으로 평탄화 작업함. + .flatMap((orderProduct) -> { + Long productId = orderProduct.productId; + Integer count = orderProduct.getCount(); + // 6. OrderProduct 객체 만들어내기 (주문한 상품만큼) + return products.stream() + .filter((product) -> product.getId().equals(productId)) + .map((product) -> OrderProduct.builder() + .product(product) + .count(count) + .orderPrice(product.getPrice() * count) + .build()); + } + ).collect(Collectors.toList()); // 7. 최종 수집 + } + } +} \ No newline at end of file diff --git a/src/main/java/shop/mtcoding/metamall/dto/order/OrderResponse.java b/src/main/java/shop/mtcoding/metamall/dto/order/OrderResponse.java new file mode 100644 index 0000000..8888af8 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/order/OrderResponse.java @@ -0,0 +1,4 @@ +package shop.mtcoding.metamall.dto.order; + +public class OrderResponse { +} diff --git a/src/main/java/shop/mtcoding/metamall/dto/product/ProductRequest.java b/src/main/java/shop/mtcoding/metamall/dto/product/ProductRequest.java new file mode 100644 index 0000000..8be4627 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/product/ProductRequest.java @@ -0,0 +1,51 @@ +package shop.mtcoding.metamall.dto.product; + +import lombok.Getter; +import lombok.Setter; +import shop.mtcoding.metamall.model.product.Product; +import shop.mtcoding.metamall.model.user.User; + +import javax.validation.constraints.Digits; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +public class ProductRequest { + + @Getter @Setter + public static class SaveDTO { + @NotEmpty + private String name; + + // 숫자는 NotNull로 검증한다 + @Digits(fraction = 0, integer = 9) + @NotNull + private Integer price; + + @Digits(fraction = 0, integer = 9) + @NotNull + private Integer qty; + + public Product toEntity(User seller){ + return Product.builder() + .name(name) + .price(price) + .qty(qty) + .seller(seller) + .build(); + } + } + + @Getter @Setter + public static class UpdateDTO { + @NotEmpty + private String name; + + @Digits(fraction = 0, integer = 9) + @NotNull + private Integer price; + + @Digits(fraction = 0, integer = 9) + @NotNull + private Integer qty; + } +} diff --git a/src/main/java/shop/mtcoding/metamall/dto/product/ProductResponse.java b/src/main/java/shop/mtcoding/metamall/dto/product/ProductResponse.java new file mode 100644 index 0000000..11d3e67 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/product/ProductResponse.java @@ -0,0 +1,4 @@ +package shop.mtcoding.metamall.dto.product; + +public class ProductResponse { +} diff --git a/src/main/java/shop/mtcoding/metamall/dto/user/UserRequest.java b/src/main/java/shop/mtcoding/metamall/dto/user/UserRequest.java index 80947db..8a4b8c0 100644 --- a/src/main/java/shop/mtcoding/metamall/dto/user/UserRequest.java +++ b/src/main/java/shop/mtcoding/metamall/dto/user/UserRequest.java @@ -2,11 +2,61 @@ import lombok.Getter; import lombok.Setter; +import shop.mtcoding.metamall.model.user.User; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; public class UserRequest { + @Getter @Setter - public static class LoginDto { + public static class JoinDTO { + + // Size는 String에만 쓸 수 있다. + @NotEmpty + @Size(min = 3, max = 20) private String username; + + @NotEmpty + @Size(min = 4, max = 20) // DB에는 60자, 실제 받을 때는 20자 이하 private String password; + + // Pattern은 String에만 쓸 수 있다. + @NotEmpty + @Pattern(regexp = "^[\\w._%+-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$", message = "이메일 형식이 아닙니다") + private String email; + + @NotEmpty + @Pattern(regexp = "USER|SELLER|ADMIN") + private String role; + + // Insert DTO만 toEntity 를 만들면 된다. + public User toEntity(){ + return User.builder() + .username(username) + .password(password) + .email(email) + .role(role) + .status(true) + .build(); + } } + + @Getter @Setter + public static class LoginDTO { + @NotEmpty + private String username; + @NotEmpty + private String password; + } + + @Getter @Setter + public static class RoleUpdateDTO { + @NotEmpty + @Pattern(regexp = "USER|SELLER|ADMIN") + private String role; + } + } + diff --git a/src/main/java/shop/mtcoding/metamall/model/log/error/ErrorLog.java b/src/main/java/shop/mtcoding/metamall/model/log/error/ErrorLog.java index fbfe7e5..41dad1d 100644 --- a/src/main/java/shop/mtcoding/metamall/model/log/error/ErrorLog.java +++ b/src/main/java/shop/mtcoding/metamall/model/log/error/ErrorLog.java @@ -17,6 +17,7 @@ public class ErrorLog { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(nullable = false, length = 100000) private String msg; private Long userId; diff --git a/src/main/java/shop/mtcoding/metamall/model/orderproduct/OrderProduct.java b/src/main/java/shop/mtcoding/metamall/model/order/product/OrderProduct.java similarity index 73% rename from src/main/java/shop/mtcoding/metamall/model/orderproduct/OrderProduct.java rename to src/main/java/shop/mtcoding/metamall/model/order/product/OrderProduct.java index 165905e..580e271 100644 --- a/src/main/java/shop/mtcoding/metamall/model/orderproduct/OrderProduct.java +++ b/src/main/java/shop/mtcoding/metamall/model/order/product/OrderProduct.java @@ -1,10 +1,11 @@ -package shop.mtcoding.metamall.model.orderproduct; +package shop.mtcoding.metamall.model.order.product; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import shop.mtcoding.metamall.model.ordersheet.OrderSheet; +import shop.mtcoding.metamall.model.order.sheet.OrderSheet; import shop.mtcoding.metamall.model.product.Product; import javax.persistence.*; @@ -19,16 +20,30 @@ public class OrderProduct { // 주문 상품 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + // checkpoint -> 무한참조 + @JsonIgnoreProperties("seller") @ManyToOne private Product product; + + @Column(nullable = false) private Integer count; // 상품 주문 개수 + + @Column(nullable = false) private Integer orderPrice; // 상품 주문 금액 + + @Column(nullable = false) private LocalDateTime createdAt; private LocalDateTime updatedAt; @ManyToOne private OrderSheet orderSheet; + // checkpoint -> 편의 메서드 만드는 이유 + public void syncOrderSheet(OrderSheet orderSheet) { + this.orderSheet = orderSheet; + } + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); diff --git a/src/main/java/shop/mtcoding/metamall/model/orderproduct/OrderProductRepository.java b/src/main/java/shop/mtcoding/metamall/model/order/product/OrderProductRepository.java similarity index 74% rename from src/main/java/shop/mtcoding/metamall/model/orderproduct/OrderProductRepository.java rename to src/main/java/shop/mtcoding/metamall/model/order/product/OrderProductRepository.java index 6f1238c..1b686dc 100644 --- a/src/main/java/shop/mtcoding/metamall/model/orderproduct/OrderProductRepository.java +++ b/src/main/java/shop/mtcoding/metamall/model/order/product/OrderProductRepository.java @@ -1,4 +1,4 @@ -package shop.mtcoding.metamall.model.orderproduct; +package shop.mtcoding.metamall.model.order.product; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheet.java b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheet.java similarity index 65% rename from src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheet.java rename to src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheet.java index 7638710..cb493d1 100644 --- a/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheet.java +++ b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheet.java @@ -1,11 +1,11 @@ -package shop.mtcoding.metamall.model.ordersheet; +package shop.mtcoding.metamall.model.order.sheet; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import shop.mtcoding.metamall.model.orderproduct.OrderProduct; -import shop.mtcoding.metamall.model.product.Product; +import shop.mtcoding.metamall.model.order.product.OrderProduct; import shop.mtcoding.metamall.model.user.User; import javax.persistence.*; @@ -22,14 +22,32 @@ public class OrderSheet { // 주문서 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @ManyToOne private User user; // 주문자 - @OneToMany(mappedBy = "orderSheet") + + // checkpoint -> 무한참조 + @JsonIgnoreProperties("orderSheet") + @OneToMany(mappedBy = "orderSheet", cascade = CascadeType.ALL, orphanRemoval = true) private List orderProductList = new ArrayList<>(); // 총 주문 상품 리스트 + + @Column(nullable = false) private Integer totalPrice; // 총 주문 금액 (총 주문 상품 리스트의 orderPrice 합) + + @Column(nullable = false) private LocalDateTime createdAt; private LocalDateTime updatedAt; + public void addOrderProduct(OrderProduct orderProduct) { + orderProductList.add(orderProduct); + orderProduct.syncOrderSheet(this); + } + + public void removeOrderProduct(OrderProduct orderProduct) { + orderProductList.remove(orderProduct); + orderProduct.syncOrderSheet(null); + } + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); diff --git a/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java new file mode 100644 index 0000000..575834b --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java @@ -0,0 +1,13 @@ +package shop.mtcoding.metamall.model.order.sheet; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface OrderSheetRepository extends JpaRepository { + // 내가 주문한 목록보기 + @Query("select os from OrderSheet os where os.user.id = :userId") + List findByUserId(@Param("userId") Long userId); +} diff --git a/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheetRepository.java b/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheetRepository.java deleted file mode 100644 index 5d59249..0000000 --- a/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheetRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package shop.mtcoding.metamall.model.ordersheet; - -import org.springframework.data.jpa.repository.JpaRepository; - -public interface OrderSheetRepository extends JpaRepository { -} diff --git a/src/main/java/shop/mtcoding/metamall/model/product/Product.java b/src/main/java/shop/mtcoding/metamall/model/product/Product.java index bc8c618..9c89182 100644 --- a/src/main/java/shop/mtcoding/metamall/model/product/Product.java +++ b/src/main/java/shop/mtcoding/metamall/model/product/Product.java @@ -1,9 +1,11 @@ package shop.mtcoding.metamall.model.product; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import shop.mtcoding.metamall.model.user.User; import javax.persistence.*; import java.time.LocalDateTime; @@ -17,12 +19,43 @@ public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + @ManyToOne(fetch = FetchType.EAGER) + private User seller; // seller_id + + @Column(nullable = false, length = 50) private String name; // 상품 이름 + + @Column(nullable = false) private Integer price; // 상품 가격 + + @Column(nullable = false) private Integer qty; // 상품 재고 + + @Column(nullable = false) private LocalDateTime createdAt; private LocalDateTime updatedAt; + // 판매자 상품 변경 + public void update(String name, Integer price, Integer qty) { + this.name = name; + this.price = price; + this.qty = qty; + } + + // 주문시 재고 변경 (구매자) + public void updateQty(Integer orderCount) { + if (this.qty < orderCount) { + // checkpoint 주문수량이 재고 수량을 초과하였습니다. + } + this.qty -= orderCount; + } + + // 주문 취소 재고 변경 (구매자, 판매자) + public void rollbackQty(Integer orderCount) { + this.qty += orderCount; + } + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); @@ -34,8 +67,9 @@ protected void onUpdate() { } @Builder - public Product(Long id, String name, Integer price, Integer qty, LocalDateTime createdAt, LocalDateTime updatedAt) { + public Product(Long id, User seller, String name, Integer price, Integer qty, LocalDateTime createdAt, LocalDateTime updatedAt) { this.id = id; + this.seller = seller; this.name = name; this.price = price; this.qty = qty; diff --git a/src/main/java/shop/mtcoding/metamall/model/user/User.java b/src/main/java/shop/mtcoding/metamall/model/user/User.java index c929ce5..76678f2 100644 --- a/src/main/java/shop/mtcoding/metamall/model/user/User.java +++ b/src/main/java/shop/mtcoding/metamall/model/user/User.java @@ -1,5 +1,6 @@ package shop.mtcoding.metamall.model.user; +import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -17,13 +18,40 @@ public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + @Column(unique = true, nullable = false, length = 20) private String username; + + @JsonIgnore + @Column(nullable = false, length = 60) // 1234 -> 단방향 암호화 60Byte private String password; + + @Column(nullable = false, length = 60) private String email; + + @Column(nullable = false, length = 10) private String role; // USER(고객), SELLER(판매자), ADMIN(관리자) + + @Column(nullable = false, length = 10) + private Boolean status; // true 활성계정, false 비활성계정 + + @Column(nullable = false) private LocalDateTime createdAt; private LocalDateTime updatedAt; + // 권한 변경 (관리자) + public void updateRole(String role) { + if (this.role.equals(role)) { + // chaeckpoint 동일한 권한으로 변경할 수 없습니다. + } + this.role = role; + } + + // 회원 탈퇴 + public void delete() { + this.status = false; + } + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); @@ -35,12 +63,14 @@ protected void onUpdate() { } @Builder - public User(Long id, String username, String password, String email, String role, LocalDateTime createdAt) { + public User(Long id, String username, String password, String email, String role, Boolean status, LocalDateTime createdAt, LocalDateTime updatedAt) { this.id = id; this.username = username; this.password = password; this.email = email; this.role = role; + this.status = status; this.createdAt = createdAt; + this.updatedAt = updatedAt; } } diff --git a/src/main/java/shop/mtcoding/metamall/model/user/UserRepository.java b/src/main/java/shop/mtcoding/metamall/model/user/UserRepository.java index 293a101..2f642f9 100644 --- a/src/main/java/shop/mtcoding/metamall/model/user/UserRepository.java +++ b/src/main/java/shop/mtcoding/metamall/model/user/UserRepository.java @@ -6,7 +6,7 @@ import java.util.Optional; -public interface UserRepository extends JpaRepository { +public interface UserRepository extends JpaRepository { @Query("select u from User u where u.username = :username") Optional findByUsername(@Param("username") String username); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 1d9bd50..dca7d37 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -3,7 +3,6 @@ server: encoding: charset: utf-8 force: true - spring: datasource: url: jdbc:h2:mem:test;MODE=MySQL @@ -20,7 +19,18 @@ spring: properties: hibernate: format_sql: true - default_batch_fetch_size: 100 # in query 자동 작성 + # in query 자동 작성 + default_batch_fetch_size: 100 + # 404 처리하는 법 + mvc: + throw-exception-if-no-handler-found: true + web: + resources: + add-mappings: false + # hibernateLazyInitializer 오류 해결법 + # jackson: + # serialization: + # fail-on-empty-beans: false logging: level: diff --git a/src/test/java/shop/mtcoding/metamall/regex/RegexTest.java b/src/test/java/shop/mtcoding/metamall/regex/RegexTest.java new file mode 100644 index 0000000..bbc2671 --- /dev/null +++ b/src/test/java/shop/mtcoding/metamall/regex/RegexTest.java @@ -0,0 +1,110 @@ +package shop.mtcoding.metamall.regex; + +import org.junit.jupiter.api.Test; + +import java.util.regex.Pattern; + +/** + * 가장 좋은 방법은 ChatGPT에게 물어보는 것이다. [스프링부트에서 특수문자 제외시키는 정규표현식 알려줘] + */ +public class RegexTest { + @Test + public void 한글만된다_test() throws Exception { + String value = "한글"; + boolean result = Pattern.matches("^[가-힣]+$", value); + System.out.println("테스트 : " + result); + } + + @Test + public void 한글은안된다_test() throws Exception { + String value = "abc"; + boolean result = Pattern.matches("^[^ㄱ-ㅎ가-힣]*$", value); + System.out.println("테스트 : " + result); + } + + @Test + public void 영어만된다_test() throws Exception { + String value = "ssar"; + boolean result = Pattern.matches("^[a-zA-Z]+$", value); + System.out.println("테스트 : " + result); + } + + @Test + public void 영어는안된다_test() throws Exception { + String value = "가22"; + boolean result = Pattern.matches("^[^a-zA-Z]*$", value); + System.out.println("테스트 : " + result); + } + + @Test + public void 영어와숫자만된다_test() throws Exception { + String value = "ab12"; + boolean result = Pattern.matches("^[a-zA-Z0-9]+$", value); + System.out.println("테스트 : " + result); + } + + @Test + public void 영어만되고_길이는최소2최대4이다_test() throws Exception { + String value = "ssar"; + boolean result = Pattern.matches("^[a-zA-Z]{2,4}$", value); + System.out.println("테스트 : " + result); + } + + // username, email, fullname + @Test + public void user_username_test() throws Exception { + String username = "ssar"; + boolean result = Pattern.matches("^[a-zA-Z0-9]{2,20}$", username); + System.out.println("테스트 : " + result); + } + + @Test + public void user_fullname_test() throws Exception { + String fullname = "메타코딩"; + boolean result = Pattern.matches("^[a-zA-Z가-힣]{1,20}$", fullname); + System.out.println("테스트 : " + result); + } + + @Test + public void user_email_test() throws Exception { + String fullname = "ssaraa@nate.com"; // ac.kr co.kr or.kr + boolean result = Pattern.matches("^[a-zA-Z0-9]{2,10}@[a-zA-Z0-9]{2,6}\\.[a-zA-Z]{2,3}$", fullname); + System.out.println("테스트 : " + result); + } + + // ChatGPT에게 물어봄! [스프링부트에서 이메일 정규표현식 알려줘] + @Test + public void real_email_test() throws Exception { + String email = "ssar@ac"; + boolean result = Pattern.matches("^[\\w._%+-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$", email); + System.out.println("테스트 : "+result); + } + + @Test + public void account_gubun_test1() throws Exception { + String gubun = "DEPOSIT"; // ac.kr co.kr or.kr + boolean result = Pattern.matches("^(DEPOSIT)$", gubun); + System.out.println("테스트 : " + result); + } + + @Test + public void account_gubun_test2() throws Exception { + String gubun = "TRANSFER"; // ac.kr co.kr or.kr + boolean result = Pattern.matches("^(DEPOSIT|TRANSFER)$", gubun); + System.out.println("테스트 : " + result); + } + + @Test + public void account_tel_test1() throws Exception { + String tel = "010-3333-7777"; // ac.kr co.kr or.kr + boolean result = Pattern.matches("^[0-9]{3}-[0-9]{4}-[0-9]{4}", tel); + System.out.println("테스트 : " + result); + } + + @Test + public void account_tel_test2() throws Exception { + String tel = "01033337777"; // ac.kr co.kr or.kr + boolean result = Pattern.matches("^[0-9]{11}", tel); + System.out.println("테스트 : " + result); + } +}