Skip to content

Commit 67233d5

Browse files
committed
ShoppingCart changed with customer authentication
1 parent e9d33c2 commit 67233d5

File tree

11 files changed

+244
-43
lines changed

11 files changed

+244
-43
lines changed

src/main/java/com/manir/springbootecommercerestapi/controller/AuthController.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public ResponseEntity<?> registerUser(@RequestBody SignUpDto signUpDto){
5454
if (userRepository.existsByEmail(signUpDto.getEmail())){
5555
return new ResponseEntity<>("Email already exists", HttpStatus.BAD_REQUEST);
5656
}
57-
SignUpDto registeredUser = userRegisterService.registerUser(signUpDto);
57+
userRegisterService.registerUser(signUpDto);
5858
return new ResponseEntity<>("User is successfully registered", HttpStatus.OK);
5959
}
6060

Lines changed: 60 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
package com.manir.springbootecommercerestapi.controller;
22

3-
import com.manir.springbootecommercerestapi.dto.CartItemDto;
3+
import com.manir.springbootecommercerestapi.exception.EcommerceApiException;
4+
import com.manir.springbootecommercerestapi.model.User;
5+
import com.manir.springbootecommercerestapi.repository.UserRepository;
46
import com.manir.springbootecommercerestapi.response.CartItemResponse;
57
import com.manir.springbootecommercerestapi.service.ShoppingCartService;
68
import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser;
9+
import org.springframework.beans.factory.annotation.Autowired;
710
import org.springframework.http.HttpStatus;
811
import org.springframework.http.ResponseEntity;
9-
import org.springframework.security.access.prepost.PreAuthorize;
12+
import org.springframework.security.authentication.AnonymousAuthenticationToken;
13+
import org.springframework.security.core.Authentication;
14+
import org.springframework.security.core.annotation.AuthenticationPrincipal;
15+
import org.springframework.security.core.context.SecurityContextHolder;
16+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
1017
import org.springframework.web.bind.annotation.*;
1118

1219
import javax.annotation.Resource;
13-
import java.util.List;
1420

