diff --git a/README.md b/README.md new file mode 100644 index 0000000..c1f3cef --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# Springboot-MetaMall-Project +--- +## 1. 사용 기술 +- Filter +- Jwt +- Aop +- RoleInterceptor(권한 체크 ADMIN 여부) +- SessionArgumentResolver(세션 주입하기) +- ExceptionAdvice(예외핸들러) +- ValidAdvice(유효성검사) +- ErrorLogAdvice(에러로그 데이터베이스 기록) +- SameUserIdAdvice(자원 소유자 확인) +- Exception400, Exception401, Exception403, Exception, 404처리 +- MyDateUtil(시간 포멧해서 응답) +- MyFilterResponseUtil(필터는 예외핸들러를 사용못하기 때문에 재사용 메서드 생성) +- test/RegexTest(정규표현식 테스트) https://github.com/codingspecialist/junit-bank-class/tree/main/class-note/regex +스프링부트 새로운 설정설정 (log4j, DB 파라메터 trace, 404처리) +- Hibernate + JPA +- 양방향 매핑 +- Lazy Loading +- join fetch +- default_batch_fetch_size: 100 (인쿼리) +- 영속, 비영속, 준영속 +- 더티체킹 +- Repository Test +- Controller Test + +## 2. hibernateLazyInitializer 해결법 +--- +원인은 MessageConverter가 비어있는 객체를 Lazy Loading할 때 발생한다. Jackson 라이브러리는 객체를 직렬화할 때 프록시 객체를 처리할 수 없기 때문이다. +- 직접 Lazy Loading 하기 (강력 추천 - 서비스 레이어에서 DTO 만들 때 사용하면 됨) +- join fetch 하기 (강력 추천) +- Eager 전략으로 변경하기 (현재 추천 - 서비스가 없으니까!!) +- fail-on-empty-beans: false (비 추천) 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..bb46d27 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,11 @@ 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..9eda0ec 100644 --- a/src/main/java/shop/mtcoding/metamall/config/FilterRegisterConfig.java +++ b/src/main/java/shop/mtcoding/metamall/config/FilterRegisterConfig.java @@ -3,16 +3,25 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import shop.mtcoding.metamall.core.filter.JwtVerifyFilter; +import shop.mtcoding.metamall.core.filter.MyJwtVerifyFilter; @Configuration -public class FilterRegisterConfig { +public class FilterRegisterConfig { // 인증 체크 @Bean public FilterRegistrationBean jwtVerifyFilterAdd() { - FilterRegistrationBean registration = new FilterRegistrationBean<>(); - registration.setFilter(new JwtVerifyFilter()); - registration.addUrlPatterns("/user/*"); + FilterRegistrationBean registration = new + FilterRegistrationBean<>(); + registration.setFilter(new MyJwtVerifyFilter()); + + 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..1bf650c --- /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) { // CORS 설정 + 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..88488ca --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/AdminController.java @@ -0,0 +1,33 @@ +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.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..6a4c961 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/OrderController.java @@ -0,0 +1,147 @@ +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..815c153 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/controller/ProductController.java @@ -0,0 +1,111 @@ +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.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.transaction.Transactional; +import javax.validation.Valid; + +/** + * 상품등록 상품목록보기 상품상세보기 상품수정하기 상품삭제하기 + */ +@RequiredArgsConstructor +@RestController +public class ProductController { + + private final ProductRepository productRepository; + private final UserRepository userRepository; + private final HttpSession httpSession; + + /** + * 상품 등록 + */ + // seller인지 아닌지는 할 필요 없다. -> 인터셉터가 판매자인지 권한 체크를 하니까 + @PostMapping("/seller/products") // 앞에 seller가 있다? -> interceptor가 권한 판단 + 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); + } + + /** + * 상품삭제하기 + */ + @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 ddfee94..a9ad018 100644 --- a/src/main/java/shop/mtcoding/metamall/controller/UserController.java +++ b/src/main/java/shop/mtcoding/metamall/controller/UserController.java @@ -2,13 +2,13 @@ import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; +import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; import shop.mtcoding.metamall.core.exception.Exception400; import shop.mtcoding.metamall.core.exception.Exception401; import shop.mtcoding.metamall.core.jwt.JwtProvider; -import shop.mtcoding.metamall.dto.ResponseDto; +import shop.mtcoding.metamall.dto.ResponseDTO; import shop.mtcoding.metamall.dto.user.UserRequest; -import shop.mtcoding.metamall.dto.user.UserResponse; import shop.mtcoding.metamall.model.log.login.LoginLog; import shop.mtcoding.metamall.model.log.login.LoginLogRepository; import shop.mtcoding.metamall.model.user.User; @@ -16,6 +16,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import javax.validation.Valid; import java.time.LocalDateTime; import java.util.Optional; @@ -27,15 +28,27 @@ public class UserController { private final LoginLogRepository loginLogRepository; private final HttpSession session; + // 핵심로직에 신경쓰자 + @PostMapping("/join") + public ResponseEntity join(@RequestBody @Valid UserRequest.JoinDto joinDto, Errors errors) { + User userPS = userRepository.save(joinDto.toEntity()); + // RESTapi -> insert, update, select 된 모든 데이터를 응답해야 한다. + ResponseDTO responseDTO = new ResponseDTO<>().data(userPS); + return ResponseEntity.ok().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, // loginDto의 에러가 모이는 곳! + 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,10 +67,10 @@ 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("유저네임 혹은 아이디가 잘못되었습니다"); + 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..03910b1 --- /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 shop.mtcoding.metamall.core.session.SessionUser; +import shop.mtcoding.metamall.model.log.error.ErrorLog; +import shop.mtcoding.metamall.model.log.error.ErrorLogRepository; + +import javax.servlet.http.HttpSession; + +@Aspect +@Component +@RequiredArgsConstructor +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 50ebee2..e16b462 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,14 @@ 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 @@ -13,30 +17,44 @@ @RestControllerAdvice public class MyExceptionAdvice { - private final ErrorLogRepository errorLogRepository; - + @MyErrorLogRecord @ExceptionHandler(Exception400.class) public ResponseEntity badRequest(Exception400 e){ - return new ResponseEntity<>(e.body(), e.status()); + // trace -> debug -> info -> warn -> error (포함관계, application.yml 테스트 -> DEBUG) + 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..59c51fa --- /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..cee65aa --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/advice/MyValidAdvice.java @@ -0,0 +1,36 @@ +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..7ba1ee2 --- /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 { // path variable id 값을 세션 값과 비교 +} 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..f3edddd --- /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/exception/Exception400.java b/src/main/java/shop/mtcoding/metamall/core/exception/Exception400.java index d1b5fec..28f24c3 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..e65c2fc 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,8 +12,8 @@ public Exception403(String message) { super(message); } - public ResponseDto body(){ - ResponseDto responseDto = new ResponseDto<>(); + public ResponseDTO body(){ + ResponseDTO responseDto = new ResponseDTO<>(); responseDto.fail(HttpStatus.FORBIDDEN, "forbidden", 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/core/filter/JwtVerifyFilter.java b/src/main/java/shop/mtcoding/metamall/core/filter/MyJwtVerifyFilter.java similarity index 58% rename from src/main/java/shop/mtcoding/metamall/core/filter/JwtVerifyFilter.java rename to src/main/java/shop/mtcoding/metamall/core/filter/MyJwtVerifyFilter.java index 870bf93..46eabcd 100644 --- a/src/main/java/shop/mtcoding/metamall/core/filter/JwtVerifyFilter.java +++ b/src/main/java/shop/mtcoding/metamall/core/filter/MyJwtVerifyFilter.java @@ -4,12 +4,10 @@ import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.DecodedJWT; -import com.fasterxml.jackson.databind.ObjectMapper; -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 javax.servlet.*; import javax.servlet.http.HttpServletRequest; @@ -17,42 +15,37 @@ import javax.servlet.http.HttpSession; import java.io.IOException; -public class JwtVerifyFilter implements Filter { +// 인증 체크 +public class MyJwtVerifyFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("디버그 : JwtVerifyFilter 동작함"); HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String prefixJwt = req.getHeader(JwtProvider.HEADER); + if(prefixJwt == null){ - error(resp, new Exception400("토큰이 전달되지 않았습니다")); + MyFilterResponseUtil.badRequest(resp, new Exception400("authorization", "토큰이 전달되지 않았습니다.")); return; } + String jwt = prefixJwt.replace(JwtProvider.TOKEN_PREFIX, ""); + try { DecodedJWT decodedJWT = JwtProvider.verify(jwt); - int id = decodedJWT.getClaim("id").asInt(); + Long id = decodedJWT.getClaim("id").asLong(); String role = decodedJWT.getClaim("role").asString(); // 세션을 사용하는 이유는 권한처리를 하기 위해서이다. HttpSession session = req.getSession(); - LoginUser loginUser = LoginUser.builder().id(id).role(role).build(); - session.setAttribute("loginUser", loginUser); + SessionUser loginUser = SessionUser.builder().id(id).role(role).build(); + session.setAttribute("sessionUser", loginUser); 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..4c7d9f6 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/interceptor/MyAdminInterceptor.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 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..d3f0f59 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/interceptor/MySellerInterceptor.java @@ -0,0 +1,26 @@ +package shop.mtcoding.metamall.core.interceptor; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerInterceptor; +import shop.mtcoding.metamall.core.exception.Exception403; +import shop.mtcoding.metamall.core.session.SessionUser; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + + +@Configuration +public class MySellerInterceptor implements HandlerInterceptor { // 동작 시점 -> 주소 seller + @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..b6e0cdf --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/resolver/MySessionArgumentResolver.java @@ -0,0 +1,36 @@ +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 check2 && check1; + } + + @Override + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) + throws Exception { + + return session.getAttribute("sessionUser"); + } +} diff --git a/src/main/java/shop/mtcoding/metamall/core/session/LoginUser.java b/src/main/java/shop/mtcoding/metamall/core/session/SessionUser.java similarity index 66% rename from src/main/java/shop/mtcoding/metamall/core/session/LoginUser.java rename to src/main/java/shop/mtcoding/metamall/core/session/SessionUser.java index 59f402c..20b138b 100644 --- a/src/main/java/shop/mtcoding/metamall/core/session/LoginUser.java +++ b/src/main/java/shop/mtcoding/metamall/core/session/SessionUser.java @@ -4,12 +4,12 @@ import lombok.Getter; @Getter -public class LoginUser { - private Integer id; +public class SessionUser { + private Long id; private String role; @Builder - public LoginUser(Integer id, String role) { + public SessionUser(Long id, String role) { this.id = id; this.role = role; } diff --git a/src/main/java/shop/mtcoding/metamall/util/MyDateUtil.java b/src/main/java/shop/mtcoding/metamall/core/util/MyDateUtil.java similarity index 86% rename from src/main/java/shop/mtcoding/metamall/util/MyDateUtil.java rename to src/main/java/shop/mtcoding/metamall/core/util/MyDateUtil.java index 42ba271..3f92cf6 100644 --- a/src/main/java/shop/mtcoding/metamall/util/MyDateUtil.java +++ b/src/main/java/shop/mtcoding/metamall/core/util/MyDateUtil.java @@ -1,4 +1,4 @@ -package shop.mtcoding.metamall.util; +package shop.mtcoding.metamall.core.util; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; diff --git a/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java b/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java new file mode 100644 index 0000000..ea2f452 --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/core/util/MyFilterResponseUtil.java @@ -0,0 +1,48 @@ +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; + +// Fiter는 예외 핸들러로 처리 못한다 -> throw 못함 +public class MyFilterResponseUtil { + + public static void badRequest(HttpServletResponse resp, Exception400 e) throws IOException { + + resp.setStatus(400); // 인증 X + 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); // 인증 X + 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); // 권한 X + 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..36c8e33 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/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..33dd2de --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/order/OrderRequest.java @@ -0,0 +1,47 @@ +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..c117bad --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/dto/product/ProductRequest.java @@ -0,0 +1,45 @@ +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..8c4a2c2 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,55 @@ 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 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 = 4, max = 20) // DB에는 60자가 들어가겠지만 여기서는 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 무조건 + public User toEntity() { + return User.builder() + .username(username) + .password(password) + .email(email) + .role(role) + .status(true) + .build(); + } + } + + @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..8a574f4 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,7 +17,10 @@ public class ErrorLog { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + @Column(nullable = false, length = 100000) private String msg; + private Long userId; private LocalDateTime createdAt; 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 68% 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..f141079 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,28 +20,40 @@ 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; @ManyToOne private OrderSheet orderSheet; + // checkpoint -> 편의 메소드 만드는 이유 + public void syncOrderSheet(OrderSheet orderSheet) { + this.orderSheet = orderSheet; + } + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); } - @PreUpdate protected void onUpdate() { this.updatedAt = LocalDateTime.now(); } - @Builder - public OrderProduct(Long id, Product product, Integer count, Integer orderPrice, LocalDateTime createdAt, LocalDateTime updatedAt, OrderSheet orderSheet) { + public OrderProduct(Long id, Product product, Integer count, Integer orderPrice, + LocalDateTime createdAt, LocalDateTime updatedAt, OrderSheet orderSheet) { this.id = id; this.product = product; this.count = count; 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 58% 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..11a5398 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,12 @@ -package shop.mtcoding.metamall.model.ordersheet; +package shop.mtcoding.metamall.model.order.sheet; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import shop.mtcoding.metamall.model.orderproduct.OrderProduct; -import shop.mtcoding.metamall.model.product.Product; +import shop.mtcoding.metamall.model.order.product.OrderProduct; import shop.mtcoding.metamall.model.user.User; import javax.persistence.*; @@ -22,26 +23,41 @@ public class OrderSheet { // 주문서 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @ManyToOne private User user; // 주문자 - @OneToMany(mappedBy = "orderSheet") + + // 양방향 맵핑: 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(); } - @PreUpdate protected void onUpdate() { this.updatedAt = LocalDateTime.now(); } - // 연관관계 메서드 구현 필요 - @Builder public OrderSheet(Long id, User user, Integer totalPrice, LocalDateTime createdAt, LocalDateTime updatedAt) { this.id = id; diff --git a/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java new file mode 100644 index 0000000..575834b --- /dev/null +++ b/src/main/java/shop/mtcoding/metamall/model/order/sheet/OrderSheetRepository.java @@ -0,0 +1,13 @@ +package shop.mtcoding.metamall.model.order.sheet; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface OrderSheetRepository extends JpaRepository { + // 내가 주문한 목록보기 + @Query("select os from OrderSheet os where os.user.id = :userId") + List findByUserId(@Param("userId") Long userId); +} diff --git a/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheetRepository.java b/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheetRepository.java deleted file mode 100644 index 5d59249..0000000 --- a/src/main/java/shop/mtcoding/metamall/model/ordersheet/OrderSheetRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package shop.mtcoding.metamall.model.ordersheet; - -import org.springframework.data.jpa.repository.JpaRepository; - -public interface OrderSheetRepository extends JpaRepository { -} diff --git a/src/main/java/shop/mtcoding/metamall/model/product/Product.java b/src/main/java/shop/mtcoding/metamall/model/product/Product.java index bc8c618..f3eba0b 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,25 +18,55 @@ public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + @ManyToOne + private User seller; // 판매자 1명 + + @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(); } - @PreUpdate protected void onUpdate() { this.updatedAt = LocalDateTime.now(); } - @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..a365d5e 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; @@ -9,38 +10,67 @@ import java.time.LocalDateTime; @NoArgsConstructor -@Setter // DTO 만들면 삭제해야됨 +@Setter // DTO 만들면 삭제해야됨 -> Entity setter X @Getter @Table(name = "user_tb") @Entity public class User { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + + @Column(unique = true, nullable = false, length = 20) private String username; + + @JsonIgnore // MessageConverter가 파싱하지 않도록 + @Column(nullable = false, length = 60) private String password; + + @Column(nullable = false, length = 50) private String email; - private String role; // USER(고객), SELLER(판매자), ADMIN(관리자) + + @Column(nullable = false, length = 10) + private String role; // USER(고객), SELLER(판매자), ADMIN(관리자) -> ENUM으로 만들면 좋다 + + @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 동일한 권한으로 변경할 수 없습니다. + } + this.role = role; + } + + // 회원 탈퇴 + public void delete() { + this.status = false; + } + @PrePersist protected void onCreate() { this.createdAt = LocalDateTime.now(); } - @PreUpdate protected void onUpdate() { this.updatedAt = LocalDateTime.now(); } - @Builder - public User(Long id, String username, String password, String email, String role, LocalDateTime createdAt) { + public User(Long id, String username, String password, String email, String role, + Boolean status, LocalDateTime createdAt, LocalDateTime updatedAt) { this.id = id; this.username = username; this.password = password; this.email = email; this.role = role; + this.status = status; this.createdAt = createdAt; + this.updatedAt = updatedAt; } } diff --git a/src/main/java/shop/mtcoding/metamall/model/user/UserRepository.java b/src/main/java/shop/mtcoding/metamall/model/user/UserRepository.java index 293a101..2f642f9 100644 --- a/src/main/java/shop/mtcoding/metamall/model/user/UserRepository.java +++ b/src/main/java/shop/mtcoding/metamall/model/user/UserRepository.java @@ -6,7 +6,7 @@ import java.util.Optional; -public interface UserRepository extends JpaRepository { +public interface UserRepository extends JpaRepository { @Query("select u from User u where u.username = :username") Optional findByUsername(@Param("username") String username); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 1d9bd50..4c62521 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,8 +19,18 @@ spring: properties: hibernate: format_sql: true - default_batch_fetch_size: 100 # in query 자동 작성 - + # in query 자동 작성 + default_batch_fetch_size: 100 # 인쿼리 + # 404 처리하는 법 + mvc: + throw-exception-if-no-handler-found: true + web: + resources: + add-mappings: false + # hibernateLazyInitializer 오류 해결법 +#jackson: +# serialization: +# fail-on-empty-beans: false logging: level: '[shop.mtcoding.metamall]': DEBUG # DEBUG 레벨부터 에러 확인할 수 있게 설정하기 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..0b662b6 --- /dev/null +++ b/src/test/java/shop/mtcoding/metamall/regex/RegexTest.java @@ -0,0 +1,116 @@ +package shop.mtcoding.metamall.regex; + +import org.junit.jupiter.api.Test; + +import java.util.regex.Pattern; + +/** + * 가장 좋은 방법은 ChatGPT에게 물어보는 것이다. [스프링부트에서 특수문자 제외시키는 정규표현식 알려줘] + */ +public class RegexTest { + + /** + * ^ $ -> 시작과 끝 표시 + * ^: 부정 + * 걍 gpt에게 물어보셈 ㅇㅇ + */ + @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); + } +} \ No newline at end of file