Skip to content

Commit fe37854

Browse files
committed
Some code refactors are done on getting authenticated user.
1 parent 7d2f8b3 commit fe37854

File tree

6 files changed

+83
-88
lines changed

6 files changed

+83
-88
lines changed

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

+18-33
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,17 @@
22

33
import com.manir.springbootecommercerestapi.dto.OrderDto;
44
import com.manir.springbootecommercerestapi.dto.OrderProductsDto;
5-
import com.manir.springbootecommercerestapi.exception.EcommerceApiException;
65
import com.manir.springbootecommercerestapi.model.User;
76
import com.manir.springbootecommercerestapi.repository.UserRepository;
7+
import com.manir.springbootecommercerestapi.service.CommonService;
88
import com.manir.springbootecommercerestapi.service.OrderProductsService;
99
import com.manir.springbootecommercerestapi.service.OrderService;
1010
import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser;
1111
import org.springframework.beans.factory.annotation.Autowired;
1212
import org.springframework.http.HttpStatus;
1313
import org.springframework.http.ResponseEntity;
14-
import org.springframework.security.authentication.AnonymousAuthenticationToken;
1514
import org.springframework.security.core.Authentication;
1615
import org.springframework.security.core.annotation.AuthenticationPrincipal;
17-
import org.springframework.security.core.context.SecurityContextHolder;
18-
import org.springframework.security.core.userdetails.UsernameNotFoundException;
1916
import org.springframework.web.bind.annotation.GetMapping;
2017
import org.springframework.web.bind.annotation.PostMapping;
2118
import org.springframework.web.bind.annotation.RequestMapping;
@@ -27,55 +24,43 @@
2724
@RequestMapping(value = "api/v1/order")
2825
public class OrderController {
2926

30-
@Autowired
31-
private UserRepository userRepository;
3227
@Autowired
3328
private OrderService orderService;
3429
@Autowired
3530
private OrderProductsService orderProductsService;
31+
@Autowired
32+
private CommonService commonService;
3633

3734
//place order complete order api
3835
@isAuthenticatedAsAdminOrUser
3936
@PostMapping("/placeOrder")
4037
public ResponseEntity<?> placeOrder(@AuthenticationPrincipal Authentication authentication){
41-
authentication = SecurityContextHolder.getContext().getAuthentication();
42-
if (!(authentication instanceof AnonymousAuthenticationToken)){
43-
String currentUserEmail = authentication.getName();
44-
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found"));
45-
orderService.placeOrder(customer);
46-
return new ResponseEntity<>("Order placed successfully", HttpStatus.CREATED);
47-
}else{
48-
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
49-
}
38+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
39+
orderService.placeOrder(customer);
40+
return new ResponseEntity<>("Order placed successfully", HttpStatus.CREATED);
5041
}
5142

5243
//find order by customer api
5344
@isAuthenticatedAsAdminOrUser
5445
@GetMapping("/findByCustomer")
5546
public List<OrderDto> listOrdersByCustomer(@AuthenticationPrincipal Authentication authentication){
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-
List<OrderDto> customerOrders = orderService.listOrdersByCustomer(customer);
61-
return customerOrders;
62-
}else{
63-
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
64-
}
47+
48+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
49+
50+
List<OrderDto> customerOrders = orderService.listOrdersByCustomer(customer);
51+
return customerOrders;
6552
}
6653

54+
55+
6756
//find ordered items by Customer
6857
@isAuthenticatedAsAdminOrUser
6958
@GetMapping("/findOrderedItemsByCustomer")
7059
public List<OrderProductsDto> findOrderedItemsByCustomer(@AuthenticationPrincipal Authentication authentication){
71-
authentication = SecurityContextHolder.getContext().getAuthentication();
72-
if (!(authentication instanceof AnonymousAuthenticationToken)){
73-
String currentUserEmail = authentication.getName();
74-
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found"));
75-
List<OrderProductsDto> customerOrderedItems = orderProductsService.findOrderItemsByCustomer(customer);
76-
return customerOrderedItems;
77-
}else{
78-
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
79-
}
60+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
61+
List<OrderProductsDto> customerOrderedItems = orderProductsService.findOrderItemsByCustomer(customer);
62+
return customerOrderedItems;
8063
}
64+
65+
8166
}

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

+16-47
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
11
package com.manir.springbootecommercerestapi.controller;
22

3-
import com.manir.springbootecommercerestapi.exception.EcommerceApiException;
43
import com.manir.springbootecommercerestapi.model.User;
5-
import com.manir.springbootecommercerestapi.repository.UserRepository;
64
import com.manir.springbootecommercerestapi.response.CartItemResponse;
7-
import com.manir.springbootecommercerestapi.service.OrderService;
5+
import com.manir.springbootecommercerestapi.service.CommonService;
86
import com.manir.springbootecommercerestapi.service.ShoppingCartService;
97
import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser;
108
import org.springframework.beans.factory.annotation.Autowired;
119
import org.springframework.http.HttpStatus;
1210
import org.springframework.http.ResponseEntity;
13-
import org.springframework.security.authentication.AnonymousAuthenticationToken;
1411
import org.springframework.security.core.Authentication;
1512
import org.springframework.security.core.annotation.AuthenticationPrincipal;
16-
import org.springframework.security.core.context.SecurityContextHolder;
17-
import org.springframework.security.core.userdetails.UsernameNotFoundException;
1813
import org.springframework.web.bind.annotation.*;
1914

