Lab 6 MVC

This commit is contained in:
shadowik 2023-05-15 03:13:22 +04:00
parent c98e598675
commit 7684dd0e02
27 changed files with 537 additions and 340 deletions

View File

@ -31,8 +31,13 @@ dependencies {
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.thymeleaf:thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
implementation 'org.projectlombok:lombok:1.18.22'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

View File

@ -0,0 +1,15 @@
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = {"", "/"})
public class MvcController {
@GetMapping("")
public String getUserPage(Model model) {
return "redirect:/master";
}
}

View File

@ -0,0 +1,14 @@
package com.example.demo.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 com.example.demo.configuration;
import com.example.demo.master.MasterRole;
import com.example.demo.master.MasterService;
import com.example.demo.master.MasterSignupMvcController;
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.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
securedEnabled = true
)
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login";
private final MasterService masterService;
public SecurityConfiguration(MasterService masterService) {
this.masterService = masterService;
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (masterService.findMaster(admin) == null) {
log.info("Admin user successfully created");
masterService.addMaster(admin, admin, admin, admin, MasterRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeHttpRequests()
.requestMatchers(MasterSignupMvcController.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 authenticationManagerBean(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http
.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(masterService);
return authenticationManagerBuilder.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers("/css/**")
.requestMatchers("/js/**")
.requestMatchers("/templates/**")
.requestMatchers("/webjars/**");
}
}

View File

@ -1,4 +1,4 @@
package com.example.demo;
package com.example.demo.configuration;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
@ -20,15 +20,7 @@ public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK);
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
};
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("login");
}
}

View File

