diff --git a/build.gradle b/build.gradle index 4943187..3f3f018 100644 --- a/build.gradle +++ b/build.gradle @@ -19,6 +19,8 @@ repositories { } dependencies { + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-aop' 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..9205da6 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..4b49f93 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("/users/*"); //토큰만 있음 ok + 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..6dc7a68 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/config/MyWebMvcConfig.java @@ -0,0 +1,46 @@ +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; + +@RequiredArgsConstructor +@Configuration +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..f197069 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/AdminController.java @@ -0,0 +1,35 @@ +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..867affb --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/OrderController.java @@ -0,0 +1,111 @@ +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.*; +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; +/** + * 주문하기(고객), 주문목록보기(고객), 주문목록보기(판매자), 주문취소하기(고객), 주문취소하기 + (판매자) */ +@RequiredArgsConstructor +@RestController +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 -> { + orderSheetPS.addOrderProduct(orderProductPS); + orderProductPS.getProduct().updateQty(orderProductPS.getCount()); + }) + ); + // 6. 응답하기 + ResponseDTO responseDto = new ResponseDTO<>().data(orderSheetPS); + 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); + } +} \ No newline at end of file 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..2dd5f3a --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/ProductController.java @@ -0,0 +1,98 @@ +package shop.mtcoding.metamall.controller; + +import lombok.RequiredArgsConstructor; +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; + +/** + * 상품등록, 상품목록보기, 상품상세보기, 상품수정하기, 상품삭제하기 + * */ +@RequiredArgsConstructor +@RestController +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. 판매자 찾기 + 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().body(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().body(responseDto); + } + + //상품상세보기 + @GetMapping("/products/{id}") + public ResponseEntity findById(@PathVariable Long id){ + // 1. 상품 찾기 + Product productPS = productRepository.findById(id).orElseThrow( + ()-> new Exception400("id","해당 상품을 찾을 수 없습니다")); + // 2. 응답하기 + ResponseDTO responseDto = new ResponseDTO<>().data(productPS); + return ResponseEntity.ok().body(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(()-> new Exception400("id","해당 상품을 찾을 수 없습니다")); + // 2. Update 더티체킹 + productPS.update(updateDTO.getName(), updateDTO.getPrice(), updateDTO.getQty()); + // 3. 응답하기 + ResponseDTO responseDto = new ResponseDTO<>().data(productPS); + return ResponseEntity.ok().body(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( + ()-> new Exception400("id","해당 상품을 찾을 수 없습니다")); + productRepository.delete(productPS); + ResponseDTO responseDto = new ResponseDTO<>(); + return ResponseEntity.ok().body(responseDto); + } +} \ No newline at end of file diff --git a/src/main/java/shop/mtcoding/metamall/controller/UserController.java b/src/main/java/shop/mtcoding/metamall/controller/UserController.java index ddfee94..08b3819 100644 --- a/src/main/java/shop/mtcoding/metamall/controller/UserController.java +++ b/src/main/java/shop/mtcoding/metamall/controller/UserController.java @@ -2,62 +2,79 @@ import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; +import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; +import shop.mtcoding.metamall.core.annotation.MySameUserIdCheck; 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.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; import shop.mtcoding.metamall.model.user.UserRepository; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import javax.validation.Valid; import java.time.LocalDateTime; -import java.util.Optional; + +/** + * 회원가입, 로그인, 유저상세보기 */ @RequiredArgsConstructor @RestController public class UserController { - private final UserRepository userRepository; private final LoginLogRepository loginLogRepository; private final HttpSession session; + //핵심 로직 + + //회원가입(POST) + @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); + } + + + //로그인(POST) @PostMapping("/login") - public ResponseEntity login(@RequestBody UserRequest.LoginDto loginDto, HttpServletRequest request) { - Optional userOP = userRepository.findByUsername(loginDto.getUsername()); - if (userOP.isPresent()) { - // 1. 유저 정보 꺼내기 - User loginUser = userOP.get(); - - // 2. 패스워드 검증하기 - if(!loginUser.getPassword().equals(loginDto.getPassword())){ - throw new Exception401("인증되지 않았습니다"); - } - - // 3. JWT 생성하기 - String jwt = JwtProvider.create(userOP.get()); - - // 4. 최종 로그인 날짜 기록 (더티체킹 - update 쿼리 발생) - loginUser.setUpdatedAt(LocalDateTime.now()); - - // 5. 로그 테이블 기록 - LoginLog loginLog = LoginLog.builder() - .userId(loginUser.getId()) - .userAgent(request.getHeader("User-Agent")) - .clientIP(request.getRemoteAddr()) - .build(); - loginLogRepository.save(loginLog); - - // 6. 응답 DTO 생성 - ResponseDto responseDto = new ResponseDto<>().data(loginUser); - return ResponseEntity.ok().header(JwtProvider.HEADER, jwt).body(responseDto); - } else { - throw new Exception400("유저네임 혹은 아이디가 잘못되었습니다"); - } + public ResponseEntity login(@RequestBody @Valid UserRequest.LoginDTO + loginDTO, Errors errors, HttpServletRequest request) { + User userPS = userRepository.findByUsername(loginDTO.getUsername()).orElseThrow( + ()->new Exception400("username","유저네임을 찾을 수 없습니다")); + + // 1. 패스워드 검증하기 + if (!userPS.getPassword().equals(loginDTO.getPassword())) { + throw new Exception400("password","패스워드가 잘못입력되었습니다"); } + // 2. JWT 생성하기 + String jwt = JwtProvider.create(userPS); + + // 3. 최종 로그인 날짜 기록 (더티체킹 - update 쿼리 발생) + userPS.setUpdatedAt(LocalDateTime.now()); + + // 4. 로그 테이블 기록 + LoginLog loginLog = LoginLog.builder() + .userId(userPS.getId()) + .userAgent(request.getHeader("User-Agent")) + .clientIP(request.getRemoteAddr()) + .build(); + loginLogRepository.save(loginLog); + + // 5. 응답 DTO 생성 + ResponseDTO responseDto = new ResponseDTO<>().data(userPS); + return ResponseEntity.ok().header(JwtProvider.HEADER,jwt).body(responseDto); + } + @MySameUserIdCheck + @GetMapping("/users/{id}") + public ResponseEntity findById(@PathVariable Long id){ + User userPS =userRepository.findById(id).orElseThrow( + ()->new Exception400("id","유저를 찾을 수 없습니다")); + ResponseDTO responseDto = new ResponseDTO<>().data(userPS); + return ResponseEntity.ok().body(responseDto); } -} +} \ No newline at end of file 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..fb3aef7 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyErrorLogAdvice.java @@ -0,0 +1,38 @@ +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.http.converter.HttpMessageNotReadableException; +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; +@RequiredArgsConstructor +@Aspect +@Component +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) throws HttpMessageNotReadableException + { + 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); + } } + } } +} \ No newline at end of file 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..9b8b941 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,59 @@ 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){ + return new ResponseEntity<>(e.body(), e.status()); } + @MyErrorLogRecord @ExceptionHandler(Exception403.class) public ResponseEntity forbidden(Exception403 e){ + 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){ + 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 serverError(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..aae7002 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MySameUserIdAdvice.java @@ -0,0 +1,4 @@ +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..792da2a --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyValidAdvice.java @@ -0,0 +1,34 @@ +package shop.mtcoding.metamall.core.advice; + +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; +@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..a220a23 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/annotation/MyErrorLogRecord.java @@ -0,0 +1,10 @@ +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 { +} \ No newline at end of file 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..5de4942 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/annotation/MySameUserIdCheck.java @@ -0,0 +1,10 @@ +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 { +} \ No newline at end of file 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..cc22554 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/annotation/MySessionStore.java @@ -0,0 +1,10 @@ +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..2bccfce 100644 --- a/src/main/java/shop/mtcoding/metamall/core/exception/Exception400.java +++ b/src/main/java/shop/mtcoding/metamall/core/exception/Exception400.java @@ -2,19 +2,27 @@ import lombok.Getter; import org.springframework.http.HttpStatus; -import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.ResponseDTO; +import shop.mtcoding.metamall.dto.ValidDTO; -// 유효성 실패 +// 유효성 실패, 잘못된 파라메터 요청 @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()); + public ResponseDTO body(){ + 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/Exception401.java b/src/main/java/shop/mtcoding/metamall/core/exception/Exception401.java index 5d2f310..8dcb131 100644 --- a/src/main/java/shop/mtcoding/metamall/core/exception/Exception401.java +++ b/src/main/java/shop/mtcoding/metamall/core/exception/Exception401.java @@ -3,7 +3,7 @@ import lombok.Getter; import org.springframework.http.HttpStatus; -import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.ResponseDTO; // 인증 안됨 @@ -13,8 +13,8 @@ public Exception401(String message) { super(message); } - public ResponseDto body(){ - ResponseDto responseDto = new ResponseDto<>(); + public ResponseDTO body(){ + ResponseDTO responseDto = new ResponseDTO<>(); responseDto.fail(HttpStatus.UNAUTHORIZED, "unAuthorized", getMessage()); return responseDto; } diff --git a/src/main/java/shop/mtcoding/metamall/core/exception/Exception403.java b/src/main/java/shop/mtcoding/metamall/core/exception/Exception403.java index c8dc137..755b103 100644 --- a/src/main/java/shop/mtcoding/metamall/core/exception/Exception403.java +++ b/src/main/java/shop/mtcoding/metamall/core/exception/Exception403.java @@ -2,7 +2,7 @@ import lombok.Getter; import org.springframework.http.HttpStatus; -import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.ResponseDTO; // 권한 없음 @@ -12,10 +12,10 @@ public Exception403(String message) { super(message); } - public ResponseDto body(){ - ResponseDto responseDto = new ResponseDto<>(); - responseDto.fail(HttpStatus.FORBIDDEN, "forbidden", getMessage()); - return responseDto; + public ResponseDTO body(){ + ResponseDTO ResponseDto = new ResponseDTO<>(); + ResponseDto.fail(HttpStatus.FORBIDDEN, "forbidden", getMessage()); + return ResponseDto; } public HttpStatus status(){ 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..b3a1755 100644 --- a/src/main/java/shop/mtcoding/metamall/core/filter/JwtVerifyFilter.java +++ b/src/main/java/shop/mtcoding/metamall/core/filter/JwtVerifyFilter.java @@ -8,8 +8,9 @@ import org.springframework.http.HttpStatus; import shop.mtcoding.metamall.core.exception.Exception400; import shop.mtcoding.metamall.core.jwt.JwtProvider; -import shop.mtcoding.metamall.core.session.LoginUser; -import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.core.session.SessionUser; +import shop.mtcoding.metamall.core.util.MyFilterResponseUtil; +import shop.mtcoding.metamall.dto.ResponseDTO; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; @@ -17,6 +18,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 { @@ -25,34 +27,24 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha 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("loginUser", 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..913ca9d --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/interceptor/MyAdminInterceptor.java @@ -0,0 +1,23 @@ +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")){ + throw new Exception403("권한이 없습니다"); + } + return true; + } +} 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..c6a15e3 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/interceptor/MySellerInterceptor.java @@ -0,0 +1,24 @@ +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("권한이 없습니다"); + } + } +} \ No newline at end of file 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..d6719d3 --- /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; + +@RequiredArgsConstructor +@Configuration +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/core/util/MyDateUtil.java b/src/main/java/shop/mtcoding/metamall/core/util/MyDateUtil.java new file mode 100644 index 0000000..3f92cf6 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/util/MyDateUtil.java @@ -0,0 +1,10 @@ +package shop.mtcoding.metamall.core.util; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class MyDateUtil { + public static String toStringFormat(LocalDateTime localDateTime) { + return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + } +} 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..a9bda88 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java @@ -0,0 +1,50 @@ +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 v1 = new ResponseDTO<>(); // delete 반환값 void +// ResponseDTO v2 = new ResponseDTO<>().data("값"); // get, put, post 성공시 메세지 +// ResponseDTO v3 = new ResponseDTO<>().fail(); // 실패시 + + 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, + "forbidden", 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 similarity index 81% rename from src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java rename to src/main/java/shop/mtcoding/metamall/dto/ResponseDTO.java index 7f190c6..fd8c682 100644 --- a/src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java +++ b/src/main/java/shop/mtcoding/metamall/dto/ResponseDTO.java @@ -4,23 +4,23 @@ import org.springframework.http.HttpStatus; @Getter -public class ResponseDto { +public class ResponseDTO { private Integer status; // 에러시에 의미 있음. private String msg; // 에러시에 의미 있음. ex) badRequest private T data; // 에러시에는 구체적인 에러 내용 ex) username이 입력되지 않았습니다 - public ResponseDto(){ + public ResponseDTO(){ this.status = HttpStatus.OK.value(); this.msg = "성공"; this.data = null; } - public ResponseDto data(T data){ + public ResponseDTO data(T data){ this.data = data; // 응답할 데이터 바디 return this; } - public ResponseDto fail(HttpStatus httpStatus, String msg, T data){ + public ResponseDTO fail(HttpStatus httpStatus, String msg, T data){ this.status = httpStatus.value(); this.msg = msg; // 에러 제목 this.data = data; // 에러 내용 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..1d6202e --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/ValidDTO.java @@ -0,0 +1,11 @@ +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..f05154b --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/order/OrderRequest.java @@ -0,0 +1,45 @@ +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; + } + + public List getIds() { + return orderProducts.stream().map((orderProduct) -> + orderProduct.getProductId()).collect(Collectors.toList()); + } + + public List toEntity(List products) { + return orderProducts.stream() + .flatMap((orderProduct) -> { + Long productId = orderProduct.productId; + Integer count = orderProduct.getCount(); + 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()); + } + } +} \ No newline at end of file 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..0546cf5 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/product/ProductRequest.java @@ -0,0 +1,44 @@ +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; + } +} \ No newline at end of file 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..72f9de2 100644 --- a/src/main/java/shop/mtcoding/metamall/dto/user/UserRequest.java +++ b/src/main/java/shop/mtcoding/metamall/dto/user/UserRequest.java @@ -1,12 +1,47 @@ package shop.mtcoding.metamall.dto.user; +import lombok.Builder; 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{ + @NotEmpty @Size(min=3, max=20) private String username; + @NotEmpty @Size(min=4, max=20) private String password; + @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를 만들어준다. update할때는 더티체킹 + public User toEntity(){ + return User.builder() + .username(username) + .password(password) + .email(email) + .build(); + } + } + @Getter @Setter + public static class LoginDTO { + @NotEmpty + private String username; + @NotEmpty + private String password; + } + + @Getter @Setter + public static class RoleUpdateDTO { + @Pattern(regexp = "USER|SELLER|ADMIN") + @NotEmpty + 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 74% 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..3890ffe 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,9 +20,15 @@ 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; // 상품 주문 금액 private LocalDateTime createdAt; private LocalDateTime updatedAt; @@ -29,6 +36,11 @@ public class OrderProduct { // 주문 상품 @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 66% 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..9a21142 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.*; @@ -24,12 +24,26 @@ public class OrderSheet { // 주문서 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 합) 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..e8a954a --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java @@ -0,0 +1,14 @@ +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..c368668 100644 --- a/src/main/java/shop/mtcoding/metamall/model/product/Product.java +++ b/src/main/java/shop/mtcoding/metamall/model/product/Product.java @@ -4,10 +4,13 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import shop.mtcoding.metamall.model.user.User; + import javax.persistence.*; import java.time.LocalDateTime; + @NoArgsConstructor @Setter // DTO 만들면 삭제해야됨 @Getter @@ -17,12 +20,39 @@ public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + @ManyToOne + 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; // 상품 재고 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 = this.qty - orderCount; + } + + //주문 취소시 재고량 변경 (구매자, 판매자) + public void rollbackQty(Integer orderCount) { + this.qty = this.qty + orderCount; + } + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); @@ -34,8 +64,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; @@ -43,3 +74,4 @@ public Product(Long id, String name, Integer price, Integer qty, LocalDateTime c this.updatedAt = updatedAt; } } + 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..7513431 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,37 @@ public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @Column(unique = true, nullable = false, length = 20) private String username; + + @Column(nullable = false, length = 60) //무조건 60이상 왜냐면 단방향 암호화 하면 1234 -> 60바이트 + @JsonIgnore private String password; + @Column(nullable = false, length = 50) 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)){ + // checkpoint : throw 동일한 권한으로 변경할 수 없습니다. + } + this.role = role; + } + + //회원 탈퇴 + public void delete(){ + this.status = false; + } + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); @@ -35,12 +60,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/java/shop/mtcoding/metamall/util/MyFilterResponseUtils.java b/src/main/java/shop/mtcoding/metamall/util/MyFilterResponseUtils.java new file mode 100644 index 0000000..7ba3dd8 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/util/MyFilterResponseUtils.java @@ -0,0 +1,27 @@ +package shop.mtcoding.metamall.core.util; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.HttpStatus; +import shop.mtcoding.metamall.dto.ResponseDTO; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +public class MyFilterResponseUtils { + 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, + "forbidden", e.getMessage()); + ObjectMapper om = new ObjectMapper(); + String responseBody = om.writeValueAsString(responseDto); + resp.getWriter().println(responseBody); + } } \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 1d9bd50..60a0a9f 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,9 +19,21 @@ spring: properties: hibernate: format_sql: true - default_batch_fetch_size: 100 # in query 자동 작성 - + # in query 자동 작성 + default_batch_fetch_size: 100 + # db session controller까지 가져오기 + open-in-view: true + # 404 처리하는 법 + mvc: + throw-exception-if-no-handler-found: true + web: + resources: + add-mappings: false + # hibernateLazyInitializer 오류 해결법 + # jackson: + # serialization: + # fail-on-empty-beans: false logging: - level: - '[shop.mtcoding.metamall]': DEBUG # DEBUG 레벨부터 에러 확인할 수 있게 설정하기 - '[org.hibernate.type]': TRACE # 콘솔 쿼리에 ? 에 주입된 값 보기 \ No newline at end of file +level: +'[shop.mtcoding.metamall]': DEBUG # DEBUG 레벨부터 에러 확인할 수 있게 설정하기 +'[org.hibernate.type]': TRACE # 콘솔 쿼리에 ? 에 주입된 값 보기입된 값 보기 \ No newline at end of file