2015
import javax.annotation.Resource;
@@ -26,26 +21,16 @@ public class ShoppingCartController {
2621
@Resource
2722
private ShoppingCartService shoppingCartService;
2823
@Autowired
29-
private UserRepository userRepository;
30-
@Autowired
31-
private OrderService orderService;
24+
private CommonService commonService;
3225

3326
//find by customer api
3427
@isAuthenticatedAsAdminOrUser
3528
@GetMapping("/findByCustomer")
3629
public CartItemResponse findByCustomerId(@AuthenticationPrincipal Authentication authentication){
37-
authentication = SecurityContextHolder.getContext().getAuthentication();
38-
if (!(authentication instanceof AnonymousAuthenticationToken)) {
39-
String currentUserEmail = authentication.getName();
40-
//System.out.println("Name:" + currentUserEmail);
41-
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(()-> new UsernameNotFoundException("Customer not found"));
42-
CartItemResponse responseCartItems = shoppingCartService.findByCustomer(customer);
43-
return responseCartItems;
44-
45-
}else{
46-
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
47-
}
4830

31+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
32+
CartItemResponse responseCartItems = shoppingCartService.findByCustomer(customer);
33+
return responseCartItems;
4934
}
5035

5136
//add item to the cart api
@@ -54,15 +39,10 @@ public CartItemResponse findByCustomerId(@AuthenticationPrincipal Authentication
5439
public ResponseEntity<CartItemResponse> addCartItem(@AuthenticationPrincipal Authentication authentication,
5540
@PathVariable Long productId,
5641
@PathVariable Integer quantity){
57-
authentication = SecurityContextHolder.getContext().getAuthentication();
58-
if (!(authentication instanceof AnonymousAuthenticationToken)){
59-
String currentUserEmail = authentication.getName();
60-
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer not found"));
61-
CartItemResponse responseCartItem = shoppingCartService.addCartItem(customer, productId, quantity);
62-
return new ResponseEntity<>(responseCartItem, HttpStatus.CREATED);
63-
}else {
64-
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
65-
}
42+
43+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
44+
CartItemResponse responseCartItem = shoppingCartService.addCartItem(customer, productId, quantity);
45+
return new ResponseEntity<>(responseCartItem, HttpStatus.CREATED);
6646
}
6747

6848
//update item quantity api
@@ -71,31 +51,20 @@ public ResponseEntity<CartItemResponse> addCartItem(@AuthenticationPrincipal Aut
7151
public ResponseEntity<CartItemResponse> updateItemQuantity(@AuthenticationPrincipal Authentication authentication,
7252
@PathVariable Long productId,
7353
@PathVariable Integer quantity){
74-
authentication = SecurityContextHolder.getContext().getAuthentication();
75-
if (!(authentication instanceof AnonymousAuthenticationToken)){
76-
String currentUserEmail = authentication.getName();
77-
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found"));
78-
CartItemResponse responseCartItem = shoppingCartService.updateItemQuantity(customer, productId, quantity);
79-
return new ResponseEntity<>(responseCartItem, HttpStatus.OK);
80-
}else{
81-
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
82-
}
54+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
55+
CartItemResponse responseCartItem = shoppingCartService.updateItemQuantity(customer, productId, quantity);
56+
return new ResponseEntity<>(responseCartItem, HttpStatus.OK);
8357
}
8458

8559
//delete item product api
8660
@isAuthenticatedAsAdminOrUser
8761
@DeleteMapping("/deleteItemProduct/{productId}")
8862
public ResponseEntity<String> deleteItemProduct(@AuthenticationPrincipal Authentication authentication,
8963
@PathVariable Long productId){
90-
authentication = SecurityContextHolder.getContext().getAuthentication();
91-
if (!(authentication instanceof AnonymousAuthenticationToken)){
92-
String currentUserEmail = authentication.getName();
93-
User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found"));
94-
shoppingCartService.deleteItemProduct(customer, productId);
95-
return ResponseEntity.ok("Product with id = " + productId +" is deleted successfully from your shopping cart");
96-
}else{
97-
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
98-
}
64+
65+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
66+
shoppingCartService.deleteItemProduct(customer, productId);
67+
return ResponseEntity.ok("Product with id = " + productId +" is deleted successfully from your shopping cart");
9968
}
10069

10170

src/main/java/com/manir/springbootecommercerestapi/service/CommonService.java

+5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package com.manir.springbootecommercerestapi.service;
22

33
import com.manir.springbootecommercerestapi.dto.CartItemDto;
4+
import com.manir.springbootecommercerestapi.model.User;
45
import com.manir.springbootecommercerestapi.response.CartItemResponse;
56
import com.manir.springbootecommercerestapi.response.CommonResponse;
67
import org.springframework.data.domain.Page;
8+
import org.springframework.security.core.Authentication;
79

810
import java.util.List;
911

@@ -14,4 +16,7 @@ public interface CommonService<T> {
1416

1517
//cart iem response handler
1618
CartItemResponse getResponse(CartItemDto cartItemDto);
19+
20+
//get current authenticated user
21+
User getCurrentAuthenticatedUser(Authentication authentication);
1722
}

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

+30
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,39 @@
11
package com.manir.springbootecommercerestapi.service.Impl;
22

33
import com.manir.springbootecommercerestapi.dto.CartItemDto;
4+
import com.manir.springbootecommercerestapi.exception.EcommerceApiException;
5+
import com.manir.springbootecommercerestapi.model.User;
6+
import com.manir.springbootecommercerestapi.repository.UserRepository;
47
import com.manir.springbootecommercerestapi.response.CartItemResponse;
58
import com.manir.springbootecommercerestapi.response.CommonResponse;
69
import com.manir.springbootecommercerestapi.service.CommonService;
10+
import lombok.AllArgsConstructor;
711
import lombok.extern.slf4j.Slf4j;
812
import org.slf4j.Logger;
913
import org.slf4j.LoggerFactory;
1014
import org.springframework.data.domain.Page;
15+
import org.springframework.http.HttpStatus;
16+
import org.springframework.security.authentication.AnonymousAuthenticationToken;
17+
import org.springframework.security.core.Authentication;
18+
import org.springframework.security.core.context.SecurityContextHolder;
19+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
1120
import org.springframework.stereotype.Service;
1221

22+
23+
import javax.annotation.Resource;
1324
import java.util.ArrayList;
1425
import java.util.List;
1526

1627
@Service
1728
@Slf4j
29+
@AllArgsConstructor
1830
public class CommonServiceImpl implements CommonService{
1931

2032
private static Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);
2133

34+
@Resource(name = "userRepository")
35+
private final UserRepository userRepository;
36+
2237
@Override
2338
public CommonResponse getResponseContent(Page page, List dtoList) {
2439

@@ -45,4 +60,19 @@ public CartItemResponse getResponse(CartItemDto cartItemDto) {
4560
cartItemResponse.setTotalCost(totalPrice);
4661
return cartItemResponse;
4762
}
63+
64+
@Override
65+
public User getCurrentAuthenticatedUser(Authentication authentication) {
66+
authentication = SecurityContextHolder.getContext().getAuthentication();
67+
if (authentication == null || authentication instanceof AnonymousAuthenticationToken){
68+
throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST);
69+
}
70+
String currentUserEmail = authentication.getName();
71+
User currentUser = userRepository.findByEmail(currentUserEmail)
72+
.orElseThrow(
73+
() -> new UsernameNotFoundException("User Not found")
74+
);
75+
76+
return currentUser;
77+
}
4878
}

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

+13-7
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,9 @@ public class OrderServiceImpl implements OrderService {
4141
@Transactional
4242
public void placeOrder(User customer) {
4343
CartItemResponse cartItemDto = shoppingCartService.findByCustomer(customer);
44-
OrderDto orderDto = new OrderDto();
45-
orderDto.setTotalPrice(cartItemDto.getTotalCost());
46-
orderDto.setEmail(customer.getEmail());
47-
orderDto.setName(customer.getName());
48-
orderDto.setCustomer(customer);
49-
OrderDto savedOrder = saveOrder(orderDto, customer);
44+
OrderDto orderDto = setFields(cartItemDto, customer);
45+
//save order to the db
46+
OrderDto savedOrder = saveOrder(orderDto);
5047
List<CartItemDto> cartItemDtoList = cartItemDto.getContent();
5148
for(CartItemDto cartItem : cartItemDtoList){
5249
OrderProducts orderProducts = new OrderProducts();
@@ -62,14 +59,23 @@ public void placeOrder(User customer) {
6259
}
6360

6461
@Override
65-
public OrderDto saveOrder(OrderDto orderDto, User customer) {
62+
public OrderDto saveOrder(OrderDto orderDto) {
6663
//convert to entity
6764
Order order = mapToEntity(orderDto);
6865
//save order to db
6966
Order placedOrder = orderRepository.save(order);
7067
return mapToDto(placedOrder);
7168
}
7269

70+
private OrderDto setFields(CartItemResponse cartItemDto, User customer){
71+
OrderDto orderDto = new OrderDto();
72+
orderDto.setTotalPrice(cartItemDto.getTotalCost());
73+
orderDto.setEmail(customer.getEmail());
74+
orderDto.setName(customer.getName());
75+
orderDto.setCustomer(customer);
76+
77+
return orderDto;
78+
}
7379
@Override
7480
public List<OrderDto> listOrdersByCustomer(User customer) {
7581
List<Order> orders = orderRepository.findByCustomer(customer);

src/main/java/com/manir/springbootecommercerestapi/service/OrderService.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@
88
public interface OrderService {
99

1010
void placeOrder(User customer);
11-
OrderDto saveOrder(OrderDto orderDto, User customer);
11+
OrderDto saveOrder(OrderDto orderDto);
1212
List<OrderDto> listOrdersByCustomer(User customer);
1313
}

0 commit comments

Comments
 (0)