@ -1,9 +1,7 @@
package com.example.demo.master;
import com.example.demo.order.Order;
import jakarta.persistence.*;
import java.util.List;
import java.util.Objects;
@Entity
@ -19,14 +17,17 @@ public class Master {
private String email;
private String password;
private MasterRole role;
public Master() {
}
public Master(String firstName, String lastName, String email, String password) {
public Master(String firstName, String lastName, String email, String password, MasterRole role) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.role = role;
}
public Long getId() {
@ -45,6 +46,10 @@ public class Master {
public String getPassword() { return password; }
public MasterRole getRole() {
return role;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@ -61,6 +66,10 @@ public class Master {
this.password = password;
}
public void setRole(MasterRole role) {
this.role = role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -1,8 +1,7 @@
package com.example.demo.master;
import com.example.demo.WebConfiguration;
import com.example.demo.configuration.WebConfiguration;
import com.example.demo.order.OrderService;
import com.example.demo.product.ProductDto;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
@ -17,59 +16,59 @@ import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/master")
public class MasterController {
private final MasterService masterService;
private final OrderService orderService;
public MasterController(MasterService masterService, OrderService orderService) {
this.masterService = masterService;
this.orderService = orderService;
}
@GetMapping("/")
public MasterDto getCurrentMaster() {
return new MasterDto(masterService.findMaster(masterService.getCurrentMasterId()));
}
@GetMapping("/{email}/{password}")
public MasterDto getCurrentMaster(@PathVariable("email") String email,
@PathVariable("password") String password) {
var master = new MasterDto(masterService.findMaster(email, password));
masterService.setCurrentMasterId(master.getId());
return master;
}
@PostMapping("/")
public MasterDto createMaster(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName,
@RequestParam("email") String email,
@RequestParam("password") String password) {
MasterDto master = new MasterDto(masterService.addMaster(firstName, lastName, email, password));
masterService.setCurrentMasterId(master.getId());
orderService.addOrder(master.getId());
return master;
}
@PatchMapping("/")
public MasterDto updateMaster(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName,
@RequestParam("email") String email,
@RequestParam("password") String password) {
return new MasterDto(masterService.updateMaster(masterService.getCurrentMasterId(),
firstName, lastName, email, password));
}
@DeleteMapping("/")
public MasterDto deleteMaster(@PathVariable Long id) {
return new MasterDto(masterService.deleteMaster(masterService.getCurrentMasterId()));
}
@PostMapping("/log_out")
public void logOut() {
masterService.setCurrentMasterId(0L);
}
@GetMapping("/all")
public List<MasterDto> GetMasters(){
return masterService.findAllMasters().stream().map(MasterDto::new).toList();
}
// private final MasterService masterService;
// private final OrderService orderService;
//
//
// public MasterController(MasterService masterService, OrderService orderService) {
// this.masterService = masterService;
// this.orderService = orderService;
// }
//
// @GetMapping("/")
// public MasterDto getCurrentMaster() {
// return new MasterDto(masterService.findMaster(masterService.getCurrentMasterId()));
//
// }
// @GetMapping("/{email}/{password}")
// public MasterDto getCurrentMaster(@PathVariable("email") String email,
// @PathVariable("password") String password) {
// var master = new MasterDto(masterService.findMaster(email, password));
// masterService.setCurrentMasterId(master.getId());
// return master;
// }
// @PostMapping("/")
// public MasterDto createMaster(@RequestParam("firstName") String firstName,
// @RequestParam("lastName") String lastName,
// @RequestParam("email") String email,
// @RequestParam("password") String password) {
// MasterDto master = new MasterDto(masterService.addMaster(firstName, lastName, email, password));
// masterService.setCurrentMasterId(master.getId());
// orderService.addOrder(master.getId());
// return master;
// }
//
// @PatchMapping("/")
// public MasterDto updateMaster(@RequestParam("firstName") String firstName,
// @RequestParam("lastName") String lastName,
// @RequestParam("email") String email,
// @RequestParam("password") String password) {
// return new MasterDto(masterService.updateMaster(masterService.getCurrentMasterId(),
// firstName, lastName, email, password));
// }
//
// @DeleteMapping("/")
// public MasterDto deleteMaster(@PathVariable Long id) {
// return new MasterDto(masterService.deleteMaster(masterService.getCurrentMasterId()));
// }
//
// @PostMapping("/log_out")
// public void logOut() {
// masterService.setCurrentMasterId(0L);
// }
//
// @GetMapping("/all")
// public List<MasterDto> GetMasters(){
// return masterService.findAllMasters().stream().map(MasterDto::new).toList();
// }
}

View File

@ -3,10 +3,13 @@ package com.example.demo.master;
import com.example.demo.order.OrderService;
import com.example.demo.product.ProductDto;
import com.example.demo.product.ProductService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
@Controller
@RequestMapping("/master")
public class MasterMvcController {
@ -18,67 +21,16 @@ public class MasterMvcController {
this.orderService = orderService;
}
@GetMapping("/login")
public String loginPage(Model model) {
if (masterService.getCurrentMasterId() != 0) {
return "redirect:/product";
}
model.addAttribute("user", new Master());
return "Login";
}
@PostMapping("/login")
public String login(@ModelAttribute Master user) {
var master = new MasterDto(masterService.findMaster(user.getEmail(), user.getPassword()));
masterService.setCurrentMasterId(master.getId());
return "redirect:/product/my_products";
}
@GetMapping("")
public String getUserPage(Model model) {
if (masterService.getCurrentMasterId() != 0) {
model.addAttribute("user", masterService.findMaster(masterService.getCurrentMasterId()));
} else {
return "redirect:/master/register";
}
public String getUserPage(Principal principal,Model model) {
Long masterId = masterService.findMaster(principal.getName()).getId();
model.addAttribute("user", masterService.findMaster(masterId));
return "UserPage";
}
@PostMapping(value = "", params = "action=update")
public String updateUserPage(@ModelAttribute Master user) {
if (masterService.getCurrentMasterId() == 0) {
return "redirect:/master";
}
masterService.updateMaster(
masterService.getCurrentMasterId(),
user.getFirstName(),
user.getLastName(),
user.getEmail(),
user.getPassword());
return "redirect:/product";
}
@PostMapping(value = "", params = "action=log_out")
public String logOut() {
masterService.setCurrentMasterId(0L);
return "redirect:/product";
}
@GetMapping("/register")
public String registerPage(Model model) {
model.addAttribute("user", new Master());
return "UserPage";
}
@PostMapping(value = "/register", params = "action=register")
public String register(@ModelAttribute Master user) {
MasterDto master = new MasterDto(masterService.addMaster(
user.getFirstName(),
user.getLastName(),
user.getEmail(),
user.getPassword()));
masterService.setCurrentMasterId(master.getId());
orderService.addOrder(master.getId());
return "redirect:/product/my_products";
}
}

View File

@ -7,4 +7,6 @@ import java.util.Optional;
public interface MasterRepository extends JpaRepository<Master, Long> {
Optional<Master> findByEmail(String email);
Master findOneByEmailIgnoreCase(String login);
}

View File

@ -0,0 +1,20 @@
package com.example.demo.master;
import org.springframework.security.core.GrantedAuthority;
public enum MasterRole 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

@ -1,32 +1,44 @@
package com.example.demo.master;
import com.example.demo.order.Order;
import com.example.demo.order.OrderController;
import com.example.demo.order.OrderService;
import com.example.demo.util.validation.ValidatorUtil;
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 org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class MasterService {
public class MasterService implements UserDetailsService {
private final MasterRepository masterRepository;
private final ValidatorUtil validatorUtil;
private final PasswordEncoder passwordEncoder;
private Long currentMasterId = 0L;
public MasterService(MasterRepository masterRepository, ValidatorUtil validatorUtil) {
public MasterService(MasterRepository masterRepository, ValidatorUtil validatorUtil, PasswordEncoder passwordEncoder) {
this.masterRepository = masterRepository;
this.validatorUtil = validatorUtil;
this.passwordEncoder = passwordEncoder;
}
@Transactional
public Master addMaster(String firstName, String lastName, String email, String password, MasterRole role) {
final Master master = new Master(firstName, lastName, email, passwordEncoder.encode(password), role);
validatorUtil.validate(master);
return masterRepository.save(master);
}
@Transactional
public Master addMaster(String firstName, String lastName, String email, String password) {
final Master master = new Master(firstName, lastName, email, password);
final Master master = new Master(firstName, lastName, email, passwordEncoder.encode(password), MasterRole.USER);
validatorUtil.validate(master);
return masterRepository.save(master);
}
@ -48,6 +60,11 @@ public class MasterService {
return realMaster;
}
@Transactional(readOnly = true)
public Master findMaster(String email) {
return masterRepository.findOneByEmailIgnoreCase(email);
}
@Transactional(readOnly = true)
public List<Master> findAllMasters() {
return masterRepository.findAll();
@ -76,14 +93,15 @@ public class MasterService {
masterRepository.deleteAll();
}
@Transactional
public Long getCurrentMasterId (){
return currentMasterId;
}
@Transactional
public void setCurrentMasterId(Long masterId) {
currentMasterId = masterId;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final Master userEntity = findMaster(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getEmail(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
}

View File

@ -0,0 +1,37 @@
package com.example.demo.master;
import jakarta.validation.constraints.NotBlank;
public class MasterSignupDto {
private String firstName;
private String lastName;
private String email;
private String password;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {return email; }
public String getPassword() { return password; }
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,49 @@
package com.example.demo.master;
import com.example.demo.order.OrderService;
import com.example.demo.util.validation.ValidationException;
import jakarta.validation.Valid;
import org.aspectj.weaver.ast.Or;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping(MasterSignupMvcController.SIGNUP_URL)
public class MasterSignupMvcController {
public static final String SIGNUP_URL = "/signup";
private final MasterService masterService;
private final OrderService orderService;
public MasterSignupMvcController(MasterService masterService, OrderService orderService) {
this.masterService = masterService;
this.orderService = orderService;
}
@GetMapping
public String showSignupForm(Model model) {
model.addAttribute("userDto", new MasterSignupDto());
return "singup";
}
@PostMapping
public String signup(@ModelAttribute("userDto") @Valid MasterSignupDto userSignupDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "signup";
}
try {
Master master = masterService.addMaster(userSignupDto.getFirstName(), userSignupDto.getLastName(),
userSignupDto.getEmail(), userSignupDto.getPassword(), MasterRole.USER);
orderService.addOrder(master.getId());
return "redirect:/login";
} catch (ValidationException e) {
model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

View File

@ -1,54 +1,54 @@
package com.example.demo.order;
import com.example.demo.WebConfiguration;
import com.example.demo.master.MasterService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/order")
public class OrderController {
private final OrderService orderService;
private final MasterService masterService;
public OrderController(OrderService orderService, MasterService masterService) {
this.orderService = orderService;
this.masterService = masterService;
}
@GetMapping("/{id}")
public OrderDto getOrder(@PathVariable Long id) {
return new OrderDto(orderService.findOrder(id));
}
@DeleteMapping("/")
public void buyProducts() {
orderService.buyProducts(masterService.getCurrentMasterId());
}
@GetMapping("/")
public List<OrderDto> getOrder() {
return orderService.findAllOrders().stream().map(OrderDto::new).toList();
}
@PostMapping("/")
public OrderDto createOrder(@RequestParam("master") Long masterId) {
return new OrderDto(orderService.addOrder(masterId));
}
@PostMapping("/{product}")
public void addProduct(@PathVariable("product") Long productId) {
orderService.addProduct(masterService.getCurrentMasterId(), productId);
}
@DeleteMapping("/{product}")
public void deleteProduct(@PathVariable("product") Long productId) {
orderService.deleteProduct(masterService.getCurrentMasterId(), productId);
}
@GetMapping("/findOrders/{masterId}")
public List<OrderDto> findOrders(@PathVariable("masterId") Long masterId) {
return orderService.findMastersOrders(masterId).stream().map(OrderDto::new).toList();
}
}
//package com.example.demo.order;
//
//import com.example.demo.configuration.WebConfiguration;
//import com.example.demo.master.MasterService;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.List;
//
//@RestController
//@RequestMapping(WebConfiguration.REST_API + "/order")
//public class OrderController {
// private final OrderService orderService;
// private final MasterService masterService;
//
// public OrderController(OrderService orderService, MasterService masterService) {
// this.orderService = orderService;
// this.masterService = masterService;
// }
//
// @GetMapping("/{id}")
// public OrderDto getOrder(@PathVariable Long id) {
// return new OrderDto(orderService.findOrder(id));
// }
//
// @DeleteMapping("/")
// public void buyProducts() {
// orderService.buyProducts(masterService.getCurrentMasterId());
// }
//
// @GetMapping("/")
// public List<OrderDto> getOrder() {
// return orderService.findAllOrders().stream().map(OrderDto::new).toList();
// }
//
// @PostMapping("/")
// public OrderDto createOrder(@RequestParam("master") Long masterId) {
// return new OrderDto(orderService.addOrder(masterId));
// }
//
// @PostMapping("/{product}")
// public void addProduct(@PathVariable("product") Long productId) {
// orderService.addProduct(masterService.getCurrentMasterId(), productId);
// }
//
// @DeleteMapping("/{product}")
// public void deleteProduct(@PathVariable("product") Long productId) {
// orderService.deleteProduct(masterService.getCurrentMasterId(), productId);
// }
//
// @GetMapping("/findOrders/{masterId}")
// public List<OrderDto> findOrders(@PathVariable("masterId") Long masterId) {
// return orderService.findMastersOrders(masterId).stream().map(OrderDto::new).toList();
// }
//}

View File

@ -1,6 +1,8 @@
package com.example.demo.order;
import com.example.demo.master.MasterRole;
import com.example.demo.master.MasterService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@ -8,6 +10,7 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
@ -24,34 +27,33 @@ public class OrderMvcController {
}
@GetMapping("")
public String getOrder(Model model) {
if (masterService.getCurrentMasterId() == 0) {
return "redirect:/master/login";
}
model.addAttribute("user", masterService.findMaster(masterService.getCurrentMasterId()));
model.addAttribute("order", orderService.findOrder(masterService.getCurrentMasterId()));
public String getOrder(Model model, Principal principal) {
Long masterId = masterService.findMaster(principal.getName()).getId();
model.addAttribute("order", orderService.findOrder(masterId));
AtomicInteger fullCost = new AtomicInteger();
orderService.findOrder(masterService.getCurrentMasterId()).getProducts().forEach(
orderService.findOrder(masterId).getProducts().forEach(
item -> fullCost.addAndGet(item.getCost()));
model.addAttribute("fullCost", fullCost);
return "OrderPage";
}
@PostMapping(value = "", params = "action=delete")
public String deleteProduct(@RequestParam(value = "id", required = true) Long id) {
orderService.deleteProduct(masterService.getCurrentMasterId(), id);
public String deleteProduct(@RequestParam(value = "id", required = true) Long id, Principal principal) {
Long masterId = masterService.findMaster(principal.getName()).getId();
orderService.deleteProduct(masterId, id);
return "redirect:/order";
}
@PostMapping(value = "", params = "action=buy")
public String buyProducts() {
orderService.buyProducts(masterService.getCurrentMasterId());
public String buyProducts(Principal principal) {
Long masterId = masterService.findMaster(principal.getName()).getId();
orderService.buyProducts(masterId);
return "redirect:/product";
}
@GetMapping("/masters_order")
@Secured(MasterRole.AsString.ADMIN)
public String MastersOrders(Model model, @RequestParam(value = "master_id", defaultValue = "-1") String masterId) {
model.addAttribute("user", masterService.findMaster(masterService.getCurrentMasterId()));
model.addAttribute("masters", masterService.findAllMasters());
if (!Objects.equals(masterId, "-1")) {

View File

@ -1,7 +1,6 @@
package com.example.demo.product;
import com.example.demo.WebConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.configuration.WebConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;

View File

@ -7,6 +7,8 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
@Controller
@RequestMapping("/product")
@ -24,67 +26,46 @@ public class ProductMvcController {
@GetMapping("")
public String getProducts(Model model) {
if (masterService.getCurrentMasterId() != 0) {
Master user = masterService.findMaster(masterService.getCurrentMasterId());
model.addAttribute("user", user);
}
else {
model.addAttribute("user", new Master());
}
model.addAttribute("products", productService.findAllProducts()
.stream().map(ProductDto::new).toList());
return "Products";
}
@PostMapping("")
public String addProductToOrder(@RequestParam(value = "id", required = true) Long id) {
if (masterService.getCurrentMasterId() == 0) {
return "redirect:/master/login";
}
orderService.addProduct(masterService.getCurrentMasterId(), id);
public String addProductToOrder(@RequestParam(value = "id", required = true) Long id, Principal principal) {
Long masterId = masterService.findMaster(principal.getName()).getId();
orderService.addProduct(masterId, id);
return "redirect:/product";
}
@GetMapping("/my_products")
public String getMasterProduct(Model model) {
if (masterService.getCurrentMasterId() == 0) {
return "redirect:/product";
}
model.addAttribute("user",
masterService.findMaster(masterService.getCurrentMasterId()));
public String getMasterProduct(Model model, Principal principal) {
Long masterId = masterService.findMaster(principal.getName()).getId();
model.addAttribute("products",
productService.findProducts(masterService.getCurrentMasterId()).stream().map(ProductDto::new).toList());
productService.findProducts(masterId).stream().map(ProductDto::new).toList());
return "UserProducts";
}
@GetMapping("/create_product")
public String createProductPage(Model model) {
if (masterService.getCurrentMasterId() == 0) {
return "redirect:/product";
}
model.addAttribute("user", masterService.findMaster(masterService.getCurrentMasterId()));
model.addAttribute("product", new Product());
model.addAttribute("buttonText", "Create");
return "ProductCreate";
}
@PostMapping("/create_product")
public String createProduct(@ModelAttribute Product product) {
public String createProduct(@ModelAttribute Product product, Principal principal) {
Long masterId = masterService.findMaster(principal.getName()).getId();
productService.addProduct(
product.getName(),
product.getCost(),
masterService.getCurrentMasterId()
masterId
);
return "redirect:/product/my_products";
}
@GetMapping("/update_product/{id}")
public String updateProductPage(Model model, @PathVariable("id") Long id) {
if (masterService.getCurrentMasterId() == 0) {
return "redirect:/product";
}
model.addAttribute("user", masterService.findMaster(masterService.getCurrentMasterId()));
model.addAttribute("product", productService.findProduct(id));
model.addAttribute("buttonText", "Update");
return "ProductCreate";

View File

@ -1,25 +0,0 @@
body {
background: #f54d9a;
}
.logo {
background: #FF9CCE;
}
main {
padding: 2%;
margin: 10% 5%;
}
main img {
width: 100%;
object-fit: cover;
}
form {
padding: 1%;
}
.product-div {
background: #e874ac;
}

View File

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">>
<head>
<meta charset="UTF-8">
<title>Login</title>
@ -15,15 +15,15 @@
crossorigin="anonymous"></script>
</head>
<body style="background: #f54d9a">
<header th:insert="~{Header :: header}"></header>
<div>
<!--<header th:insert="~{Header :: header}"></header>-->
<div layout:fragment="content">
<h1 class="text-center">Masters</h1>
<div class="container">
<div class="row gy-5 p-2">
<form th:action="@{/order/masters_order}" method="get">
<select th:each="master : ${masters}" th:name="master_id" class="form-select" aria-label="Default select example">
<option th:id="master_id" th:value="${master.id}" >
<select th:name="master_id" class="form-select" aria-label="Default select example">
<option th:each="master : ${masters}" th:id="master_id" th:value="${master.id}" >
<span th:text="${master.firstName + ' ' + master.lastName }"></span>
</option>
</select>

View File

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">>
<head>
<meta charset="UTF-8">
<title>Login</title>
@ -15,7 +15,8 @@
crossorigin="anonymous"></script>
</head>
<body style="background: #f54d9a">
<header th:insert="~{Header :: header}"></header>
<!--<header th:insert="~{Header :: header}"></header>-->
<div layout:fragment="content">
<div>
<h1 class="text-center">Order</h1>
<form method="post" th:object="${order}">
@ -44,5 +45,6 @@
</div>
</form>
</div>
</div>
</body>
</html>

View File

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">>
<head>
<meta charset="UTF-8">
<title>Login</title>
@ -15,7 +15,8 @@
crossorigin="anonymous"></script>
</head>
<body style="background: #f54d9a">
<header th:insert="~{Header :: header}"></header>
<!-- <header th:insert="~{Header :: header}"></header>-->
<div layout:fragment="content">
<div>
<form method="post" th:object="${product}">
<input type="text" th:field="*{name}" th:value="${product.getName()}" name="name" class="form-control" id="name">
@ -23,5 +24,6 @@
<button type="submit" class="btn btn-primary" th:text="${buttonText}">Add</button>
</form>
</div>
</div>
</body>
</html>

View File

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">>
<head>
<meta charset="UTF-8">
<title>Title</title>
@ -15,8 +15,8 @@
crossorigin="anonymous"></script>
</head>
<body style="background: #f54d9a">
<header th:insert="~{Header :: header}"></header>
<!-- <header th:insert="~{Header :: header}"></header>-->
<div layout:fragment="content">
<div class="container">
<div th:each="item : ${products}" class="row product-div p-2 m-2">
<form method="post" th:object="${item}" >
@ -33,6 +33,6 @@
</form>
</div>
</div>
</div>
</body>
</html>

View File

@ -1,55 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/style.css"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ"
crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js"
integrity="sha384-zYPOMqeu1DAVkHiLqWBUTcbYfZ8osu1Nd6Z89ify25QV9guujx43ITvfi12/QExE"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.min.js"
integrity="sha384-Y4oOpwW3duJdCWv5ly8SCFYWqFDsfob/3GkgExXKV4idmbt98QcxXYs9UoXAB7BZ"
crossorigin="anonymous"></script>
</head>
<body style="background: #f54d9a">
<header th:insert="~{Header :: header}"></header>
<form method="post" th:object="${user}">
<div class="container">
<div class="row gy-5 p-2">
<input type="text" name="name" class="form-control"
id="name" placeholder="Name" th:value="${user.firstName}" th:field="*{firstName}">
</div>
<div class="row gy-5 p-2">
<input type="text" name="surname" class="form-control"
id="surname" placeholder="Surname" th:value="${user.lastName}" th:field="*{lastName}">
</div>
<div class="row gy-5 p-2">
<input type="email" name="email" class="form-control"
id="email" placeholder="Email" th:value="${user.email}" th:field="*{email}">
</div>
<div class="row gy-5 p-2">
<input type="password" name="password" class="form-control"
id="password" placeholder="Password" th:value="${user.password}" th:field="*{password}">
</div>
<div th:if='${user.firstName != null}' class="row align-items-start">
<div class="col">
<button name="action" class="btn btn-primary w-100" value="update">Update</button>
</div>
<div class="col">
<button name="action" th:onclick="/master/log_out"
class="btn btn-primary w-100" value="log_out">Log Out</button>
</div>
</div>
<div th:unless='${user.firstName != null}' class="row gy-5">
<button name="action" value="register" class="btn btn-primary w-100">Register</button>
</div>
<div th:unless='${user.firstName != null}' class="row align-items-start">
<a href="/sing_in" class="btn btn-primary">Sing In</a>
</div>
</div>
</form>
</body>
</html>

View File

@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">>
<head>
<meta charset="UTF-8">
<title>Title</title>
@ -16,7 +16,7 @@
crossorigin="anonymous"></script>
</head>
<body style="background: #f54d9a">
<header th:insert="~{Header :: header}"></header>
<div layout:fragment="content">
<div class="container">
<div class="row align-content-center">
<a href="/product/create_product" class="btn btn-primary w-100 h-100 text-lg-center">Create</a>
@ -33,5 +33,6 @@
</div>
</div>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="ru" data-bs-theme="dark"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ"
crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js"
integrity="sha384-zYPOMqeu1DAVkHiLqWBUTcbYfZ8osu1Nd6Z89ify25QV9guujx43ITvfi12/QExE"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.min.js"
integrity="sha384-Y4oOpwW3duJdCWv5ly8SCFYWqFDsfob/3GkgExXKV4idmbt98QcxXYs9UoXAB7BZ"
crossorigin="anonymous"></script>
</head>
<body>
<div id="body-shell">
<header class="logo d-flex flex-wrap align-items-center justify-content-center
justify-content-md-between py-3 mb-4 border-bottom" th:fragment="header">
<a href="/" class="d-flex align-items-center col-md-3 mb-2 mb-md-0 text-dark text-decoration-none">
<svg class="bi me-2" width="40" height="32" role="img" aria-label="Bootstrap"><use xlink:href="#bootstrap"></use></svg>
</a>
<ul class="nav col-12 col-md-auto mb-2 justify-content-center mb-md-0">
<li sec:authorize="isAuthenticated()"><a href="/product/my_products" class="nav-link px-2 link-dark">My Products</a></li>
<li><a href="/product" class="nav-link px-2 link-dark">Products</a></li>
<li sec:authorize="hasRole('ROLE_ADMIN')"><a href="/order/masters_order" class="nav-link px-2 link-dark">Orders</a></li>
</ul>
<div sec:authorize="isAuthenticated()" class="col-md-3 text-end">
<a href="/order" class="btn btn-outline-primary me-2">Shop List</a>
<a href="/master" class="nav-link px-2 link-dark">Пользователь</a>
</div>
<div sec:authorize="!isAuthenticated()" class="col-md-3 text-end">
<a href="/login" class="btn btn-outline-primary me-2">Login</a>
<a href="/signup" class="btn btn-primary">Register</a>
</div>
</header>
<div id="content-div" layout:fragment="content"></div>
</div>
</body>
<th:block layout:fragment="scripts">
</th:block>
</html>

View File

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">>
<head>
</head>
<body style="background: #f54d9a">
<!-- <header th:insert="~{Header :: header}"></header>-->
<div layout:fragment="content">
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
User not found
</div>
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
Logout success
</div>
<div th:if="${param.created}" class="alert alert-success margin-bottom">
User '<span th:text="${param.created}"></span>' was successfully created
</div>
<form th:action="@{/login}" method="post">
<div class="mb-3">
<p class="mb-1">Login</p>
<input name="username" id="username" class="form-control"
type="text" required autofocus />
</div>
<div class="mb-3">
<p class="mb-1">Password</p>
<input name="password" id="password" class="form-control"
type="password" required />
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success">
Sing in
</button>
</div>
<div>
<p>
<span>Not a member yet?</span>
<a href="/signup">Sing Up here</a>
</p>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,8 +1,11 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
<meta charset="UTF-8">
<title>Login</title>
<title>Title</title>
<link rel="stylesheet" href="/style.css"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ"
@ -15,24 +18,33 @@
crossorigin="anonymous"></script>
</head>
<body style="background: #f54d9a">
<header th:insert="~{Header :: header}"></header>
<form method="post" th:object="${user}">
<div layout:fragment="content">
<form method="post" th:object="${userDto}" th:action="@{/signup}">
<div class="container">
<div class="row gy-5 p-2">
<input type="text" name="name" class="form-control"
id="name" placeholder="Name" th:field="${userDto.firstName}">
</div>
<div class="row gy-5 p-2">
<input type="text" name="surname" class="form-control"
id="surname" placeholder="Surname" th:field="${userDto.lastName}">
</div>
<div class="row gy-5 p-2">
<input type="email" name="email" class="form-control"
id="email" placeholder="Email" th:field="*{email}">
id="email" placeholder="Email" th:field="${userDto.email}">
</div>
<div class="row gy-5 p-2">
<input type="password" name="password" class="form-control"
id="password" placeholder="Password" th:field="*{password}">
id="password" placeholder="Password" th:field="${userDto.password}">
</div>
<div class="row gy-5">
<button type="submit" class="btn btn-primary">Sing In</button>
<button value="register" class="btn btn-primary w-100">Register</button>
</div>
<div class="row gy-5 ">
<a href="/master/register" class="btn btn-primary">Register</a>
<div class="row align-items-start">
<a href="/sing_in" class="btn btn-primary">Sing In</a>
</div>
</div>
</form>
</div>
</body>
</html>