1521
@RestController
1622
@RequestMapping("api/v1/cart")
@@ -19,43 +25,75 @@ public class ShoppingCartController {
1925
@Resource
2026
private ShoppingCartService shoppingCartService;
2127

28+
@Autowired
29+
private UserRepository userRepository;
30+
31+
2232
//find by customer api
2333
@isAuthenticatedAsAdminOrUser
24-
@GetMapping("/findByCustomer/{customerId}")
25-
public CartItemResponse findByCustomerId(@PathVariable Long customerId){
26-
CartItemResponse responseCartItems = shoppingCartService.findByCustomerId(customerId);
34+
@GetMapping("/findByCustomer")
35+
public CartItemResponse findByCustomerId(@AuthenticationPrincipal Authentication authentication){
36+
authentication = SecurityContextHolder.getContext().getAuthentication();
37+
if (!(authentication instanceof AnonymousAuthenticationToken)) {
38+
String currentUserEmail = authentication.getName();
39+
//System.out.println("Name:" + currentUserEmail);
40+
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(()-> new UsernameNotFoundException("Customer not found"));
41+
CartItemResponse responseCartItems = shoppingCartService.findByCustomer(customer);
42+
return responseCartItems;
43+
44+
}else{
45+
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
46+
}
2747

28-
return responseCartItems;
2948
}
3049

3150
//add item to the cart api
3251
@isAuthenticatedAsAdminOrUser
33-
@PostMapping("/addItem/{customerId}/{productId}/{quantity}")
34-
public ResponseEntity<CartItemResponse> addCartItem(@PathVariable Long customerId,
52+
@PostMapping("/addItem/{productId}/{quantity}")
53+
public ResponseEntity<CartItemResponse> addCartItem(@AuthenticationPrincipal Authentication authentication,
3554
@PathVariable Long productId,
3655
@PathVariable Integer quantity){
37-
CartItemResponse responseCartItem = shoppingCartService.addCartItem(customerId, productId, quantity);
38-
39-
return new ResponseEntity<>(responseCartItem, HttpStatus.CREATED);
56+
authentication = SecurityContextHolder.getContext().getAuthentication();
57+
if (!(authentication instanceof AnonymousAuthenticationToken)){
58+
String currentUserEmail = authentication.getName();
59+
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer not found"));
60+
CartItemResponse responseCartItem = shoppingCartService.addCartItem(customer, productId, quantity);
61+
return new ResponseEntity<>(responseCartItem, HttpStatus.CREATED);
62+
}else {
63+
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
64+
}
4065
}
4166

4267
//update item quantity api
4368
@isAuthenticatedAsAdminOrUser
44-
@PutMapping("/updateItemQuantity/{customerId}/{productId}/{quantity}")
45-
public ResponseEntity<CartItemResponse> updateItemQuantity(@PathVariable Long customerId,
69+
@PutMapping("/updateItemQuantity/{productId}/{quantity}")
70+
public ResponseEntity<CartItemResponse> updateItemQuantity(@AuthenticationPrincipal Authentication authentication,
4671
@PathVariable Long productId,
4772
@PathVariable Integer quantity){
48-
49-
CartItemResponse responseCartItem = shoppingCartService.updateItemQuantity(customerId, productId, quantity);
50-
51-
return new ResponseEntity<>(responseCartItem, HttpStatus.OK);
73+
authentication = SecurityContextHolder.getContext().getAuthentication();
74+
if (!(authentication instanceof AnonymousAuthenticationToken)){
75+
String currentUserEmail = authentication.getName();
76+
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found"));
77+
CartItemResponse responseCartItem = shoppingCartService.updateItemQuantity(customer, productId, quantity);
78+
return new ResponseEntity<>(responseCartItem, HttpStatus.OK);
79+
}else{
80+
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
81+
}
5282
}
5383

5484
//delete item product api
5585
@isAuthenticatedAsAdminOrUser
56-
@DeleteMapping("/deleteItemProduct/{customerId}/{productId}")
57-
public ResponseEntity<String> deleteItemProduct(@PathVariable Long customerId, @PathVariable Long productId){
58-
shoppingCartService.deleteItemProduct(customerId, productId);
59-
return ResponseEntity.ok("Product with id = " + productId +" is deleted successfully from your shopping cart");
86+
@DeleteMapping("/deleteItemProduct/{productId}")
87+
public ResponseEntity<String> deleteItemProduct(@AuthenticationPrincipal Authentication authentication,
88+
@PathVariable Long productId){
89+
authentication = SecurityContextHolder.getContext().getAuthentication();
90+
if (!(authentication instanceof AnonymousAuthenticationToken)){
91+
String currentUserEmail = authentication.getName();
92+
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found"));
93+
shoppingCartService.deleteItemProduct(customer, productId);
94+
return ResponseEntity.ok("Product with id = " + productId +" is deleted successfully from your shopping cart");
95+
}else{
96+
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
97+
}
6098
}
6199
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.manir.springbootecommercerestapi.dto;
2+
3+
import lombok.Data;
4+
5+
@Data
6+
public class OrderDto {
7+
private Long id;
8+
private String name;
9+
private String email;
10+
private String phone;
11+
private String address;
12+
private double totalPrice;
13+
private String note;
14+
private String status;
15+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.manir.springbootecommercerestapi.model;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Data;
5+
import lombok.NoArgsConstructor;
6+
7+
import javax.persistence.*;
8+
import java.util.Set;
9+
10+
@AllArgsConstructor
11+
@NoArgsConstructor
12+
@Data
13+
@Entity
14+
@Table(name = "orders")
15+
public class Order {
16+
@Id
17+
@GeneratedValue(strategy = GenerationType.IDENTITY)
18+
private Long id;
19+
private String name;
20+
private String email;
21+
private String phone;
22+
private String address;
23+
private double totalPrice;
24+
private String note;
25+
private String status;
26+
27+
//relation with user
28+
@ManyToOne()
29+
@JoinColumn(name = "customer_id")
30+
private User customer;
31+
32+
//relation with order_products
33+
@OneToMany(cascade = CascadeType.ALL,
34+
fetch = FetchType.LAZY, orphanRemoval = true,
35+
mappedBy = "order")
36+
private Set<OrderProducts> orderProducts;
37+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.manir.springbootecommercerestapi.model;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Data;
5+
import lombok.NoArgsConstructor;
6+
7+
import javax.persistence.*;
8+
9+
@AllArgsConstructor
10+
@NoArgsConstructor
11+
@Data
12+
@Entity
13+
@Table(name = "order_products")
14+
public class OrderProducts {
15+
@Id
16+
@GeneratedValue(strategy = GenerationType.IDENTITY)
17+
private Long id;
18+
private double productPrice;
19+
private Integer productQuantity;
20+
private double totalPrice;
21+
private String note;
22+
private String status;
23+
24+
//relation with user
25+
@ManyToOne()
26+
@JoinColumn(name = "customer_id")
27+
private User customer;
28+
29+
//relation with product
30+
@ManyToOne()
31+
@JoinColumn(name = "product_id")
32+
private Product product;
33+
34+
//relation with order
35+
@ManyToOne()
36+
@JoinColumn(name = "order_id")
37+
private Order order;
38+
}

src/main/java/com/manir/springbootecommercerestapi/model/Product.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,10 @@ public class Product {
5454
//relation to cart item
5555
@OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true)
5656
private Set<CartItem> cartItems;
57+
58+
//relation with order_products
59+
@OneToMany(cascade = CascadeType.ALL,
60+
fetch = FetchType.LAZY, orphanRemoval = true,
61+
mappedBy = "product")
62+
private Set<OrderProducts> orderProducts;
5763
}

src/main/java/com/manir/springbootecommercerestapi/model/User.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,16 @@ public class User {
3131
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
3232
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
3333
private Set<Role> roles;
34+
35+
//relation with order
36+
@OneToMany(cascade = CascadeType.ALL,
37+
fetch = FetchType.LAZY, orphanRemoval = true,
38+
mappedBy = "customer")
39+
private Set<Order> orders;
40+
41+
//relation with order_product
42+
@OneToMany(cascade = CascadeType.ALL,
43+
fetch = FetchType.LAZY, orphanRemoval = true,
44+
mappedBy = "customer")
45+
private Set<OrderProducts> orderProducts;
3446
}
Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.manir.springbootecommercerestapi.repository;
22

33
import com.manir.springbootecommercerestapi.model.CartItem;
4+
import com.manir.springbootecommercerestapi.model.Product;
5+
import com.manir.springbootecommercerestapi.model.User;
46
import org.springframework.data.jpa.repository.JpaRepository;
57
import org.springframework.data.jpa.repository.Modifying;
68
import org.springframework.data.jpa.repository.Query;
@@ -9,16 +11,16 @@
911

1012
public interface CartItemRepository extends JpaRepository<CartItem, Long> {
1113

12-
List<CartItem> findByCustomerId(Long customerId);
14+
List<CartItem> findByCustomer(User customer);
1315

1416
//CartItem findByCustomerAndProduct(User customer, Product product);
15-
CartItem findByCustomerIdAndProductId(Long customerId, Long productId);
17+
CartItem findByCustomerAndProduct(User customer, Product product);
1618

1719
@Query("UPDATE CartItem c SET c.quantity = ?3 WHERE c.product.id = ?2 AND c.customer.id = ?1")
1820
void updateItemQuantity(Long customerId, Long productId, Integer quantity);
1921

2022
@Query("DELETE FROM CartItem c WHERE c.customer.id = ?1 AND c.product.id = ?2")
2123
@Modifying
22-
void deleteByCustomerIdAndProductId(Long customerId, Long productId);
24+
void deleteByCustomerAndProduct(Long customerId, Long productId);
2325

2426
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.manir.springbootecommercerestapi.security;
2+
3+
import com.manir.springbootecommercerestapi.model.User;
4+
import lombok.AllArgsConstructor;
5+
import lombok.Data;
6+
import lombok.NoArgsConstructor;
7+
import org.springframework.security.core.GrantedAuthority;
8+
import org.springframework.security.core.userdetails.UserDetails;
9+
10+
import java.util.Collection;
11+
12+
@Data
13+
@AllArgsConstructor
14+
@NoArgsConstructor
15+
public class CustomUserDetails implements UserDetails {
16+
private User user;
17+
@Override
18+
public Collection<? extends GrantedAuthority> getAuthorities() {
19+
return null;
20+
}
21+
22+
@Override
23+
public String getPassword() {
24+
return null;
25+
}
26+
27+
@Override
28+
public String getUsername() {
29+
return user.getEmail();
30+
}
31+
32+
@Override
33+
public boolean isAccountNonExpired() {
34+
return false;
35+
}
36+
37+
@Override
38+
public boolean isAccountNonLocked() {
39+
return false;
40+
}
41+
42+
@Override
43+
public boolean isCredentialsNonExpired() {
44+
return false;
45+
}
46+
47+
@Override
48+
public boolean isEnabled() {
49+
return false;
50+
}
51+
52+
53+
}

src/main/java/com/manir/springbootecommercerestapi/service/Impl/ShoppingCartServiceImpl.java

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@ public class ShoppingCartServiceImpl implements ShoppingCartService {
3838
@Resource
3939
private CommonService commonService;
4040
@Override
41-
public CartItemResponse findByCustomerId(Long customerId) {
41+
public CartItemResponse findByCustomer(User customer) {
4242

43-
List<CartItem> cartItems = cartItemRepository.findByCustomerId(customerId);
43+
List<CartItem> cartItems = cartItemRepository.findByCustomer(customer);
4444

4545
if (cartItems.size() == 0){
4646
throw new EcommerceApiException("User has no product in cart item", HttpStatus.BAD_REQUEST);
@@ -58,18 +58,17 @@ public CartItemResponse findByCustomerId(Long customerId) {
5858
}
5959

6060
@Override
61-
public CartItemResponse addCartItem(Long customerId, Long productId, Integer quantity) {
61+
public CartItemResponse addCartItem(User customer, Long productId, Integer quantity) {
6262
Integer addedQuantity = quantity;
63-
User user = findCustomerById(customerId);
6463
Product product = findProductById(productId);
6564

66-
CartItem cartItem = cartItemRepository.findByCustomerIdAndProductId(customerId, productId);
65+
CartItem cartItem = cartItemRepository.findByCustomerAndProduct(customer, product);
6766
if(cartItem != null){
6867
addedQuantity = cartItem.getQuantity() + quantity;
6968
cartItem.setQuantity(addedQuantity);
7069
}else {
7170
cartItem = new CartItem();
72-
cartItem.setCustomer(user);
71+
cartItem.setCustomer(customer);
7372
cartItem.setProduct(product);
7473
cartItem.setQuantity(quantity);
7574
}
@@ -82,9 +81,9 @@ public CartItemResponse addCartItem(Long customerId, Long productId, Integer qua
8281
}
8382

8483
@Override
85-
public CartItemResponse updateItemQuantity(Long customerId, Long productId, Integer quantity) {
86-
87-
CartItem cartItem = cartItemRepository.findByCustomerIdAndProductId(customerId, productId);
84+
public CartItemResponse updateItemQuantity(User customer, Long productId, Integer quantity) {
85+
Product product = findProductById(productId);
86+
CartItem cartItem = cartItemRepository.findByCustomerAndProduct(customer, product);
8887
if (cartItem == null){
8988
throw new EcommerceApiException("Product is not in the cart item", HttpStatus.BAD_REQUEST);
9089
}
@@ -98,13 +97,13 @@ public CartItemResponse updateItemQuantity(Long customerId, Long productId, Inte
9897

9998
@Override
10099
@Transactional
101-
public void deleteItemProduct(Long customerId, Long productId) {
102-
103-
CartItem cartItem = cartItemRepository.findByCustomerIdAndProductId(customerId, productId);
100+
public void deleteItemProduct(User customer, Long productId) {
101+
Product product = findProductById(productId);
102+
CartItem cartItem = cartItemRepository.findByCustomerAndProduct(customer, product);
104103
if (cartItem == null){
105104
throw new EcommerceApiException("Product is not in the cart item", HttpStatus.BAD_REQUEST);
106105
}
107-
cartItemRepository.deleteByCustomerIdAndProductId(customerId, productId);
106+
cartItemRepository.deleteByCustomerAndProduct(customer.getId(), productId);
108107
}
109108

110109
//map to dto

0 commit comments

Comments
 (0)