Skip to content

Commit

Permalink
Merge pull request #24 from batuhaniskr/feature-user-products
Browse files Browse the repository at this point in the history
Added relationship between products and user
batuhaniskr authored May 24, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
2 parents 0b393a5 + 3c47eea commit d9a3665
Showing 13 changed files with 202 additions and 151 deletions.
3 changes: 3 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -42,11 +42,14 @@

<!-- Use MySQL Connector-J -->

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Original file line number Diff line number Diff line change
@@ -3,7 +3,6 @@
import java.util.List;

import com.batuhaniskr.product.model.User;
import com.batuhaniskr.product.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
Original file line number Diff line number Diff line change
@@ -4,7 +4,6 @@
import org.springframework.stereotype.Service;

import com.batuhaniskr.product.model.User;
import com.batuhaniskr.product.repository.UserRepository;

@Service
public class UserService {
Original file line number Diff line number Diff line change
@@ -8,6 +8,9 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@@ -40,12 +43,16 @@ public MainController(ProductService productService, CategoryService categorySer

@GetMapping("")
public String index(Model model, @RequestParam("page") Optional<Integer> page,
@RequestParam("size") Optional<Integer> size) {
@RequestParam("size") Optional<Integer> size,
@AuthenticationPrincipal UserDetails userDetails) {


page.ifPresent(p -> currentPage = p);
size.ifPresent(s -> pageSize = s);

Pageable pageable = new PageRequest(currentPage - 1, pageSize);
Page<ProductDTO> productPage = productService.getAllProduct(pageable);
String userEmail = userDetails.getUsername();
Page<ProductDTO> productPage = productService.getAllProduct(pageable, userEmail);

model.addAttribute("productPage", productPage);

@@ -71,9 +78,10 @@ public String addProduct(@Valid Model model) {
}

@PostMapping(value = "/save")
public String save(@Valid ProductDTO productDTO) {
public String save(ProductDTO productDTO, @AuthenticationPrincipal UserDetails userDetails) {
LOG.log(Level.INFO, "/ {0}",productDTO.getName());
productService.saveProduct(productDTO);
String userEmail = userDetails.getUsername();
productService.saveProduct(productDTO, userEmail);

return "redirect:/products";
}
12 changes: 12 additions & 0 deletions src/main/java/com/batuhaniskr/product/model/Product.java
Original file line number Diff line number Diff line change
@@ -32,6 +32,10 @@ public class Product {
@JoinColumn(name = "category_id", nullable = false)
private Category category;

@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;

public Integer getId() {
return id;
}
@@ -80,6 +84,14 @@ public void setCategory(Category category) {
this.category = category;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

@PrePersist
public void onPrePersist() {
this.createdAt = new Date();
11 changes: 11 additions & 0 deletions src/main/java/com/batuhaniskr/product/model/User.java
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@

import javax.persistence.*;
import java.util.Collection;
import java.util.List;

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "email"))
@@ -24,6 +25,8 @@ public class User {
name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Product> products;
public User() {
}

@@ -80,6 +83,14 @@ public void setRoles(Collection<Role> roles) {
this.roles = roles;
}

public List<Product> getProducts() {
return products;
}

public void setProducts(List<Product> products) {
this.products = products;
}

@Override
public String toString() {
return "User{" +
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.batuhaniskr.product.repository;

import com.batuhaniskr.product.model.Product;
import com.batuhaniskr.product.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Integer> {
Page<Product> findByUser(Pageable pageable, User user);
}
Original file line number Diff line number Diff line change
@@ -2,8 +2,9 @@

import com.batuhaniskr.product.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

User findByEmail(String email);
}
}
22 changes: 19 additions & 3 deletions src/main/java/com/batuhaniskr/product/service/ProductService.java
Original file line number Diff line number Diff line change
@@ -3,6 +3,8 @@
import com.batuhaniskr.product.dto.ProductDTO;
import com.batuhaniskr.product.model.Category;
import com.batuhaniskr.product.model.Product;
import com.batuhaniskr.product.model.Role;
import com.batuhaniskr.product.model.User;
import com.batuhaniskr.product.repository.CategoryRepository;
import com.batuhaniskr.product.repository.ProductRepository;
import org.modelmapper.ModelMapper;
@@ -17,28 +19,42 @@ public class ProductService {

private ProductRepository productRepository;
private CategoryRepository categoryRepository;
private UserService userService;
private ModelMapper modelMapper;


@Autowired
public ProductService(ProductRepository productRepository,
CategoryRepository categoryRepository,
UserService userService,
ModelMapper modelMapper) {
this.productRepository = productRepository;
this.categoryRepository = categoryRepository;
this.userService = userService;
this.modelMapper = modelMapper;
}

public Page<ProductDTO> getAllProduct(Pageable pageable) {
public Page<ProductDTO> getAllProduct(Pageable pageable, String username) {
User user = userService.findByEmail(username);
for (Role role: user.getRoles()) {
if (role.getName().equals("ROLE_ADMIN")) {
return productRepository.findAll(pageable)
.map(x -> modelMapper.map(x, ProductDTO.class));
}
}

return productRepository.findAll(pageable)
return productRepository.findByUser(pageable, user)
.map(x -> modelMapper.map(x, ProductDTO.class));
}

public void saveProduct(ProductDTO productDTO) {
public void saveProduct(ProductDTO productDTO, String email) {
User user = userService.findByEmail(email);
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
Product product = modelMapper.map(productDTO, Product.class);
Category category = categoryRepository.findByCategoryName(product.getCategory().getCategoryName());
product.setCategory(category);
product.setUser(user);

productRepository.save(product);
}

Original file line number Diff line number Diff line change
@@ -3,11 +3,8 @@
import com.batuhaniskr.product.dto.UserRegistrationDto;
import com.batuhaniskr.product.model.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Repository;

@Repository
public interface UserService extends UserDetailsService {

User findByEmail(String email);
User save(UserRegistrationDto userRegistrationDto);
}
User save(UserRegistrationDto registrationDto);
}
44 changes: 36 additions & 8 deletions src/test/java/com/batuhaniskr/product/ProductServiceTests.java
Original file line number Diff line number Diff line change
@@ -2,18 +2,19 @@

import com.batuhaniskr.product.dto.CategoryDTO;
import com.batuhaniskr.product.dto.ProductDTO;
import com.batuhaniskr.product.model.Category;
import com.batuhaniskr.product.model.Product;
import com.batuhaniskr.product.model.User;
import com.batuhaniskr.product.repository.CategoryRepository;
import com.batuhaniskr.product.repository.ProductRepository;
import com.batuhaniskr.product.service.ProductService;
import com.batuhaniskr.product.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Java6Assertions.assertThat;
@@ -23,18 +24,24 @@
@RunWith(SpringRunner.class)
public class ProductServiceTests {

@Mock
private ModelMapper mockModelMapper;

@Mock
private ProductRepository productRepository;

@Mock
private CategoryRepository categoryRepository;

@Mock
private UserService userService;

@Mock
private ModelMapper mockModelMapper;

@InjectMocks
private ProductService productService;

@Test
public void getProductById() {
ProductService productService = new ProductService(productRepository, categoryRepository, mockModelMapper);
ProductService productService = new ProductService(productRepository, categoryRepository, userService, mockModelMapper);
ProductDTO productDTO = new ProductDTO();
productDTO.setId(1);
productDTO.setName("Test");
@@ -55,4 +62,25 @@ public void getProductById() {

assertThat(productByOneId).isEqualTo(productDTO);
}

@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "user1")
public void testGetProductById_UserNotOwner() {
// Arrange
User user1 = new User();
user1.setUsername("user1");

User user2 = new User();
user2.setUsername("user2");

Product product = new Product();
product.setId(1);
product.setUser(user2);

when(productRepository.findOne(1)).thenReturn(product);
when(userService.findByEmail("user1")).thenReturn(user1);

// Act
productService.getProductById(1);
}
}
Loading

0 comments on commit d9a3665

Please sign in to comment.