сдана 6

This commit is contained in:
Inohara 2023-05-15 16:04:43 +04:00
parent 5bfc441e59
commit 0a86d54ff6
7 changed files with 84 additions and 36 deletions

View File

@ -16,7 +16,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true) @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login"; private static final String LOGIN_URL = "/login";

View File

@ -4,6 +4,8 @@ import com.example.demo.supply.Product.ProductDto;
import com.example.demo.supply.Product.ProductService; import com.example.demo.supply.Product.ProductService;
import com.example.demo.supply.Supplier.SupplierDto; import com.example.demo.supply.Supplier.SupplierDto;
import com.example.demo.supply.Supplier.SupplierService; import com.example.demo.supply.Supplier.SupplierService;
import com.example.demo.supply.User.UserRole;
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;
@ -55,6 +57,7 @@ public class OrderMvcController {
} }
@GetMapping("/add") @GetMapping("/add")
@Secured({UserRole.AsString.ADMIN})
public String addOrder(Model model) { public String addOrder(Model model) {
model.addAttribute("orderDto", new OrderDtoForCreate()); model.addAttribute("orderDto", new OrderDtoForCreate());
model.addAttribute("selectedSupplier", null); model.addAttribute("selectedSupplier", null);
@ -64,6 +67,7 @@ public class OrderMvcController {
} }
@PostMapping("/create") @PostMapping("/create")
@Secured({UserRole.AsString.ADMIN})
public String saveOrder(Model model, public String saveOrder(Model model,
@ModelAttribute("orderDto") @Valid OrderDtoForCreate order, @ModelAttribute("orderDto") @Valid OrderDtoForCreate order,
BindingResult bindingResult) { BindingResult bindingResult) {

View File

@ -1,11 +1,16 @@
package com.example.demo.supply.Product; package com.example.demo.supply.Product;
import com.example.demo.supply.User.UserRole;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
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;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.validation.Valid; import javax.validation.Valid;
import java.security.Principal;
@Controller @Controller
@RequestMapping("/product") @RequestMapping("/product")
@ -25,36 +30,49 @@ public class ProductMvcController {
@GetMapping(value = {"/edit", "/edit/{id}"}) @GetMapping(value = {"/edit", "/edit/{id}"})
public String editProduct(@PathVariable(required = false) Long id, public String editProduct(@PathVariable(required = false) Long id,
Model model) { Model model, Principal principal) {
if (id == null || id <= 0) { String roleName = ((Authentication)principal).getAuthorities().toArray()[0].toString();
model.addAttribute("productDto", new ProductDto()); if(UserRole.ADMIN.toString().equals(roleName)) {
} else { if (id == null || id <= 0) {
model.addAttribute("productId", id); model.addAttribute("productDto", new ProductDto());
model.addAttribute("productDto", new ProductDto(productService.findProduct(id))); } else {
model.addAttribute("productId", id);
model.addAttribute("productDto", new ProductDto(productService.findProduct(id)));
}
return "product-edit";
} }
return "product-edit"; else return "redirect:/product";
} }
@PostMapping(value = {"", "/{id}"}) @PostMapping(value = {"", "/{id}"})
public String saveProduct(@PathVariable(required = false) Long id, public String saveProduct(@PathVariable(required = false) Long id,
@ModelAttribute @Valid ProductDto productDto, @ModelAttribute @Valid ProductDto productDto,
BindingResult bindingResult, BindingResult bindingResult,
Model model) { Model model,
if (bindingResult.hasErrors()) { Principal principal) {
model.addAttribute("errors", bindingResult.getAllErrors()); String roleName = ((Authentication)principal).getAuthorities().toArray()[0].toString();
return "product-edit"; if(UserRole.ADMIN.toString().equals(roleName)) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "product-edit";
}
if (id == null || id <= 0) {
productService.addProduct(productDto.getName(), productDto.getCost());
} else {
productService.updateProduct(id, productDto.getName(), productDto.getCost());
}
return "redirect:/product";
} }
if (id == null || id <= 0) { else return "redirect:/product";
productService.addProduct(productDto.getName(), productDto.getCost());
} else {
productService.updateProduct(id, productDto.getName(), productDto.getCost());
}
return "redirect:/product";
} }
@PostMapping("/delete/{id}") @PostMapping("/delete/{id}")
public String deleteProduct(@PathVariable Long id) { public String deleteProduct(@PathVariable Long id, Principal principal) {
productService.deleteProduct(id); String roleName = ((Authentication)principal).getAuthorities().toArray()[0].toString();
return "redirect:/product"; if(UserRole.ADMIN.toString().equals(roleName)) {
productService.deleteProduct(id);
return "redirect:/product";
}
else return "redirect:/product";
} }
} }

View File

@ -2,6 +2,7 @@ package com.example.demo.supply.User;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -9,6 +10,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import java.security.Principal;
import java.util.List; import java.util.List;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@ -22,19 +24,26 @@ public class UserMvcController {
} }
@GetMapping @GetMapping
@Secured({UserRole.AsString.ADMIN})
public String getUsers(@RequestParam(defaultValue = "1") int page, public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size, @RequestParam(defaultValue = "5") int size,
Model model) { Model model, Principal principal) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new); String roleName = ((Authentication)principal).getAuthorities().toArray()[0].toString();
model.addAttribute("users", users); if(UserRole.ADMIN.toString().equals(roleName)) {
final int totalPages = users.getTotalPages(); final Page<UserDto> users = userService.findAllPages(page, size)
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages) .map(UserDto::new);
.boxed() model.addAttribute("users", users);
.toList(); final int totalPages = users.getTotalPages();
model.addAttribute("pages", pageNumbers); final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
model.addAttribute("totalPages", totalPages); .boxed()
return "users"; .toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "users";
}
else{
model.addAttribute("error", "Доступ запрещен");
return "error";
}
} }
} }

View File

@ -42,6 +42,7 @@
<a class="nav-link" href="/logout"> <a class="nav-link" href="/logout">
Выход (<span th:text="${#authentication.name}"></span>) Выход (<span th:text="${#authentication.name}"></span>)
</a> </a>
</ul> </ul>
</div> </div>
</div> </div>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="alert alert-danger">
<span th:text="${error}"></span>
</div>
<a href="/">На главную</a>
</div>
</body>
</html>

View File

@ -1,6 +1,8 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" <html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}"> layout:decorate="~{default}">
<head> <head>
</head> </head>
@ -31,11 +33,11 @@
<td th:text="${product.cost}" /> <td th:text="${product.cost}" />
<td style="width: 10%"> <td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example"> <div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm" <a class="btn btn-warning button-fixed button-sm"
th:href="@{/product/edit/{id}(id=${product.id})}"> th:href="@{/product/edit/{id}(id=${product.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить <i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a> </a>
<button type="button" class="btn btn-danger button-fixed button-sm" <button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${product.id}').click()|"> th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${product.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить <i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button> </button>