Вроде все работает

This commit is contained in:
Nikita Sergeev 2023-05-10 18:48:08 +04:00
parent 75071fdc1d
commit dc08796833
30 changed files with 611 additions and 29 deletions

View File

@ -34,6 +34,11 @@ dependencies {
implementation 'org.webjars:bootstrap:5.1.3' implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0' implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0' implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation group: 'org.springframework.security', name: 'spring-security-web'
implementation group: 'org.springframework.security', name: 'spring-security-config'
} }
tasks.named('test') { tasks.named('test') {

View File

@ -0,0 +1,14 @@
package ip.labwork.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,76 @@
package ip.labwork.configuration;
import ip.labwork.user.controller.UserSignupMvcController;
import ip.labwork.user.model.UserRole;
import ip.labwork.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login";
private final UserService userService;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeRequests()
.requestMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.and()
.logout().permitAll();
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoderConfiguration bCryptPasswordEncoder)
throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(userService)
.passwordEncoder(bCryptPasswordEncoder.createPasswordEncoder())
.and()
.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers("/css/**")
.requestMatchers("/js/**")
.requestMatchers("/templates/**")
.requestMatchers("/webjars/**");
}
}

View File

@ -1,28 +1,28 @@
package ip.labwork; package ip.labwork.configuration;
import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.http.HttpStatus; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
public class WebConfiguration implements WebMvcConfigurer { public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api"; public static final String REST_API = "/api";
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedMethods("*");
}
@Override @Override
public void addViewControllers(ViewControllerRegistry registry) { public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
ViewControllerRegistration registration = registry.addViewController("/notFound"); ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html"); registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK); registration.setStatusCode(HttpStatus.OK);
registry.addViewController("rest-test");
registry.addViewController("login");
} }
@Bean @Bean
@ -31,4 +31,8 @@ public class WebConfiguration implements WebMvcConfigurer {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound")); container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
}; };
} }
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
} }

View File

@ -1,6 +1,6 @@
package ip.labwork.method.controller; package ip.labwork.method.controller;
import ip.labwork.WebConfiguration; import ip.labwork.configuration.WebConfiguration;
import ip.labwork.method.service.MethodService; import ip.labwork.method.service.MethodService;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;

View File

@ -1,6 +1,6 @@
package ip.labwork.shop.controller; package ip.labwork.shop.controller;
import ip.labwork.WebConfiguration; import ip.labwork.configuration.WebConfiguration;
import ip.labwork.shop.service.ComponentService; import ip.labwork.shop.service.ComponentService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;

View File

