diff --git a/src/main/java/gift/main/Exception/ErrorCode.java b/src/main/java/gift/main/Exception/ErrorCode.java index 578d92224..1a477bd5e 100644 --- a/src/main/java/gift/main/Exception/ErrorCode.java +++ b/src/main/java/gift/main/Exception/ErrorCode.java @@ -8,16 +8,22 @@ public enum ErrorCode { EMPTY_NAME(HttpStatus.BAD_REQUEST, "이름을 채워주세요"), EMPTY_PASSWORD(HttpStatus.BAD_REQUEST, "비밀번호를 채워주세요"), + //인증관련 NO_TOKEN(HttpStatus.UNAUTHORIZED, "토큰이 비어있습니다."), INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "인증에 실패했습니다."), + NO_PERMISSION(HttpStatus.UNAUTHORIZED, "해당 페이지에 권합이 없습니다."), + NO_PERMISSION_PRODUCT(HttpStatus.UNAUTHORIZED, "해당 상품에 권합이 없습니다."), + + //로그인 ALREADY_EMAIL(HttpStatus.BAD_REQUEST, "이미 존재하는 이메일입니다."), ERROR_LOGIN(HttpStatus.BAD_REQUEST, "이메일과 비밀번호를 정확히 입력해주세요"), + USER_NOT_FOUND(HttpStatus.BAD_REQUEST, "이메일과 비밀번호를 정확히 입력해주세요"), + PRODUCT_NOT_FOUND(HttpStatus.NOT_FOUND, "해당 제품을 찾을 수 없습니다."), ; //이메일과 비밀번호 코드가 401이 아닌 400인 이유: 코드를 보고 해당 유저가 있다고 판단할 것 같아서 - private final HttpStatus httpStatus; private final String errorMessage; diff --git a/src/main/java/gift/main/Exception/GlobalExceptionHandler.java b/src/main/java/gift/main/Exception/GlobalExceptionHandler.java index 15819379b..713413e46 100644 --- a/src/main/java/gift/main/Exception/GlobalExceptionHandler.java +++ b/src/main/java/gift/main/Exception/GlobalExceptionHandler.java @@ -1,4 +1,5 @@ package gift.main.Exception; + import io.jsonwebtoken.security.SignatureException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -20,7 +21,7 @@ public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public String handleGeneralException(Model model, Exception e) { - model.addAttribute("error",e.getMessage()); + model.addAttribute("error", e.getMessage()); String refererUrl = " http://localhost:8080/spring-gift/"; model.addAttribute("refererUrl", refererUrl); return "error/error"; diff --git a/src/main/java/gift/main/MainController.java b/src/main/java/gift/main/MainController.java index 3915bcc64..69b4e3148 100644 --- a/src/main/java/gift/main/MainController.java +++ b/src/main/java/gift/main/MainController.java @@ -1,6 +1,5 @@ package gift.main; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/src/main/java/gift/main/annotation/AdminCheck.java b/src/main/java/gift/main/annotation/AdminCheck.java new file mode 100644 index 000000000..b10e612fc --- /dev/null +++ b/src/main/java/gift/main/annotation/AdminCheck.java @@ -0,0 +1,11 @@ +package gift.main.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.TYPE}) //적용될 부분 +@Retention(RetentionPolicy.RUNTIME) +public @interface AdminCheck { +} diff --git a/src/main/java/gift/main/annotation/IsValidName.java b/src/main/java/gift/main/annotation/IsValidName.java index 86bfcfef6..8d10a7b11 100644 --- a/src/main/java/gift/main/annotation/IsValidName.java +++ b/src/main/java/gift/main/annotation/IsValidName.java @@ -5,11 +5,7 @@ import jakarta.validation.Constraint; import jakarta.validation.Payload; -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; -import java.lang.annotation.ElementType; -import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.*; @Documented diff --git a/src/main/java/gift/main/aop/AdminAspect.java b/src/main/java/gift/main/aop/AdminAspect.java new file mode 100644 index 000000000..23d61df54 --- /dev/null +++ b/src/main/java/gift/main/aop/AdminAspect.java @@ -0,0 +1,27 @@ +package gift.main.aop; + +import gift.main.Exception.CustomException; +import gift.main.Exception.ErrorCode; +import gift.main.annotation.SessionUser; +import gift.main.dto.UserVo; +import gift.main.entity.Role; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.springframework.stereotype.Component; + +/* +도입 유지 고민... + */ + +@Component +@Aspect +public class AdminAspect { + +// @Before("execution(* gift.main.controller.ProductController.*(..))") + public void checkAdmin(@SessionUser UserVo userVo) { + System.out.println("실행된다."); + if (!Role.ADMIN.equals(userVo.getRole())) { + throw new CustomException(ErrorCode.NO_PERMISSION); + } + } +} diff --git a/src/main/java/gift/main/config/WebConfig.java b/src/main/java/gift/main/config/WebConfig.java index 27817de81..11466a829 100644 --- a/src/main/java/gift/main/config/WebConfig.java +++ b/src/main/java/gift/main/config/WebConfig.java @@ -3,6 +3,7 @@ import gift.main.interceptor.AuthInterceptor; import gift.main.resolver.SessionUserArgumentResolver; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; @@ -12,6 +13,7 @@ @Configuration @EnableWebMvc +//@EnableAspectJAutoProxy(proxyTargetClass=true) public class WebConfig implements WebMvcConfigurer { private final AuthInterceptor authLoginInterceptor; diff --git a/src/main/java/gift/main/controller/AdminProductController.java b/src/main/java/gift/main/controller/AdminProductController.java deleted file mode 100644 index 9b051c8be..000000000 --- a/src/main/java/gift/main/controller/AdminProductController.java +++ /dev/null @@ -1,54 +0,0 @@ -package gift.main.controller; - -import gift.main.dto.ProductRequest; -import gift.main.entity.Product; -import gift.main.service.ProductService; -import jakarta.validation.Valid; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@RestController -@RequestMapping("/admin") -public class AdminProductController { - private final ProductService productService; - - public AdminProductController(ProductService productService) { - this.productService = productService; - } - - @GetMapping("/products") - public ResponseEntity getProducts() { - List products = productService.getProducts(); - return ResponseEntity.ok(products); - } - - @GetMapping("/product/{id}") - public ResponseEntity findProduct(@PathVariable(name = "id") Long id) { - Product product = productService.getProduct(id); - return ResponseEntity.ok(product); - } - - @PostMapping("/product") - public ResponseEntity addProduct(@Valid @RequestBody ProductRequest productRequest) { - productService.addProduct(productRequest); - return ResponseEntity.ok("Product added successfully"); - } - - @PutMapping("/product") - public ResponseEntity updateProduct(@RequestParam(value = "id") long id,@Valid @RequestBody ProductRequest productRequest) { - productService.updateProduct(id, productRequest); - return ResponseEntity.ok("Product updated successfully"); - } - - @DeleteMapping("/product/{id}") - public ResponseEntity deleteProduct(@PathVariable(name = "id") Long id) { - productService.deleteProduct(id); - return ResponseEntity.ok("Product deleted successfully"); - } - - -} diff --git a/src/main/java/gift/main/controller/ProductController.java b/src/main/java/gift/main/controller/ProductController.java new file mode 100644 index 000000000..0fb98625c --- /dev/null +++ b/src/main/java/gift/main/controller/ProductController.java @@ -0,0 +1,59 @@ +package gift.main.controller; + +import gift.main.annotation.AdminCheck; +import gift.main.annotation.SessionUser; +import gift.main.dto.ProductRequest; +import gift.main.dto.ProductResponce; +import gift.main.dto.UserVo; +import gift.main.service.ProductService; +import jakarta.validation.Valid; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/admin") +public class ProductController { + private final ProductService productService; + + public ProductController(ProductService productService) { + this.productService = productService; + } + + @GetMapping("/products") + public ResponseEntity getProducts(@SessionUser UserVo sessionUserVo) { + List products = productService.getProducts(); + return ResponseEntity.ok(products); + } + + @GetMapping("/product/{id}") + public ResponseEntity findProduct(@PathVariable(name = "id") Long id, @SessionUser UserVo sessionUserVo) { + ProductResponce product = productService.getProduct(id); + return ResponseEntity.ok(product); + } + + @PostMapping("/product") + public ResponseEntity addProduct(@Valid @RequestBody ProductRequest productRequest, @SessionUser UserVo sessionUserVo) { + productService.addProduct(productRequest, sessionUserVo); + return ResponseEntity.ok("Product added successfully"); + } + + @PutMapping("/product") + public ResponseEntity updateProduct( + @RequestParam(value = "id") long id, + @Valid @RequestBody ProductRequest productRequest, + @SessionUser UserVo sessionUserVo) { + + productService.updateProduct(id, productRequest); + return ResponseEntity.ok("Product added successfully"); + } + + @DeleteMapping("/product/{id}") + public ResponseEntity deleteProduct(@PathVariable(name = "id") Long id) { + productService.deleteProduct(id); + return ResponseEntity.ok("Product deleted successfully"); + } + + +} diff --git a/src/main/java/gift/main/controller/WishProductController.java b/src/main/java/gift/main/controller/WishProductController.java index 25870bedf..79f4d0902 100644 --- a/src/main/java/gift/main/controller/WishProductController.java +++ b/src/main/java/gift/main/controller/WishProductController.java @@ -1,6 +1,7 @@ package gift.main.controller; import gift.main.annotation.SessionUser; +import gift.main.dto.ProductResponce; import gift.main.dto.UserVo; import gift.main.entity.Product; import gift.main.entity.WishProduct; @@ -10,9 +11,7 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; -import java.util.HashMap; import java.util.List; -import java.util.Map; @RestController @RequestMapping("/product") @@ -28,32 +27,27 @@ public WishProductController(WishProductService wishProductService, ProductServi @GetMapping public ResponseEntity getProducts() { - List products = productService.getProducts(); - Map> response = new HashMap<>(); - response.put("products", products); - return ResponseEntity.ok(response); + List products = productService.getProducts(); + return ResponseEntity.ok(products); } @DeleteMapping("/wishlist/{productId}") @Transactional public ResponseEntity deleteWishProduct(@PathVariable(name = "productId") Long productId, @SessionUser UserVo sessionUserVo) { wishProductService.deleteProducts(productId, sessionUserVo); - return ResponseEntity.ok("성공적으로 삭제 완료~!"); + return ResponseEntity.ok("successfully deleted the item to your wishlist"); } @GetMapping("/wishlist") public ResponseEntity getWishProduct(@SessionUser UserVo sessionUser) { List wishProducts = wishProductService.getWishProducts(sessionUser.getId()); - Map> response = new HashMap<>(); - response.put("wishlistProducts", wishProducts); - return ResponseEntity.ok(response); - } + return ResponseEntity.ok(wishProducts); } @Transactional @PostMapping("/wishlist/{productId}") - public ResponseEntity addWishlistProduct(@PathVariable(name = "productId") Long productId, @SessionUser UserVo sessionUser){ + public ResponseEntity addWishlistProduct(@PathVariable(name = "productId") Long productId, @SessionUser UserVo sessionUser) { wishProductService.addWishlistProduct(productId, sessionUser); - return ResponseEntity.ok("성공적으로 등록~"); + return ResponseEntity.ok("successfully added the item to your wishlist"); } } diff --git a/src/main/java/gift/main/dto/ProductDto.java b/src/main/java/gift/main/dto/ProductDto.java deleted file mode 100644 index 11224f692..000000000 --- a/src/main/java/gift/main/dto/ProductDto.java +++ /dev/null @@ -1,36 +0,0 @@ -package gift.main.dto; - - -public class ProductDto { - - private String name; - - private int price; - - private String imageUrl; - - public ProductDto(String name, int price, String imageUrl) { - this.name = name; - this.price = price; - this.imageUrl = imageUrl; - } - - public ProductDto(ProductRequest productRequest) { - this.name = productRequest.name(); - this.price = productRequest.price(); - this.imageUrl = productRequest.imageUrl(); - } - - - public String getName() { - return name; - } - - public int getPrice() { - return price; - } - - public String getImageUrl() { - return imageUrl; - } -} diff --git a/src/main/java/gift/main/dto/ProductRequest.java b/src/main/java/gift/main/dto/ProductRequest.java index 0a86d4222..2d85c6b44 100644 --- a/src/main/java/gift/main/dto/ProductRequest.java +++ b/src/main/java/gift/main/dto/ProductRequest.java @@ -5,8 +5,7 @@ import jakarta.validation.constraints.PositiveOrZero; public record ProductRequest( - @IsValidName String name, - @PositiveOrZero(message = "상품 가격은 음수일 수 없습니다.") int price, - @NotBlank(message = "이미지주소를 등록해주세요.") String imageUrl) { - + @IsValidName String name, + @PositiveOrZero(message = "상품 가격은 음수일 수 없습니다.") int price, + @NotBlank(message = "이미지주소를 등록해주세요.") String imageUrl) { } diff --git a/src/main/java/gift/main/dto/ProductResponce.java b/src/main/java/gift/main/dto/ProductResponce.java new file mode 100644 index 000000000..e4102e94e --- /dev/null +++ b/src/main/java/gift/main/dto/ProductResponce.java @@ -0,0 +1,10 @@ +package gift.main.dto; + +import gift.main.entity.Product; + +public record ProductResponce(Long id, String name, int price, String imageUrl, String seller) { + + public ProductResponce(Product product) { + this(product.getId(), product.getName(), product.getPrice(), product.getImageUrl(), product.getSellerName()); + } +} diff --git a/src/main/java/gift/main/dto/UserDto.java b/src/main/java/gift/main/dto/UserDto.java index f0fc27aa3..962969679 100644 --- a/src/main/java/gift/main/dto/UserDto.java +++ b/src/main/java/gift/main/dto/UserDto.java @@ -1,7 +1,7 @@ package gift.main.dto; -public class UserDto { +public class UserDto { private final String name; private final String email; private final String password; diff --git a/src/main/java/gift/main/dto/UserJoinRequest.java b/src/main/java/gift/main/dto/UserJoinRequest.java index b78d07ac0..5482f9bb2 100644 --- a/src/main/java/gift/main/dto/UserJoinRequest.java +++ b/src/main/java/gift/main/dto/UserJoinRequest.java @@ -11,7 +11,7 @@ public record UserJoinRequest( String email, @NotBlank(message = "패스워드 입력해주세요.") String password, - String role ) { + String role) { } diff --git a/src/main/java/gift/main/entity/Product.java b/src/main/java/gift/main/entity/Product.java index 4376cbb0d..1d5436d2d 100644 --- a/src/main/java/gift/main/entity/Product.java +++ b/src/main/java/gift/main/entity/Product.java @@ -12,44 +12,44 @@ public class Product { @Column(nullable = false) private String name; + @Column(nullable = false, columnDefinition = "decimal(10,2) check (price >= 0)") private int price; + @Column(nullable = false) private String imageUrl; + @ManyToOne + @JoinColumn(name = "seller_id") + private User seller; + public Product() { } - public Product(ProductRequest productRequest) { + public Product(ProductRequest productRequest, User seller) { this.name = productRequest.name(); this.price = productRequest.price(); this.imageUrl = productRequest.imageUrl(); + this.seller = seller; } - public Product(long id, String name, int price, String imageUrl) { - this.id = id; + public Product(String name, int price, String imageUrl, User seller) { this.name = name; this.price = price; this.imageUrl = imageUrl; + this.seller = seller; } - public Product(String name, int price, String imageUrl) { - this.name = name; - this.price = price; - this.imageUrl = imageUrl; - + public void updateValue(ProductRequest productRequest) { + this.name = productRequest.name(); + this.price = productRequest.price(); + this.imageUrl = productRequest.imageUrl(); } - public void setName(String name) { + public void updateValue(String name, int price, String imageUrl) { this.name = name; - } - - public void setPrice(int price) { this.price = price; - } - - public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } @@ -69,4 +69,8 @@ public String getImageUrl() { return imageUrl; } + public String getSellerName() { + return seller.getName(); + } + } diff --git a/src/main/java/gift/main/entity/User.java b/src/main/java/gift/main/entity/User.java index 15fe9905a..40fd5a46a 100644 --- a/src/main/java/gift/main/entity/User.java +++ b/src/main/java/gift/main/entity/User.java @@ -42,7 +42,6 @@ public User(String name, String email, String password, Role role) { } - public User(long id, String name, String email, String password, String role) { this.id = id; this.name = name; diff --git a/src/main/java/gift/main/entity/WishProduct.java b/src/main/java/gift/main/entity/WishProduct.java index 8ee2bb0eb..95181e242 100644 --- a/src/main/java/gift/main/entity/WishProduct.java +++ b/src/main/java/gift/main/entity/WishProduct.java @@ -9,33 +9,33 @@ public class WishProduct { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @Column(nullable = false) - private Long productId; - @Column(nullable = false) - private Long userId; - - public WishProduct(Long productId, Long userId) { - this.productId = productId; - this.userId = userId; - } + @ManyToOne + @JoinColumn(name = "prduct_id") + public Product product; + + @ManyToOne + @JoinColumn(name = "user_id") + public User user; public WishProduct() { } - public Long getProductId() { - return productId; + public WishProduct(Product product, User user) { + this.product = product; + this.user = user; } - public Long getUserId() { - return userId; + public Long getId() { + return id; } - public void setId(Long id) { - this.id = id; + public Product getProduct() { + return product; } - public Long getId() { - return id; + public User getUser() { + return user; + } } diff --git a/src/main/java/gift/main/interceptor/AuthInterceptor.java b/src/main/java/gift/main/interceptor/AuthInterceptor.java index b4bf8e097..bc4a04014 100644 --- a/src/main/java/gift/main/interceptor/AuthInterceptor.java +++ b/src/main/java/gift/main/interceptor/AuthInterceptor.java @@ -1,8 +1,8 @@ package gift.main.interceptor; -import gift.main.dto.UserVo; import gift.main.Exception.CustomException; import gift.main.Exception.ErrorCode; +import gift.main.dto.UserVo; import gift.main.util.JwtUtil; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/gift/main/repository/ProductRepository.java b/src/main/java/gift/main/repository/ProductRepository.java index ca96bef5d..609cac2f5 100644 --- a/src/main/java/gift/main/repository/ProductRepository.java +++ b/src/main/java/gift/main/repository/ProductRepository.java @@ -4,7 +4,10 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import java.util.Optional; + @Repository public interface ProductRepository extends JpaRepository { + Optional findById(Long id); } diff --git a/src/main/java/gift/main/repository/UserRepository.java b/src/main/java/gift/main/repository/UserRepository.java index 0e195ca2d..81b8ef5d5 100644 --- a/src/main/java/gift/main/repository/UserRepository.java +++ b/src/main/java/gift/main/repository/UserRepository.java @@ -4,9 +4,15 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import java.util.Optional; + @Repository public interface UserRepository extends JpaRepository { boolean existsByEmail(String email); - User findByEmailAndPassword(String email, String password); + Optional findByEmailAndPassword(String email, String password); + + Optional findByEmail(String email); + + Optional findById(Long id); } diff --git a/src/main/java/gift/main/repository/WishProductRepository.java b/src/main/java/gift/main/repository/WishProductRepository.java index 29ea500e6..80abd5fc3 100644 --- a/src/main/java/gift/main/repository/WishProductRepository.java +++ b/src/main/java/gift/main/repository/WishProductRepository.java @@ -5,9 +5,12 @@ import org.springframework.stereotype.Repository; import java.util.List; +import java.util.Optional; @Repository public interface WishProductRepository extends JpaRepository { void deleteByProductIdAndUserId(Long productId, Long userId); - List findAllByUserId(Long userId); + + Optional> findAllByUserId(Long userId); + } diff --git a/src/main/java/gift/main/resolver/SessionUserArgumentResolver.java b/src/main/java/gift/main/resolver/SessionUserArgumentResolver.java index fcd49ead6..0b8a73cb6 100644 --- a/src/main/java/gift/main/resolver/SessionUserArgumentResolver.java +++ b/src/main/java/gift/main/resolver/SessionUserArgumentResolver.java @@ -4,7 +4,6 @@ import gift.main.dto.UserVo; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; -import jakarta.websocket.Session; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; @@ -19,7 +18,6 @@ public boolean supportsParameter(MethodParameter parameter) { } - @Override //넣어줄 반환값을 넣어준다. public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(HttpServletRequest.class); diff --git a/src/main/java/gift/main/service/ProductService.java b/src/main/java/gift/main/service/ProductService.java index 5e7032135..4b9f6d6a8 100644 --- a/src/main/java/gift/main/service/ProductService.java +++ b/src/main/java/gift/main/service/ProductService.java @@ -3,30 +3,42 @@ import gift.main.Exception.CustomException; import gift.main.Exception.ErrorCode; import gift.main.dto.ProductRequest; +import gift.main.dto.ProductResponce; +import gift.main.dto.UserVo; import gift.main.entity.Product; +import gift.main.entity.User; import gift.main.repository.ProductRepository; +import gift.main.repository.UserRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - import java.util.List; +import java.util.stream.Collectors; @Service public class ProductService { private final ProductRepository productRepository; + private final UserRepository userRepository; - public ProductService(ProductRepository productRepository) { + public ProductService(ProductRepository productRepository, UserRepository userRepository) { this.productRepository = productRepository; + this.userRepository = userRepository; } - public List getProducts() { - List productList = productRepository.findAll(); - return productList; + public List getProducts() { + List productResponces = productRepository.findAll() + .stream() + .map(product -> new ProductResponce(product)) //스트림 요소를 다른 형태로 바꾸는 메서드 + .collect(Collectors.toList()); //변환된 요소 각각을 리스트로~! + + return productResponces; } @Transactional - public void addProduct(ProductRequest productRequest) { - Product product = new Product(productRequest); + public void addProduct(ProductRequest productRequest, UserVo user) { + User seller = userRepository.findById(user.getId()) + .orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)); + Product product = new Product(productRequest, seller); productRepository.save(product); } @@ -36,27 +48,22 @@ public void deleteProduct(long id) { } @Transactional - public void updateProduct(long id,ProductRequest productRequest) { + public void updateProduct(long id, ProductRequest productRequest) { Product product = productRepository.findById(id) .orElseThrow(() -> new CustomException(ErrorCode.PRODUCT_NOT_FOUND)); - product.setName(product.getName()); - product.setPrice(product.getPrice()); - product.setImageUrl(product.getImageUrl()); - + product.updateValue(productRequest); productRepository.save(product); } - public Product getProduct(long id) { + public ProductResponce getProduct(long id) { Product product = productRepository.findById(id) .orElseThrow(() -> new CustomException(ErrorCode.PRODUCT_NOT_FOUND)); - return product; + return new ProductResponce(product); + //변경은 어디서? } - - - } diff --git a/src/main/java/gift/main/service/UserService.java b/src/main/java/gift/main/service/UserService.java index 0a9b3d395..376394497 100644 --- a/src/main/java/gift/main/service/UserService.java +++ b/src/main/java/gift/main/service/UserService.java @@ -1,11 +1,10 @@ package gift.main.service; +import gift.main.Exception.CustomException; +import gift.main.Exception.ErrorCode; import gift.main.dto.UserJoinRequest; import gift.main.dto.UserLoginRequest; import gift.main.entity.User; -import gift.main.Exception.ErrorCode; -import gift.main.Exception.CustomException; - import gift.main.repository.UserRepository; import gift.main.util.JwtUtil; import org.springframework.stereotype.Service; @@ -28,9 +27,10 @@ public UserService(JwtUtil jwtUtil, UserRepository userRepository) { public String joinUser(UserJoinRequest userJoinRequest) { //유효성 검사해야하는데용~! if (userRepository.existsByEmail(userJoinRequest.email())) { - throw new CustomException(ErrorCode.ALREADY_EMAIL.getErrorMessage(), ErrorCode.ALREADY_EMAIL.getHttpStatus()); + throw new CustomException(ErrorCode.ALREADY_EMAIL); } - User userdto = new User(userJoinRequest) ; + User userdto = new User(userJoinRequest); + User user = userRepository.save(userdto); return jwtUtil.createToken(user); @@ -38,10 +38,8 @@ public String joinUser(UserJoinRequest userJoinRequest) { public String loginUser(UserLoginRequest userLoginRequest) { - User user = userRepository.findByEmailAndPassword(userLoginRequest.email(),userLoginRequest.password()); - if (user == null) { - throw new CustomException(ErrorCode.ERROR_LOGIN.getErrorMessage(), ErrorCode.ERROR_LOGIN.getHttpStatus()); - } + User user = userRepository.findByEmailAndPassword(userLoginRequest.email(), userLoginRequest.password()) + .orElseThrow(() -> new CustomException(ErrorCode.ERROR_LOGIN)); return jwtUtil.createToken(user); } diff --git a/src/main/java/gift/main/service/WishProductService.java b/src/main/java/gift/main/service/WishProductService.java index 76bcfe662..9687b4b0a 100644 --- a/src/main/java/gift/main/service/WishProductService.java +++ b/src/main/java/gift/main/service/WishProductService.java @@ -1,7 +1,13 @@ package gift.main.service; +import gift.main.Exception.CustomException; +import gift.main.Exception.ErrorCode; import gift.main.dto.UserVo; +import gift.main.entity.Product; +import gift.main.entity.User; import gift.main.entity.WishProduct; +import gift.main.repository.ProductRepository; +import gift.main.repository.UserRepository; import gift.main.repository.WishProductRepository; import org.springframework.stereotype.Service; @@ -11,20 +17,32 @@ public class WishProductService { private final WishProductRepository wishProductRepository; + private final ProductRepository productRepository; + private final UserRepository userRepository; - public WishProductService(WishProductRepository wishProductRepository) { + public WishProductService(WishProductRepository wishProductRepository, ProductRepository productRepository, UserRepository userRepository) { this.wishProductRepository = wishProductRepository; - } - - public void addWishlistProduct(Long productId, UserVo sessionUser) { - wishProductRepository.deleteByProductIdAndUserId(productId, sessionUser.getId()); + this.productRepository = productRepository; + this.userRepository = userRepository; } public List getWishProducts(Long userId) { - List wishProducts = wishProductRepository.findAllByUserId(userId); + List wishProducts = wishProductRepository.findAllByUserId(userId) + .orElseGet(() -> List.of()); + return wishProducts; + } + public void addWishlistProduct(Long productId, UserVo sessionUser) { + Product product = productRepository.findById(productId) + .orElseThrow(() -> new CustomException(ErrorCode.PRODUCT_NOT_FOUND)); + User user = userRepository.findByEmail(sessionUser.getEmail()) + .orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)); + wishProductRepository.save(new WishProduct(product, user)); + } + + public void deleteProducts(Long productId, UserVo sessionUserVo) { wishProductRepository.deleteByProductIdAndUserId(productId, sessionUserVo.getId()); } diff --git a/src/main/java/gift/main/util/JwtUtil.java b/src/main/java/gift/main/util/JwtUtil.java index 7304d7b1d..4036786f3 100644 --- a/src/main/java/gift/main/util/JwtUtil.java +++ b/src/main/java/gift/main/util/JwtUtil.java @@ -21,7 +21,7 @@ public JwtUtil(@Value("${spring.jwt.secret}") String secret) { } public String createToken(Long id, String name, String email, String password, String role) { - String token = Jwts.builder() + String token = Jwts.builder() .claim("id", id) .claim("name", name) .claim("email", email) @@ -35,7 +35,7 @@ public String createToken(Long id, String name, String email, String password, S } public String createToken(User user) { - String token = Jwts.builder() + String token = Jwts.builder() .claim("id", user.getId()) .claim("name", user.getName()) .claim("email", user.getEmail()) @@ -51,7 +51,7 @@ public String createToken(User user) { public String createToken(Long id, UserDto userDto) { - String token = Jwts.builder() + String token = Jwts.builder() .claim("id", id) .claim("name", userDto.getName()) .claim("email", userDto.getEmail()) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 032e98cad..9caecf845 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -22,11 +22,13 @@ spring.datasource.username=sa spring.datasource.password= spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect -spring.jpa.properties.hibernate.format_sql=true +#spring.jpa.properties.hibernate.format_sql=true spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.open-in-view=false -spring.mvc.hiddenmethod.filter.enable=true + +#spring.mvc.hiddenmethod.filter.enable=true + diff --git a/src/main/resources/templates/product.html b/src/main/resources/templates/product.html index b63629455..28f5d9760 100644 --- a/src/main/resources/templates/product.html +++ b/src/main/resources/templates/product.html @@ -64,6 +64,7 @@

물건 리스트 확인

Name Price Image + Seller @@ -155,6 +156,7 @@ '' + product.name + '' + '' + product.price + '' + '' + product.imageUrl + '' + + '' + product.seller+ '' + ''; } else { html += '상품을 찾을 수 없습니다.'; @@ -188,6 +190,7 @@ '' + product.name + '' + '' + product.price + '' + '' + product.imageUrl + '' + + '' + product.seller + '' + '' + '
' + '' + diff --git a/src/main/resources/templates/user.html b/src/main/resources/templates/user.html index 8e6892df0..ff9d346fc 100644 --- a/src/main/resources/templates/user.html +++ b/src/main/resources/templates/user.html @@ -53,7 +53,7 @@

로그인

name: $('#joinName').val(), email: $('#joinEmail').val(), password: $('#joinPassword').val(), - role: $('#role').is(':checked') ? 'admin' : 'user' + role: $('#role').is(':checked') ? 'ADMIN' : 'USER' }; $.ajax({ type: 'POST', diff --git a/src/test/java/gift/main/repository/ProductRepositoryTest.java b/src/test/java/gift/main/repository/ProductRepositoryTest.java index 46decb664..578fd6b4b 100644 --- a/src/test/java/gift/main/repository/ProductRepositoryTest.java +++ b/src/test/java/gift/main/repository/ProductRepositoryTest.java @@ -1,8 +1,7 @@ package gift.main.repository; -import gift.main.Exception.CustomException; + import gift.main.entity.Product; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; @@ -21,7 +20,6 @@ class ProductRepositoryTest { private ProductRepository productRepository; @Test - @Transactional public void 조회() { //givem String name = "물건"; @@ -36,7 +34,6 @@ class ProductRepositoryTest { } @Test - @Transactional public void 모두조회() { //given productRepository.save(new Product("테스트1", 123, "123")); @@ -53,7 +50,6 @@ class ProductRepositoryTest { @Test - @Transactional public void 수정() { //given Product product = new Product("테스트용", 123, "123"); @@ -61,7 +57,7 @@ class ProductRepositoryTest { //when String newName = "newName"; - product1.setName(newName); + product1.updateValue(newName,123,"123"); productRepository.save(product1); //then @@ -70,7 +66,6 @@ class ProductRepositoryTest { } @Test - @Transactional public void 삭제() { //given Product product = new Product("테스트용", 123, "123"); diff --git a/src/test/java/gift/main/repository/UserRepositoryTest.java b/src/test/java/gift/main/repository/UserRepositoryTest.java index e0590c692..0f547caa7 100644 --- a/src/test/java/gift/main/repository/UserRepositoryTest.java +++ b/src/test/java/gift/main/repository/UserRepositoryTest.java @@ -21,7 +21,6 @@ class UserRepositoryTest { @Test - @Transactional public void 모두조회() { //given userRepository.save(new User("name", "123@123", "123", "USER")); @@ -37,7 +36,6 @@ class UserRepositoryTest { @Test - @Transactional public void 이메일중복허용안함() { //given userRepository.save(new User("name", "123@123", "123", "USER")); diff --git a/src/test/java/gift/main/repository/WishProductRepositoryTest.java b/src/test/java/gift/main/repository/WishProductRepositoryTest.java index 1b41f8722..956eca6a8 100644 --- a/src/test/java/gift/main/repository/WishProductRepositoryTest.java +++ b/src/test/java/gift/main/repository/WishProductRepositoryTest.java @@ -21,7 +21,6 @@ class WishProductRepositoryTest { @Test - @Transactional public void 유저아이디값으로여러개조회하기() { //given(준비) Long userId = 1L; @@ -40,7 +39,6 @@ class WishProductRepositoryTest { @Test - @Transactional public void 값삭제하기() { //given(준비) Long userId = 1L;