From 9520c3b7b2ebb70c9106fbddabb1fefe235f0aa1 Mon Sep 17 00:00:00 2001 From: Kayden Date: Fri, 14 Apr 2023 18:00:15 +0900 Subject: [PATCH 1/6] =?UTF-8?q?Entity=20=EC=84=A4=EA=B3=84=20=EC=99=84?= =?UTF-8?q?=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 2 ++ .../metamall/MetamallApplication.java | 6 ++-- .../metamall/model/log/error/ErrorLog.java | 2 ++ .../product}/OrderProduct.java | 16 +++++++-- .../product}/OrderProductRepository.java | 2 +- .../sheet}/OrderSheet.java | 22 +++++++++--- .../sheet}/OrderSheetRepository.java | 2 +- .../metamall/model/product/Product.java | 33 ++++++++++++++++- .../mtcoding/metamall/model/user/User.java | 36 ++++++++++++++++++- src/main/resources/application.yml | 18 +++++++--- 10 files changed, 121 insertions(+), 18 deletions(-) rename src/main/java/shop/mtcoding/metamall/model/{orderproduct => order/product}/OrderProduct.java (78%) rename src/main/java/shop/mtcoding/metamall/model/{orderproduct => order/product}/OrderProductRepository.java (74%) rename src/main/java/shop/mtcoding/metamall/model/{ordersheet => order/sheet}/OrderSheet.java (69%) rename src/main/java/shop/mtcoding/metamall/model/{ordersheet => order/sheet}/OrderSheetRepository.java (74%) diff --git a/build.gradle b/build.gradle index 4943187..05c9628 100644 --- a/build.gradle +++ b/build.gradle @@ -19,6 +19,8 @@ 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 '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..9152593 100644 --- a/src/main/java/shop/mtcoding/metamall/MetamallApplication.java +++ b/src/main/java/shop/mtcoding/metamall/MetamallApplication.java @@ -4,10 +4,8 @@ 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; 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..8c26d04 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,8 @@ 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 78% 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..d26e522 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,10 @@ -package shop.mtcoding.metamall.model.orderproduct; +package shop.mtcoding.metamall.model.order.product; 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 +19,15 @@ public class OrderProduct { // 주문 상품 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + // checkpoint -> 무한참조 @ManyToOne private Product product; + + @Column(nullable = false) private Integer count; // 상품 주문 개수 + + @Column(nullable = false) private Integer orderPrice; // 상품 주문 금액 private LocalDateTime createdAt; private LocalDateTime updatedAt; @@ -29,6 +35,12 @@ 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 69% 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..be8d9b4 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,10 @@ -package shop.mtcoding.metamall.model.ordersheet; +package shop.mtcoding.metamall.model.order.sheet; 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 +21,29 @@ public class OrderSheet { // 주문서 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @ManyToOne private User user; // 주문자 - @OneToMany(mappedBy = "orderSheet") + + // checkpoint -> 무한참조 + @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/ordersheet/OrderSheetRepository.java b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java similarity index 74% rename from src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheetRepository.java rename to src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java index 5d59249..c706a6f 100644 --- a/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheetRepository.java +++ b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java @@ -1,4 +1,4 @@ -package shop.mtcoding.metamall.model.ordersheet; +package shop.mtcoding.metamall.model.order.sheet; import org.springframework.data.jpa.repository.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..cf834d0 100644 --- a/src/main/java/shop/mtcoding/metamall/model/product/Product.java +++ b/src/main/java/shop/mtcoding/metamall/model/product/Product.java @@ -4,6 +4,7 @@ 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 +18,41 @@ public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + @ManyToOne + private User seller; + + @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; 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..a3899a9 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,44 @@ public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + @Column(unique = true, nullable = false, length = 20) private String username; + + @JsonIgnore // User로 응답 시 massage converter가 password를 파싱하여 노출하지 않도록 설정 + @Column(nullable = false, length = 60) // 단방향 암호 후 60byte private String password; + + @Column(nullable = false, length = 50) private String email; + + // @Enumerated(EnumType.STRING) Enum Type으로 설정하는 것이 좋음 + @Column(nullable = false, length = 10) private String role; // USER(고객), SELLER(판매자), ADMIN(관리자) + + @Column(nullable = false, length = 10) + private Boolean status; // ture 활성 계정, false 비활성 계정 + + @Column(nullable = false) private LocalDateTime createdAt; + + // 수정 시에 값이 들어오므로 Null 허용 private LocalDateTime updatedAt; + // 권한 변경 (관리자) + public void updateRole() { + if (this.role.equals(role)) { + // checkpoint 동일한 권한으로 변경할 수 없습니다. + } + this.role = role; + } + + // 회원 탈퇴 + public void delete() { + this.status = false; + } + + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); @@ -35,12 +67,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/resources/application.yml b/src/main/resources/application.yml index 1d9bd50..60b78d8 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,20 @@ spring: properties: hibernate: format_sql: true - default_batch_fetch_size: 100 # in query 자동 작성 + # in query 자동 작성 + default_batch_fetch_size: 100 + # 404 처리하는 법(Spring에 있는 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 + '[shop.mtcoding.metamall]': DEBUG # DEBUG 레벨부터 에러 확인할 수 있게 설정하기(log) + '[org.hibernate.type]': TRACE # 콘솔 쿼리에 ? 에 주입된 값 보기(insert, select에 ?) \ No newline at end of file From 66d6e0f1ea9fd5f2238c2d01c58d34becf97657f Mon Sep 17 00:00:00 2001 From: Kayden Date: Tue, 18 Apr 2023 15:05:14 +0900 Subject: [PATCH 2/6] =?UTF-8?q?Repository=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../metamall/model/order/sheet/OrderSheetRepository.java | 7 +++++++ 1 file changed, 7 insertions(+) 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 index c706a6f..4f60e74 100644 --- a/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java +++ b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java @@ -1,6 +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); } From d263693a510c37b1f8fe15fe5a121762dc2f02b7 Mon Sep 17 00:00:00 2001 From: Kayden Date: Tue, 18 Apr 2023 15:15:19 +0900 Subject: [PATCH 3/6] =?UTF-8?q?Dummy=20Data=20=20=EC=84=B8=ED=8C=85=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/shop/mtcoding/metamall/MetamallApplication.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/shop/mtcoding/metamall/MetamallApplication.java b/src/main/java/shop/mtcoding/metamall/MetamallApplication.java index 9152593..c8c151e 100644 --- a/src/main/java/shop/mtcoding/metamall/MetamallApplication.java +++ b/src/main/java/shop/mtcoding/metamall/MetamallApplication.java @@ -10,16 +10,21 @@ import shop.mtcoding.metamall.model.user.User; import shop.mtcoding.metamall.model.user.UserRepository; +import java.util.Arrays; + @SpringBootApplication public class MetamallApplication { + // CommandLineRunner 는 Spring Boot 가 최초 실행될 때 return 값을 실행시켜 줌 @Bean CommandLineRunner initData(UserRepository userRepository, ProductRepository productRepository, OrderProductRepository orderProductRepository, OrderSheetRepository orderSheetRepository){ 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)); // 벌크 컬렉터로 save 시에는 saveAll 사용(컬렉션 들어가야 함) }; } From 179605e5794a54b1a2d2b5c45cd36569750c51ec Mon Sep 17 00:00:00 2001 From: Kayden Date: Tue, 18 Apr 2023 16:27:48 +0900 Subject: [PATCH 4/6] =?UTF-8?q?Exception=20=EC=B2=98=EB=A6=AC=20=EC=99=84?= =?UTF-8?q?=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/advice/MyExceptionAdvice.java | 25 +++++++++++----- .../metamall/core/exception/Exception400.java | 21 +++++++++----- .../metamall/core/exception/Exception401.java | 6 ++-- .../metamall/core/exception/Exception404.java | 24 --------------- .../metamall/core/exception/Exception500.java | 24 --------------- .../metamall/{ => core}/util/MyDateUtil.java | 2 +- .../core/util/MyFilterResponseUtil.java | 29 +++++++++++++++++++ .../{ResponseDto.java => ResponseDTO.java} | 11 ++++--- .../mtcoding/metamall/dto/user/ValidDTO.java | 11 +++++++ 9 files changed, 82 insertions(+), 71 deletions(-) delete mode 100644 src/main/java/shop/mtcoding/metamall/core/exception/Exception404.java delete mode 100644 src/main/java/shop/mtcoding/metamall/core/exception/Exception500.java rename src/main/java/shop/mtcoding/metamall/{ => core}/util/MyDateUtil.java (86%) create mode 100644 src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java rename src/main/java/shop/mtcoding/metamall/dto/{ResponseDto.java => ResponseDTO.java} (73%) create mode 100644 src/main/java/shop/mtcoding/metamall/dto/user/ValidDTO.java 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..1c60c6f 100644 --- a/src/main/java/shop/mtcoding/metamall/core/advice/MyExceptionAdvice.java +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyExceptionAdvice.java @@ -2,10 +2,13 @@ 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.exception.*; +import shop.mtcoding.metamall.dto.ResponseDTO; import shop.mtcoding.metamall.model.log.error.ErrorLogRepository; @Slf4j @@ -13,30 +16,36 @@ @RestControllerAdvice public class MyExceptionAdvice { - private final ErrorLogRepository errorLogRepository; - @ExceptionHandler(Exception400.class) public ResponseEntity badRequest(Exception400 e){ + return new ResponseEntity<>(e.body(), e.status()); } @ExceptionHandler(Exception401.class) public ResponseEntity unAuthorized(Exception401 e){ + return new ResponseEntity<>(e.body(), e.status()); } @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()); + @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()); + // 나머지 모든 예외는 이 친구에게 다 걸리짐 + @ExceptionHandler(Exception.class) + public ResponseEntity unknownServerError(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/exception/Exception400.java b/src/main/java/shop/mtcoding/metamall/core/exception/Exception400.java index d1b5fec..d0968a7 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,26 @@ 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.user.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/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/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..273a662 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java @@ -0,0 +1,29 @@ +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; + +// Filter 는 예외 핸들러로 처리 못함 +public class MyFilterResponseUtil { + 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); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java b/src/main/java/shop/mtcoding/metamall/dto/ResponseDTO.java similarity index 73% rename from src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java rename to src/main/java/shop/mtcoding/metamall/dto/ResponseDTO.java index 7f190c6..6cc650f 100644 --- a/src/main/java/shop/mtcoding/metamall/dto/ResponseDto.java +++ b/src/main/java/shop/mtcoding/metamall/dto/ResponseDTO.java @@ -4,23 +4,26 @@ 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(){ + // delete 요청 - 성공 + public ResponseDTO(){ this.status = HttpStatus.OK.value(); this.msg = "성공"; this.data = null; } - public ResponseDto data(T data){ + // get, post, put - 성공 + public ResponseDTO data(T data){ this.data = data; // 응답할 데이터 바디 return this; } - public ResponseDto fail(HttpStatus httpStatus, String msg, T data){ + // 4가지 요청에 대한 실패 + 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/user/ValidDTO.java b/src/main/java/shop/mtcoding/metamall/dto/user/ValidDTO.java new file mode 100644 index 0000000..febc93a --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/user/ValidDTO.java @@ -0,0 +1,11 @@ +package shop.mtcoding.metamall.dto.user; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter @Setter @AllArgsConstructor +public class ValidDTO { + private String key; + private String value; +} From a0ead35b2968e1dc5bf69e79247df1366d5c0185 Mon Sep 17 00:00:00 2001 From: Kayden Date: Tue, 18 Apr 2023 17:38:39 +0900 Subject: [PATCH 5/6] =?UTF-8?q?Core=20=EC=84=B8=ED=8C=85=20=EC=99=84?= =?UTF-8?q?=E3=84=B9=C2=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../metamall/config/FilterRegisterConfig.java | 6 ++- .../metamall/config/MyWebMvcConfig.java | 49 ++++++++++++++++++ .../metamall/config/WebMvcConfig.java | 18 ------- .../metamall/controller/UserController.java | 2 +- .../core/advice/MyErrorLogAdvice.java | 44 ++++++++++++++++ .../core/advice/MyExceptionAdvice.java | 12 ++++- .../core/advice/MySameUserIdAdvice.java | 51 +++++++++++++++++++ .../metamall/core/advice/MyValidAdvice.java | 38 ++++++++++++++ .../core/annotation/MyErrorLogRecord.java | 11 ++++ .../core/annotation/MySameUserIdCheck.java | 11 ++++ .../core/annotation/MySessionStore.java | 11 ++++ .../metamall/core/filter/JwtVerifyFilter.java | 28 ++++------ .../core/interceptor/MyAdminInterceptor.java | 26 ++++++++++ .../core/interceptor/MySellerInterceptor.java | 27 ++++++++++ .../resolver/MySessionArgumentResolver.java | 33 ++++++++++++ .../{LoginUser.java => SessionUser.java} | 6 +-- .../core/util/MyFilterResponseUtil.java | 12 +++++ .../metamall/model/user/UserRepository.java | 2 +- 18 files changed, 345 insertions(+), 42 deletions(-) create mode 100644 src/main/java/shop/mtcoding/metamall/config/MyWebMvcConfig.java delete mode 100644 src/main/java/shop/mtcoding/metamall/config/WebMvcConfig.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/advice/MyErrorLogAdvice.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/advice/MySameUserIdAdvice.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/advice/MyValidAdvice.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/annotation/MyErrorLogRecord.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/annotation/MySameUserIdCheck.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/annotation/MySessionStore.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/interceptor/MyAdminInterceptor.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/interceptor/MySellerInterceptor.java create mode 100644 src/main/java/shop/mtcoding/metamall/core/resolver/MySessionArgumentResolver.java rename src/main/java/shop/mtcoding/metamall/core/session/{LoginUser.java => SessionUser.java} (66%) diff --git a/src/main/java/shop/mtcoding/metamall/config/FilterRegisterConfig.java b/src/main/java/shop/mtcoding/metamall/config/FilterRegisterConfig.java index f5ea4db..b141403 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/*"); // 토큰 + 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..ec91f77 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/config/MyWebMvcConfig.java @@ -0,0 +1,49 @@ +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/UserController.java b/src/main/java/shop/mtcoding/metamall/controller/UserController.java index ddfee94..c5ecc32 100644 --- a/src/main/java/shop/mtcoding/metamall/controller/UserController.java +++ b/src/main/java/shop/mtcoding/metamall/controller/UserController.java @@ -57,7 +57,7 @@ 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("유저네임 혹은 아이디가 잘못되었습니다"); + 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..fa152f7 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyErrorLogAdvice.java @@ -0,0 +1,44 @@ +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 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; + +@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); + } + } + } + } +} 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 1c60c6f..9b3988b 100644 --- a/src/main/java/shop/mtcoding/metamall/core/advice/MyExceptionAdvice.java +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyExceptionAdvice.java @@ -7,6 +7,7 @@ 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; @@ -16,24 +17,32 @@ @RestControllerAdvice public class MyExceptionAdvice { + @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()); } + @MyErrorLogRecord @ExceptionHandler(NoHandlerFoundException.class) public ResponseEntity notFound(NoHandlerFoundException e){ ResponseDTO responseDto = new ResponseDTO<>(); @@ -41,6 +50,7 @@ public ResponseEntity notFound(NoHandlerFoundException e){ return new ResponseEntity<>(responseDto, HttpStatus.NOT_FOUND); } + @MyErrorLogRecord // 나머지 모든 예외는 이 친구에게 다 걸리짐 @ExceptionHandler(Exception.class) public ResponseEntity unknownServerError(Exception e){ 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..6b60378 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MySameUserIdAdvice.java @@ -0,0 +1,51 @@ +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.aspectj.lang.reflect.MethodSignature; +import org.springframework.stereotype.Component; +import shop.mtcoding.metamall.core.annotation.MySessionStore; +import shop.mtcoding.metamall.core.exception.Exception403; +import shop.mtcoding.metamall.core.session.SessionUser; +import shop.mtcoding.metamall.model.log.error.ErrorLog; +import shop.mtcoding.metamall.model.user.User; + +import javax.servlet.http.HttpSession; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.stream.IntStream; + +@RequiredArgsConstructor +@Aspect +@Component +public class MySameUserIdAdvice { + + private final HttpSession session; + + // 깃발에 별칭주기 + @Pointcut("@annotation(shop.mtcoding.metamall.core.annotation.MySameUserIdCheck)") + public void mySameUserId(){} + + @Before("mySameUserId()") + public void sameUserIdAdvice(JoinPoint jp) { + Object[] args = jp.getArgs(); + MethodSignature signature = (MethodSignature) jp.getSignature(); + Method method = signature.getMethod(); + Parameter[] parameters = method.getParameters(); + + IntStream.range(0, parameters.length).forEach( + (i) -> { + if(parameters[i].getName().equals("id") && parameters[i].getType() == Long.class){ + SessionUser sessionUser = (SessionUser) session.getAttribute("sessionUser"); + Long id = (Long) args[i]; + if(sessionUser.getId() != id){ + throw new Exception403("해당 id에 접근할 권한이 없습니다"); + } + } + } + ); + } +} 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..cc0078f --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyValidAdvice.java @@ -0,0 +1,38 @@ +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..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..eea3d32 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/annotation/MySessionStore.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.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface MySessionStore { +} 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..9d08793 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,11 @@ 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 shop.mtcoding.metamall.dto.ResponseDto; import javax.servlet.*; @@ -17,6 +20,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 +29,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("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..801c771 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/interceptor/MyAdminInterceptor.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 shop.mtcoding.metamall.core.util.MyFilterResponseUtils; + + +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..1b14f12 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/interceptor/MySellerInterceptor.java @@ -0,0 +1,27 @@ +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 shop.mtcoding.metamall.core.util.MyFilterResponseUtils; + +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..ea462dc --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/resolver/MySessionArgumentResolver.java @@ -0,0 +1,33 @@ +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/MyFilterResponseUtil.java b/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java index 273a662..a73030e 100644 --- a/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java +++ b/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java @@ -2,13 +2,25 @@ 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.user.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"); 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); From 1d61bf86372bc471a853105432c367dbe7842216 Mon Sep 17 00:00:00 2001 From: Kayden Date: Wed, 19 Apr 2023 14:47:08 +0900 Subject: [PATCH 6/6] =?UTF-8?q?=ED=86=A0=EC=9D=B4=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EC=A0=9D=ED=8A=B8=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../metamall/controller/AdminController.java | 35 +++++ .../metamall/controller/OrderController.java | 141 ++++++++++++++++++ .../controller/ProductController.java | 93 ++++++++++++ .../metamall/controller/UserController.java | 23 ++- .../metamall/dto/order/OrderRequest.java | 51 +++++++ .../metamall/dto/product/ProductRequest.java | 51 +++++++ .../metamall/dto/user/UserRequest.java | 45 +++++- .../model/order/product/OrderProduct.java | 2 + .../model/order/sheet/OrderSheet.java | 2 + .../mtcoding/metamall/model/user/User.java | 5 +- .../mtcoding/metamall/regex/RegexTest.java | 107 +++++++++++++ 11 files changed, 547 insertions(+), 8 deletions(-) create mode 100644 src/main/java/shop/mtcoding/metamall/controller/AdminController.java create mode 100644 src/main/java/shop/mtcoding/metamall/controller/OrderController.java create mode 100644 src/main/java/shop/mtcoding/metamall/controller/ProductController.java create mode 100644 src/main/java/shop/mtcoding/metamall/dto/order/OrderRequest.java create mode 100644 src/main/java/shop/mtcoding/metamall/dto/product/ProductRequest.java create mode 100644 src/test/java/shop/mtcoding/metamall/regex/RegexTest.java 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..b5e0df0 --- /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.BindingResult; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.*; +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..fabdecc --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/OrderController.java @@ -0,0 +1,141 @@ +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); + } + + // 판매자 주문 취소 + @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..e109ba2 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/ProductController.java @@ -0,0 +1,93 @@ +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.exception.Exception401; +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); + } + + @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); + } + + @DeleteMapping("/seller/products/{id}") + public ResponseEntity deleteById(@PathVariable Long id){ + Product productPS = productRepository.findById(id).orElseThrow(()-> new Exception400("id", "해당 상품을 찾을 수 없습니다")); + productRepository.delete(productPS); + ResponseDTO responseDto = new ResponseDTO<>(); + return ResponseEntity.ok().body(responseDto); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/controller/UserController.java b/src/main/java/shop/mtcoding/metamall/controller/UserController.java index c5ecc32..78504ad 100644 --- a/src/main/java/shop/mtcoding/metamall/controller/UserController.java +++ b/src/main/java/shop/mtcoding/metamall/controller/UserController.java @@ -2,11 +2,12 @@ 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.ResponseDTO; import shop.mtcoding.metamall.dto.user.UserRequest; import shop.mtcoding.metamall.dto.user.UserResponse; import shop.mtcoding.metamall.model.log.login.LoginLog; @@ -16,6 +17,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 +29,26 @@ 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().body(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("인증되지 않았습니다"); } @@ -54,7 +67,7 @@ public ResponseEntity login(@RequestBody UserRequest.LoginDto loginDto, HttpS loginLogRepository.save(loginLog); // 6. 응답 DTO 생성 - ResponseDto responseDto = new ResponseDto<>().data(loginUser); + ResponseDTO responseDto = new ResponseDTO<>().data(loginUser); return ResponseEntity.ok().header(JwtProvider.HEADER, jwt).body(responseDto); } else { throw new Exception400("", "유저네임 혹은 아이디가 잘못되었습니다"); 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..b7ce3e5 --- /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. 최종 수집 + } + } +} 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..4a54dfe --- /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/user/UserRequest.java b/src/main/java/shop/mtcoding/metamall/dto/user/UserRequest.java index 80947db..20546a1 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,54 @@ 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 RoleUpdateDTO { + @NotEmpty + private String role; + } + + @Getter @Setter + public static class LoginDTO { + @NotEmpty private String username; + @NotEmpty private String password; } + + @Getter @Setter + public static class JoinDTO { + @NotEmpty + @Size(min = 3, max = 20) + private String username; + + @NotEmpty + @Size(min = 3, 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 를 만들면 된다. + public User toEntity(){ + return User.builder() + .username(username) + .password(password) + .email(email) + .role(role) + .status(true) + .build(); + } + } } diff --git a/src/main/java/shop/mtcoding/metamall/model/order/product/OrderProduct.java b/src/main/java/shop/mtcoding/metamall/model/order/product/OrderProduct.java index d26e522..829ad69 100644 --- a/src/main/java/shop/mtcoding/metamall/model/order/product/OrderProduct.java +++ b/src/main/java/shop/mtcoding/metamall/model/order/product/OrderProduct.java @@ -1,5 +1,6 @@ package shop.mtcoding.metamall.model.order.product; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -21,6 +22,7 @@ public class OrderProduct { // 주문 상품 private Long id; // checkpoint -> 무한참조 + @JsonIgnoreProperties({"seller"}) @ManyToOne private Product product; diff --git a/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheet.java b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheet.java index be8d9b4..888b853 100644 --- a/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheet.java +++ b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheet.java @@ -1,5 +1,6 @@ package shop.mtcoding.metamall.model.order.sheet; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @@ -26,6 +27,7 @@ public class OrderSheet { // 주문서 private User user; // 주문자 // checkpoint -> 무한참조 + @JsonIgnoreProperties({"orderSheet"}) @OneToMany(mappedBy = "orderSheet", cascade = CascadeType.ALL, orphanRemoval = true) private List orderProductList = new ArrayList<>(); // 총 주문 상품 리스트 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 a3899a9..5957f27 100644 --- a/src/main/java/shop/mtcoding/metamall/model/user/User.java +++ b/src/main/java/shop/mtcoding/metamall/model/user/User.java @@ -7,6 +7,7 @@ import lombok.Setter; import javax.persistence.*; +import javax.validation.constraints.NotEmpty; import java.time.LocalDateTime; @NoArgsConstructor @@ -43,11 +44,11 @@ public class User { private LocalDateTime updatedAt; // 권한 변경 (관리자) - public void updateRole() { + public void updateRole(@NotEmpty String role) { if (this.role.equals(role)) { // checkpoint 동일한 권한으로 변경할 수 없습니다. } - this.role = role; + this.role = this.role; } // 회원 탈퇴 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..6e2d4cf --- /dev/null +++ b/src/test/java/shop/mtcoding/metamall/regex/RegexTest.java @@ -0,0 +1,107 @@ +package shop.mtcoding.metamall.regex; + +import org.junit.jupiter.api.Test; + +import java.util.regex.Pattern; + +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); + } +}