@ -1,7 +1,9 @@
package ip.labwork.shop.controller; package ip.labwork.shop.controller;
import ip.labwork.shop.service.ComponentService; import ip.labwork.shop.service.ComponentService;
import ip.labwork.user.model.UserRole;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
@ -16,11 +18,13 @@ public class ComponentMvcController {
this.componentService = componentService; this.componentService = componentService;
} }
@GetMapping @GetMapping
@Secured({UserRole.AsString.ADMIN})
public String getComponents(Model model) { public String getComponents(Model model) {
model.addAttribute("components", componentService.findAllComponent()); model.addAttribute("components", componentService.findAllComponent());
return "component"; return "component";
} }
@GetMapping(value = {"/edit", "/edit/{id}"}) @GetMapping(value = {"/edit", "/edit/{id}"})
@Secured({UserRole.AsString.ADMIN})
public String editComponent(@PathVariable(required = false) Long id, public String editComponent(@PathVariable(required = false) Long id,
Model model) { Model model) {
if (id == null || id <= 0) { if (id == null || id <= 0) {

View File

@ -1,6 +1,6 @@
package ip.labwork.shop.controller; package ip.labwork.shop.controller;
import ip.labwork.WebConfiguration; import ip.labwork.configuration.WebConfiguration;
import ip.labwork.shop.service.OrderService; import ip.labwork.shop.service.OrderService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;

View File

@ -14,6 +14,7 @@ public class OrderDTO {
private Date date = new Date(); private Date date = new Date();
@NotBlank(message = "Price can't be null or empty") @NotBlank(message = "Price can't be null or empty")
private int price; private int price;
private long user_id;
private OrderStatus status = OrderStatus.Неизвестен; private OrderStatus status = OrderStatus.Неизвестен;
private List<ProductDTO> productDTOList; private List<ProductDTO> productDTOList;
public OrderDTO(Order order) { public OrderDTO(Order order) {
@ -25,6 +26,7 @@ public class OrderDTO {
.map(y -> new ProductDTO(y.getProduct(), y.getCount())) .map(y -> new ProductDTO(y.getProduct(), y.getCount()))
.toList(); .toList();
this.status = Objects.equals(order.getStatus().toString(), "") ? OrderStatus.Неизвестен : order.getStatus(); this.status = Objects.equals(order.getStatus().toString(), "") ? OrderStatus.Неизвестен : order.getStatus();
this.user_id = order.getUser_id() == null ? -1 : order.getUser_id();
} }
public OrderDTO() { public OrderDTO() {
@ -69,4 +71,12 @@ public class OrderDTO {
public void setProductDTOList(List<ProductDTO> productDTOList) { public void setProductDTOList(List<ProductDTO> productDTOList) {
this.productDTOList = productDTOList; this.productDTOList = productDTOList;
} }
public long getUser_id() {
return user_id;
}
public void setUser_id(long user_id) {
this.user_id = user_id;
}
} }

View File

@ -3,6 +3,7 @@ package ip.labwork.shop.controller;
import ip.labwork.shop.model.OrderStatus; import ip.labwork.shop.model.OrderStatus;
import ip.labwork.shop.service.OrderService; import ip.labwork.shop.service.OrderService;
import ip.labwork.shop.service.ProductService; import ip.labwork.shop.service.ProductService;
import ip.labwork.user.service.UserService;
import jakarta.servlet.http.Cookie; import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
@ -11,6 +12,7 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -19,9 +21,11 @@ import java.util.List;
public class OrderMvcController { public class OrderMvcController {
private final OrderService orderService; private final OrderService orderService;
private final ProductService productService; private final ProductService productService;
public OrderMvcController(OrderService orderService, ProductService productService) { private final UserService userService;
public OrderMvcController(OrderService orderService, ProductService productService, UserService userService) {
this.orderService = orderService; this.orderService = orderService;
this.productService = productService; this.productService = productService;
this.userService = userService;
} }
@GetMapping @GetMapping
public String getOrders(HttpServletRequest request, public String getOrders(HttpServletRequest request,
@ -45,7 +49,7 @@ public class OrderMvcController {
} }
@PostMapping @PostMapping
public String createOrder(HttpServletRequest request, public String createOrder(HttpServletRequest request,
HttpServletResponse response) { HttpServletResponse response, Principal principal) {
Cookie[] cookies = request.getCookies(); Cookie[] cookies = request.getCookies();
OrderDTO orderDTO = new OrderDTO(); OrderDTO orderDTO = new OrderDTO();
List<ProductDTO> productDTOS = new ArrayList<>(); List<ProductDTO> productDTOS = new ArrayList<>();
@ -60,13 +64,14 @@ public class OrderMvcController {
orderDTO.setPrice(totalPrice); orderDTO.setPrice(totalPrice);
orderDTO.setProductDTOList(productDTOS); orderDTO.setProductDTOList(productDTOS);
orderDTO.setStatus(OrderStatus.Готов); orderDTO.setStatus(OrderStatus.Готов);
orderDTO.setUser_id(userService.findByLogin(principal.getName()).getId());
orderService.create(orderDTO); orderService.create(orderDTO);
response.addCookie(new Cookie("delete","")); response.addCookie(new Cookie("delete",""));
return "redirect:/order"; return "redirect:/order";
} }
@GetMapping(value = {"/all"}) @GetMapping(value = {"/all"})
public String getOrders(Model model) { public String getOrders(Model model, Principal principal) {
model.addAttribute("orders", orderService.findAllOrder()); model.addAttribute("orders", orderService.findFiltredOrder(userService.findByLogin(principal.getName()).getId()));
return "orders"; return "orders";
} }

View File

@ -1,6 +1,6 @@
package ip.labwork.shop.controller; package ip.labwork.shop.controller;
import ip.labwork.WebConfiguration; import ip.labwork.configuration.WebConfiguration;
import ip.labwork.shop.service.ProductService; import ip.labwork.shop.service.ProductService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;

View File

@ -2,7 +2,9 @@ package ip.labwork.shop.controller;
import ip.labwork.shop.service.ComponentService; import ip.labwork.shop.service.ComponentService;
import ip.labwork.shop.service.ProductService; import ip.labwork.shop.service.ProductService;
import ip.labwork.user.model.UserRole;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
@ -27,6 +29,7 @@ public class ProductMvcController {
return "product"; return "product";
} }
@GetMapping(value = {"/edit", "/edit/{id}"}) @GetMapping(value = {"/edit", "/edit/{id}"})
@Secured({UserRole.AsString.ADMIN})
public String editProduct(@PathVariable(required = false) Long id, public String editProduct(@PathVariable(required = false) Long id,
Model model) { Model model) {
if (id == null || id <= 0) { if (id == null || id <= 0) {

View File

@ -20,6 +20,7 @@ public class Order {
@NotNull(message = "Price can't be null or empty") @NotNull(message = "Price can't be null or empty")
@Column(name = "price") @Column(name = "price")
private Integer price; private Integer price;
private Long user_id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<OrderProducts> products; private List<OrderProducts> products;
private OrderStatus status; private OrderStatus status;
@ -27,10 +28,11 @@ public class Order {
} }
public Order(Date date, Integer price, OrderStatus status) { public Order(Date date, Integer price, OrderStatus status, Long user_id) {
this.date = date; this.date = date;
this.price = price; this.price = price;
this.status = status; this.status = status;
this.user_id = user_id;
} }
public Long getId() { public Long getId() {
@ -84,11 +86,19 @@ public class Order {
this.status = status; this.status = status;
} }
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof Order order)) return false; if (!(o instanceof Order order)) return false;
return Objects.equals(getId(), order.getId()) && Objects.equals(getDate(), order.getDate()) && Objects.equals(getPrice(), order.getPrice()); return Objects.equals(getId(), order.getId()) && Objects.equals(getDate(), order.getDate()) && Objects.equals(getPrice(), order.getPrice()) && Objects.equals(getUser_id(), order.getUser_id()) && Objects.equals(getProducts(), order.getProducts()) && getStatus() == order.getStatus();
} }
@Override @Override

View File

@ -11,4 +11,7 @@ import java.util.List;
public interface OrderRepository extends JpaRepository<Order, Long> { public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("Select os from OrderProducts os where os.order.id = :orderId") @Query("Select os from OrderProducts os where os.order.id = :orderId")
List<OrderProducts> getOrderProduct(@Param("orderId") Long orderId); List<OrderProducts> getOrderProduct(@Param("orderId") Long orderId);
@Query("Select o from Order o where o.user_id = :userId")
List<Order> getOrdersByUser_id(@Param("userId") Long userId);
} }

View File

@ -28,7 +28,7 @@ public class OrderService {
for(int i = 0; i < orderDTO.getProductDTOList().size(); i++){ for(int i = 0; i < orderDTO.getProductDTOList().size(); i++){
price += orderDTO.getProductDTOList().get(i).getPrice() * orderDTO.getProductDTOList().get(i).getCount(); price += orderDTO.getProductDTOList().get(i).getPrice() * orderDTO.getProductDTOList().get(i).getCount();
} }
final Order order = new Order(new Date(), price, orderDTO.getStatus()); final Order order = new Order(new Date(), price, orderDTO.getStatus(), orderDTO.getUser_id());
validatorUtil.validate(order); validatorUtil.validate(order);
orderRepository.save(order); orderRepository.save(order);
for (int i = 0; i < orderDTO.getProductDTOList().size(); i++) { for (int i = 0; i < orderDTO.getProductDTOList().size(); i++) {
@ -47,6 +47,11 @@ public class OrderService {
public List<OrderDTO> findAllOrder() { public List<OrderDTO> findAllOrder() {
return orderRepository.findAll().stream().map(x -> new OrderDTO(x)).toList(); return orderRepository.findAll().stream().map(x -> new OrderDTO(x)).toList();
} }
@Transactional(readOnly = true)
public List<OrderDTO> findFiltredOrder(long userid) {
return orderRepository.getOrdersByUser_id(userid).stream().map(x -> new OrderDTO(x)).toList();
}
@Transactional @Transactional
public OrderDTO update(Long id, OrderDTO orderDTO) { public OrderDTO update(Long id, OrderDTO orderDTO) {
final Order currentOrder = findOrder(id); final Order currentOrder = findOrder(id);

View File

@ -1,6 +1,6 @@
package ip.labwork.test.controller; package ip.labwork.test.controller;
import ip.labwork.WebConfiguration; import ip.labwork.configuration.WebConfiguration;
import ip.labwork.test.model.TestDto; import ip.labwork.test.model.TestDto;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;

View File

@ -0,0 +1,42 @@
package ip.labwork.user.controller;
import ip.labwork.user.model.UserDto;
import ip.labwork.user.model.UserRole;
import ip.labwork.user.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.stream.IntStream;
@Controller
@RequestMapping("/users")
public class UserMvcController {
private final UserService userService;
public UserMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
@Secured({UserRole.AsString.ADMIN})
public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size,
Model model) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "users";
}
}

View File

@ -0,0 +1,50 @@
package ip.labwork.user.controller;
import ip.labwork.user.model.User;
import ip.labwork.user.model.UserSignupDto;
import ip.labwork.user.service.UserService;
import ip.labwork.util.validation.ValidationException;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(UserSignupMvcController.SIGNUP_URL)
public class UserSignupMvcController {
public static final String SIGNUP_URL = "/signup";
private final UserService userService;
public UserSignupMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
public String showSignupForm(Model model) {
model.addAttribute("userDto", new UserSignupDto());
return "signup";
}
@PostMapping
public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "signup";
}
try {
final User user = userService.createUser(
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return "redirect:/login?created=" + user.getLogin();
} catch (ValidationException e) {
model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

View File

@ -0,0 +1,74 @@
package ip.labwork.user.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(login, user.login);
}
@Override
public int hashCode() {
return Objects.hash(id, login);
}
}

View File

@ -0,0 +1,25 @@
package ip.labwork.user.model;
public class UserDto {
private final long id;
private final String login;
private final UserRole role;
public UserDto(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.role = user.getRole();
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public UserRole getRole() {
return role;
}
}

View File

@ -0,0 +1,20 @@
package ip.labwork.user.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -0,0 +1,40 @@
package ip.labwork.user.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,8 @@
package ip.labwork.user.repository;
import ip.labwork.user.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,67 @@
package ip.labwork.user.service;
import ip.labwork.user.model.User;
import ip.labwork.user.model.UserRole;
import ip.labwork.user.repository.UserRepository;
import ip.labwork.util.validation.ValidationException;
import ip.labwork.util.validation.ValidatorUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login));
}
final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
}

View File

@ -3,7 +3,11 @@ package ip.labwork.util.validation;
import java.util.Set; import java.util.Set;
public class ValidationException extends RuntimeException { public class ValidationException extends RuntimeException {
public ValidationException(Set<String> errors) { public <T> ValidationException(Set<String> errors) {
super(String.join("\n", errors)); super(String.join("\n", errors));
} }
public <T> ValidationException(String error) {
super(error);
}
} }

View File

@ -3,6 +3,7 @@
lang="ru" lang="ru"
xmlns:th="http://www.thymeleaf.org" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6"
> >
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
@ -38,14 +39,18 @@
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
<div class="collapse navbar-collapse" id="navbarNav"> <div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav me-auto mb-2 mb-lg-0"> <ul class="navbar-nav me-auto mb-2 mb-lg-0" th:with="activeLink=${#ctx.springRequestContext.requestUri}" sec:authorize="isAuthenticated()">
<a class="nav-link fs-4 text-black" href="/component" <a class="nav-link fs-4 text-black" sec:authorize="hasRole('ROLE_ADMIN')" href="/component" th:classappend="${#strings.equals(activeLink, '/component')} ? 'active' : ''">Компоненты</a>
>Компоненты</a <a class="nav-link fs-4 text-black" href="/product" th:classappend="${#strings.equals(activeLink, '/product')} ? 'active' : ''">Продукты</a>
> <a class="nav-link fs-4 text-black" href="/order" th:classappend="${#strings.equals(activeLink, '/order')} ? 'active' : ''">Заказы</a>
<a class="nav-link fs-4 text-black" href="/product">Продукты</a> <a class="nav-link fs-4 text-black" href="/order/all" th:classappend="${#strings.equals(activeLink, '/order/all')} ? 'active' : ''">История заказов</a>
<a class="nav-link fs-4 text-black" href="/order">Заказы</a> <a sec:authorize="hasRole('ROLE_ADMIN')" class="nav-link fs-4 text-black" href="/users"
<a class="nav-link fs-4 text-black" href="/order/all">История заказов</a> th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
<a class="nav-link fs-4 text-black" href="/logout">
Выход (<span th:text="${#authentication.name}"></span>)
</a>
</ul> </ul>
</div> </div>
</div> </div>
</nav> </nav>

View File

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<main
class="flex-shrink-0"
style="background-color: white"
layout:fragment="content">
<div class="container container-padding mt-5">
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
Пользователь не найден или пароль указан не верно
</div>
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
Выход успешно произведен
</div>
<div th:if="${param.created}" class="alert alert-success margin-bottom">
Пользователь '<span th:text="${param.created}"></span>' успешно создан
</div>
<form th:action="@{/login}" method="post" class="container-padding">
<div class="mb-3">
<input type="text" name="username" id="username" class="form-control"
placeholder="Логин" required="true" autofocus="true"/>
</div>
<div class="mb-3">
<input type="password" name="password" id="password" class="form-control"
placeholder="Пароль" required="true"/>
</div>
<button type="submit" class="btn btn-success button-fixed">Войти</button>
<a class="btn btn-primary button-fixed" href="/signup">Регистрация</a>
</form>
</div>
</main>
</body>
</html>

View File

@ -3,6 +3,7 @@
lang="en" lang="en"
layout:decorate="~{default}" layout:decorate="~{default}"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6"
> >
<head> </head> <head> </head>
<body> <body>
@ -12,6 +13,7 @@
type="button" type="button"
class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3"
th:href="@{/product/edit}" th:href="@{/product/edit}"
sec:authorize="hasRole('ROLE_ADMIN')"
> >
Добавить Добавить
</a> </a>
@ -39,13 +41,14 @@
<a <a
class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${product.id}').click()|" th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${product.id}').click()|"
sec:authorize="hasRole('ROLE_ADMIN')"
> >
Удалить Удалить
</a> </a>
<a <a
class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:href="@{/product/edit/{id}(id=${product.id})}" th:href="@{/product/edit/{id}(id=${product.id})}"
type="button" type="button" sec:authorize="hasRole('ROLE_ADMIN')"
>Изменить >Изменить
</a> </a>
<a <a
@ -62,7 +65,7 @@
<button <button
th:id="'remove-' + ${product.id}" th:id="'remove-' + ${product.id}"
type="submit" type="submit"
style="display: none" style="display: none" sec:authorize="hasRole('ROLE_ADMIN')"
> >
Удалить Удалить
</button> </button>

View File

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<main
class="flex-shrink-0"
style="background-color: white"
layout:fragment="content">
<div class="container container-padding mt-5">
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
<form action="#" th:action="@{/signup}" th:object="${userDto}" method="post">
<div class="mb-3">
<input type="text" class="form-control" th:field="${userDto.login}"
placeholder="Логин" required="true" autofocus="true" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${userDto.password}"
placeholder="Пароль" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${userDto.passwordConfirm}"
placeholder="Пароль (подтверждение)" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
</form>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<main style="background-color: white" layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
</tr>
</thead>
<tbody>
<tr th:each="user, iterator: ${users}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${user.id}"></td>
<td th:text="${user.login}" style="width: 60%"></td>
<td th:text="${user.role}" style="width: 20%"></td>
</tr>
</tbody>
</table>
</div>
<div th:if="${totalPages > 0}" class="pagination">
<span style="float: left; padding: 5px 5px;">Страницы:</span>
<a th:each="page : ${pages}"
th:href="@{/users(page=${page}, size=${users.size})}"
th:text="${page}"
th:class="${page == users.number + 1} ? active">
</a>
</div>
</main>
</body>
</html>