Commit message.

This commit is contained in:
Кашин Максим 2023-05-15 01:25:15 +04:00
parent f6d23f860d
commit 0bcf6791d3
59 changed files with 668 additions and 1052 deletions

View File

@ -13,26 +13,16 @@ repositories {
} }
dependencies { dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'com.h2database:h2:2.1.210' implementation 'com.h2database:h2:2.1.210'
implementation 'org.hibernate.validator:hibernate-validator' implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.4' implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.4'
implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6' implementation 'com.auth0:java-jwt:4.4.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'}
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') { tasks.named('test') {
useJUnitPlatform() useJUnitPlatform()

Binary file not shown.

View File

@ -0,0 +1,28 @@
package com.example.maxim.Configuration;
import com.example.maxim.Configuration.jwt.JwtFilter;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAPI30Configuration {
public static final String API_PREFIX = "/api/1.0";
@Bean
public OpenAPI customizeOpenAPI() {
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
return new OpenAPI()
.addSecurityItem(new SecurityRequirement()
.addList(securitySchemeName))
.components(new Components()
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}

View File

@ -8,7 +8,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration @Configuration
public class PasswordEncoderConfiguration { public class PasswordEncoderConfiguration {
@Bean @Bean
public PasswordEncoder createPasswordEncoder(){ public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder(); return new BCryptPasswordEncoder();
} }
} }

View File

@ -1,6 +1,7 @@
package com.example.maxim.Configuration; package com.example.maxim.Configuration;
import com.example.maxim.lab3.controller.UserSignUpMVCController; import com.example.maxim.Configuration.jwt.JwtFilter;
import com.example.maxim.lab3.controller.UserController;
import com.example.maxim.lab3.model.UserRole; import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.lab3.service.UserService; import com.example.maxim.lab3.service.UserService;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -11,19 +12,23 @@ import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration @Configuration
@EnableWebSecurity
public class SecurityConfiguration { public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login";
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private final UserService userService; private final UserService userService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(UserService userService) { public SecurityConfiguration(UserService userService) {
this.userService = userService; this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup(); createAdminOnStartup();
} }
@ -34,32 +39,54 @@ public class SecurityConfiguration {
userService.createUser(admin, admin, admin, UserRole.ADMIN); userService.createUser(admin, admin, admin, UserRole.ADMIN);
} }
} }
@Bean @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and() log.info("Creating security configuration");
.cors().and() http.cors()
.and()
.csrf().disable() .csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests() .authorizeHttpRequests()
.requestMatchers(UserSignUpMVCController.SIGNUP_URL).permitAll() .requestMatchers("/", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL) .requestMatchers(HttpMethod.POST, UserController.URL_SIGNUP).permitAll()
.permitAll() .requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.anyRequest().authenticated() .requestMatchers(HttpMethod.GET, "/users/*").permitAll()
.requestMatchers(HttpMethod.GET, "/h2-console").permitAll()
.anyRequest()
.authenticated()
.and() .and()
.formLogin() .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.loginPage(LOGIN_URL).permitAll() .anonymous();
.and()
.logout().permitAll();
return http.build(); return http.build();
} }
@Bean @Bean
public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception { public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoderConfiguration bCryptPasswordEncoder)
AuthenticationManagerBuilder authenticationManagerBuilder = http throws Exception {
.getSharedObject(AuthenticationManagerBuilder.class); return http.getSharedObject(AuthenticationManagerBuilder.class)
authenticationManagerBuilder.userDetailsService(userService); .userDetailsService(userService)
return authenticationManagerBuilder.build(); .passwordEncoder(bCryptPasswordEncoder.createPasswordEncoder())
.and()
.build();
} }
@Bean @Bean
public WebSecurityCustomizer webSecurityCustomizer() { public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("public/styles/**", "/js/**","/templates/**","/webjars/**"); return (web) -> web.ignoring()
.requestMatchers(HttpMethod.OPTIONS, "/**")
.requestMatchers("/*.js")
.requestMatchers("/*.png")
.requestMatchers("/*.jpg")
.requestMatchers("/*.html")
.requestMatchers("/*.css")
.requestMatchers("/assets/**")
.requestMatchers("/favicon.ico")
.requestMatchers("/.js", "/.css")
.requestMatchers("/swagger-ui/index.html")
.requestMatchers("/webjars/**")
.requestMatchers("/swagger-resources/**")
.requestMatchers("/v3/api-docs/**");
} }
} }

View File

@ -1,16 +1,16 @@
package com.example.maxim.Configuration; package com.example.maxim.Configuration;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
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.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
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";
@Override @Override
public void addCorsMappings(CorsRegistry registry){ public void addCorsMappings(CorsRegistry registry){
@ -18,20 +18,33 @@ public class WebConfiguration implements WebMvcConfigurer {
} }
@Override @Override
public void addViewControllers(ViewControllerRegistry registry) { public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
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("login");
} }
//@Override //@Override
//public void addViewControllers(ViewControllerRegistry registry) { //public void addViewControllers(ViewControllerRegistry registry) {
// WebMvcConfigurer.super.addViewControllers(registry); // WebMvcConfigurer.super.addViewControllers(registry);
// registry.addViewController("rest-test"); // registry.addViewController("rest-test");
//} //}
// @Bean @Bean
// public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() { public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
// return container -> { return container -> {
// container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound")); container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
// }; };
// } }
@Override
public void addResourceHandlers(
ResourceHandlerRegistry registry) {
registry.addResourceHandler("/public/**")
.addResourceLocations("/WEB-INF/view/react/build/public/");
registry.addResourceHandler("/*.js")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.json")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.ico")
.addResourceLocations("/WEB-INF/view/react/build/");
}
} }

View File

@ -0,0 +1,11 @@
package com.example.maxim.Configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,71 @@
package com.example.maxim.Configuration.jwt;
import com.example.maxim.lab3.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import java.io.IOException;
public class JwtFilter extends GenericFilterBean {
private static final String AUTHORIZATION = "Authorization";
public static final String TOKEN_BEGIN_STR = "Bearer ";
private final UserService userService;
public JwtFilter(UserService userService) {
this.userService = userService;
}
private String getTokenFromRequest(HttpServletRequest request) {
String bearer = request.getHeader(AUTHORIZATION);
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
return bearer.substring(TOKEN_BEGIN_STR.length());
}
return null;
}
private void raiseException(ServletResponse response, int status, String message) throws IOException {
if (response instanceof final HttpServletResponse httpResponse) {
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpResponse.setStatus(status);
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
response.getOutputStream().write(body);
}
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof final HttpServletRequest httpRequest) {
final String token = getTokenFromRequest(httpRequest);
if (StringUtils.hasText(token)) {
try {
final UserDetails user = userService.loadUserByToken(token);
final UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (JwtException e) {
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
return;
} catch (Exception e) {
e.printStackTrace();
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
String.format("Internal error: %s", e.getMessage()));
return;
}
}
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,27 @@
package com.example.maxim.Configuration.jwt;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
public class JwtProperties {
private String devToken = "";
private Boolean isDev = true;
public String getDevToken() {
return devToken;
}
public void setDevToken(String devToken) {
this.devToken = devToken;
}
public Boolean isDev() {
return isDev;
}
public void setDev(Boolean dev) {
isDev = dev;
}
}

View File

@ -0,0 +1,107 @@
package com.example.maxim.Configuration.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;
@Component
public class JwtProvider {
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
private final static String ISSUER = "auth0";
private final Algorithm algorithm;
private final JWTVerifier verifier;
public JwtProvider(JwtProperties jwtProperties) {
if (!jwtProperties.isDev()) {
LOG.info("Generate new JWT key for prod");
try {
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
} catch (NoSuchAlgorithmException e) {
throw new JwtException(e);
}
} else {
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
}
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
public String generateToken(String login) {
final Date issueDate = Date.from(LocalDate.now()
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
final Date expireDate = Date.from(LocalDate.now()
.plusDays(15)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
return JWT.create()
.withIssuer(ISSUER)
.withIssuedAt(issueDate)
.withExpiresAt(expireDate)
.withSubject(login)
.sign(algorithm);
}
private DecodedJWT validateToken(String token) {
try {
return verifier.verify(token);
} catch (JWTVerificationException e) {
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
}
}
public boolean isTokenValid(String token) {
if (!StringUtils.hasText(token)) {
return false;
}
try {
validateToken(token);
return true;
} catch (JwtException e) {
LOG.error(e.getMessage());
return false;
}
}
public Optional<String> getLoginFromToken(String token) {
try {
return Optional.ofNullable(validateToken(token).getSubject());
} catch (JwtException e) {
LOG.error(e.getMessage());
return Optional.empty();
}
}
}

View File

@ -8,4 +8,6 @@ import org.springframework.data.repository.query.Param;
import java.util.List; import java.util.List;
public interface IBuyerRespository extends JpaRepository<Buyer, Long> { public interface IBuyerRespository extends JpaRepository<Buyer, Long> {
@Query("SELECT w.buyers FROM Car w WHERE :buyer MEMBER OF w.buyers")
List<Buyer> findBuyersOnWorkPlace(@Param("buyer") Buyer buyer);
} }

View File

@ -1,7 +1,7 @@
package com.example.maxim.lab3.Respository; package com.example.maxim.lab3.Respository;
import com.example.maxim.lab3.model.Buyer;
import com.example.maxim.lab3.model.Store; import com.example.maxim.lab3.model.Store;
import com.example.maxim.lab3.model.Buyer;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;

View File

@ -1,8 +0,0 @@
package com.example.maxim.lab3.Respository;
import com.example.maxim.lab3.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface IUserRespository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -1,27 +1,25 @@
package com.example.maxim.lab3.controller; package com.example.maxim.lab3.controller;
import com.example.maxim.Configuration.WebConfiguration;
import com.example.maxim.lab3.service.BuyerService; import com.example.maxim.lab3.service.BuyerService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("(WebConfiguration.REST_API + /buyer") @RequestMapping("/buyer")
public class BuyerController { public class BuyerController {
private final BuyerService buyerService; private final BuyerService buyerService;
public BuyerController(BuyerService buyerService){ public BuyerController(BuyerService buyerService){
this.buyerService = buyerService; this.buyerService = buyerService;
} }
@PostMapping @PostMapping
public BuyerDTO addBuyer(@RequestBody @Valid BuyerDTO buyerDTO) { public BuyerDTO addBuyer(@RequestBody BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.addBuyer(buyerDTO)); return new BuyerDTO(buyerService.addBuyer(buyerDTO));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public BuyerDTO updateBuyer(@PathVariable Long id, @RequestBody @Valid BuyerDTO buyerDTO) { public BuyerDTO updateBuyer(@PathVariable Long id,@RequestBody @Valid BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.updateBuyer(id, buyerDTO)); return new BuyerDTO(buyerService.updateBuyer(id,buyerDTO));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
@ -38,8 +36,12 @@ public class BuyerController {
public BuyerDTO findBuyer(@PathVariable Long id) { public BuyerDTO findBuyer(@PathVariable Long id) {
return new BuyerDTO(buyerService.findBuyer(id)); return new BuyerDTO(buyerService.findBuyer(id));
} }
@GetMapping("/car/{id}")
public List<BuyerDTO> findBuyersOnCar(@PathVariable Long id){
return buyerService.findBuyersOnWorkPlace(id).stream()
.map(BuyerDTO::new)
.toList();
}
@GetMapping @GetMapping
public List<BuyerDTO> findAllBuyer() { public List<BuyerDTO> findAllBuyer() {
return buyerService.findAllBuyers() return buyerService.findAllBuyers()

View File

@ -6,9 +6,9 @@ import jakarta.validation.constraints.NotBlank;
public class BuyerDTO { public class BuyerDTO {
private long id; private long id;
@NotBlank(message = "buyerFirstName can't be null or empty") @NotBlank(message = "FirstName can't be null or empty")
private String buyerFirstName; private String buyerFirstName;
@NotBlank(message = "buyerSecondName can't be null or empty") @NotBlank(message = "SecondName can't be null or empty")
private String buyerSecondName; private String buyerSecondName;
public BuyerDTO(Buyer buyer){ public BuyerDTO(Buyer buyer){
this.id =buyer.getId(); this.id =buyer.getId();

View File

@ -8,7 +8,7 @@ import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@Controller @Controller
@RequestMapping("/buyer") @RequestMapping("/buyer2")
public class BuyerMVCController { public class BuyerMVCController {
private final BuyerService buyerService; private final BuyerService buyerService;
public BuyerMVCController(BuyerService buyerService){ public BuyerMVCController(BuyerService buyerService){
@ -22,7 +22,15 @@ public class BuyerMVCController {
.toList()); .toList());
return "buyer"; return "buyer";
} }
@GetMapping("/info/{id}")
public String findBuyersOnCar(@PathVariable(required = false) Long id, Model model){
model.addAttribute("cathegory", "Кто работает с " + buyerService.findBuyer(id).getBuyerFirstName() + " " + buyerService.findBuyer(id).getBuyerSecondName());
model.addAttribute("buyers", buyerService.findBuyersOnWorkPlace(id).stream()
.map(BuyerDTO::new)
.toList());
model.addAttribute("page", "buyer");
return "buyer-info";
}
@GetMapping(value = {"/edit", "/edit/{id}"}) @GetMapping(value = {"/edit", "/edit/{id}"})
public String editBuyer(@PathVariable(required = false) Long id, public String editBuyer(@PathVariable(required = false) Long id,
Model model) { Model model) {

View File

@ -1,14 +1,12 @@
package com.example.maxim.lab3.controller; package com.example.maxim.lab3.controller;
import com.example.maxim.Configuration.WebConfiguration;
import com.example.maxim.lab3.service.CarService; import com.example.maxim.lab3.service.CarService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("WebConfiguration.REST_API + /car") @RequestMapping("/car")
public class CarController { public class CarController {
private final CarService carService; private final CarService carService;
public CarController(CarService carService){ public CarController(CarService carService){

View File

@ -8,7 +8,7 @@ import java.util.List;
public class CarDTO { public class CarDTO {
private long id; private long id;
@NotBlank(message = "carName can't be null or empty") @NotBlank(message = "CarName can't be null or empty")
private String carName; private String carName;
private List<BuyerDTO> buyerDTOList; private List<BuyerDTO> buyerDTOList;
private List<StoreDTO> storeDTOList; private List<StoreDTO> storeDTOList;
@ -33,24 +33,19 @@ public class CarDTO {
public String getCarName(){ public String getCarName(){
return carName; return carName;
} }
public void setCarName(String carName){
this.carName = carName;
}
public List<BuyerDTO> getBuyerDTOList(){ public List<BuyerDTO> getBuyerDTOList(){
return buyerDTOList; return buyerDTOList;
} }
public void setBuyerDTOList(List<BuyerDTO> buyers){
public void setCarName(String carName) { this.buyerDTOList = buyers;
this.carName = carName;
} }
public void setBuyerDTOList(List<BuyerDTO> buyerDTOList) {
this.buyerDTOList = buyerDTOList;
}
public void setStoreDTOList(List<StoreDTO> storeDTOList) {
this.storeDTOList = storeDTOList;
}
public List<StoreDTO> getStoreDTOList(){ public List<StoreDTO> getStoreDTOList(){
return storeDTOList; return storeDTOList;
} }
public void setStoreDTOList(List<StoreDTO> stores){
this.storeDTOList = stores;
}
} }

View File

@ -8,11 +8,10 @@ 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 java.util.List; import java.util.List;
@Controller @Controller
@RequestMapping("/car") @RequestMapping("/car2")
public class CarMVCController { public class CarMVCController {
private final CarService carService; private final CarService carService;
private final BuyerService buyerService; private final BuyerService buyerService;

View File

@ -1,14 +1,12 @@
package com.example.maxim.lab3.controller; package com.example.maxim.lab3.controller;
import com.example.maxim.Configuration.WebConfiguration;
import com.example.maxim.lab3.service.StoreService; import com.example.maxim.lab3.service.StoreService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("WebConfiguration.REST_API + /store") @RequestMapping("/store")
public class StoreController { public class StoreController {
private final StoreService storeService; private final StoreService storeService;
public StoreController(StoreService storeService){ public StoreController(StoreService storeService){
@ -38,12 +36,19 @@ public class StoreController {
public StoreDTO findStore(@PathVariable Long id) { public StoreDTO findStore(@PathVariable Long id) {
return new StoreDTO(storeService.findStore(id)); return new StoreDTO(storeService.findStore(id));
} }
@GetMapping("/buyer/{id}") @GetMapping("/buyer/{id}")
public List<BuyerDTO> findBuyersOnCar(@PathVariable Long id){ public List<BuyerDTO> findBuyersOnCar(@PathVariable Long id){
return storeService.findAllBuyersProducedStore(id).stream().map(BuyerDTO::new).toList(); return storeService.findAllBuyersProducedStore(id)
.stream()
.map(BuyerDTO::new)
.toList();
} }
@GetMapping @GetMapping
public List<StoreDTO> findAllStore() { public List<StoreDTO> findAllStore() {
return storeService.findAllStores().stream().map(StoreDTO::new).toList(); return storeService.findAllStores()
.stream()
.map(StoreDTO::new)
.toList();
} }
} }

View File

@ -9,12 +9,15 @@ import java.util.List;
public class StoreDTO { public class StoreDTO {
private long id; private long id;
@NotBlank(message = "storeName can't be null or empty") @NotBlank(message = "StoreName can't be null or empty")
private String storeName; private String storeName;
@NotNull
private int price;
private List<CarDTO> carDTOList; private List<CarDTO> carDTOList;
public StoreDTO(Store store){ public StoreDTO(Store store){
this.id = store.getId(); this.id = store.getId();
this.storeName = store.getStoreName(); this.storeName = store.getStoreName();
this.price = store.getPrice();
this.carDTOList = store.getCar() == null ? null : store.getCar() this.carDTOList = store.getCar() == null ? null : store.getCar()
.stream() .stream()
.filter(x -> x.getStores().contains(store.getId())) .filter(x -> x.getStores().contains(store.getId()))
@ -34,8 +37,13 @@ public class StoreDTO {
this.storeName = storeName; this.storeName = storeName;
} }
public int getPrice() {
return price;
}
public void setPrice(int price){
this.price = price;
}
public List<CarDTO> getCarDTOList(){ public List<CarDTO> getCarDTOList(){
return carDTOList; return carDTOList;
} }
} }

View File

@ -8,7 +8,7 @@ import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@Controller @Controller
@RequestMapping("/store") @RequestMapping("/store2123")
public class StoreMVCController { public class StoreMVCController {
private final StoreService storeService; private final StoreService storeService;
public StoreMVCController(StoreService storeService){ public StoreMVCController(StoreService storeService){
@ -23,7 +23,7 @@ public class StoreMVCController {
return "store"; return "store";
} }
@GetMapping("/info/{id}") @GetMapping("/info/{id}")
public String findBuyersOnWorkplace(@PathVariable(required = false) Long id, Model model){ public String findBuyersOnCar(@PathVariable(required = false) Long id, Model model){
model.addAttribute("cathegory", "Кто производит " + storeService.findStore(id).getStoreName()); model.addAttribute("cathegory", "Кто производит " + storeService.findStore(id).getStoreName());
model.addAttribute("buyers", storeService.findAllBuyersProducedStore(id) model.addAttribute("buyers", storeService.findAllBuyersProducedStore(id)
.stream() .stream()
@ -65,4 +65,3 @@ public class StoreMVCController {
return "redirect:/store"; return "redirect:/store";
} }
} }

View File

@ -0,0 +1,64 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.User;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.lab3.service.UserService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.IntStream;
@RestController
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
public static final String URL_SIGNUP = "/jwt/signup";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDTO userDto) {
return userService.loginAndGetToken(userDto);
}
@PostMapping(URL_SIGNUP)
public UserInfoDTO signup(@RequestBody @Valid UserDTO userDto) {
return userService.signupAndGetToken(userDto);
}
@GetMapping("/users/{login}")
public UserDetails getCurrentUser(@PathVariable String login) {
try {
return userService.loadUserByUsername(login);
} catch (Exception e) {
return null;
}
}
@GetMapping("/user")
public String findUser(@RequestParam("token") String token) {
UserDetails userDetails = userService.loadUserByToken(token);
User user = userService.findByLogin(userDetails.getUsername());
return user.getRole().toString();
}
@GetMapping("/users")
@Secured({UserRole.AsString.ADMIN})
public UsersPageDTO getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size) {
final Page<UserDTO> users = userService.findAllPages(page, size)
.map(UserDTO::new);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
return new UsersPageDTO(users, pageNumbers, totalPages);
}
}

View File

@ -2,12 +2,19 @@ package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.User; import com.example.maxim.lab3.model.User;
import com.example.maxim.lab3.model.UserRole; import com.example.maxim.lab3.model.UserRole;
import jakarta.validation.constraints.NotEmpty;
public class UserDTO { public class UserDTO {
private final long id; private long id;
private final String login; @NotEmpty
private final UserRole role; private String login;
@NotEmpty
private String password;
private String passwordConfirm;
private UserRole role;
public UserDTO() {
}
public UserDTO(User user) { public UserDTO(User user) {
this.id = user.getId(); this.id = user.getId();
this.login = user.getLogin(); this.login = user.getLogin();
@ -25,4 +32,12 @@ public class UserDTO {
public UserRole getRole() { public UserRole getRole() {
return role; return role;
} }
public String getPassword() {
return password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
} }

View File

@ -0,0 +1,26 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.UserRole;
public class UserInfoDTO {
private final String token;
private String login;
private final UserRole role;
public UserInfoDTO(String token, String login, UserRole role) {
this.token = token;
this.login = login;
this.role = role;
}
public String getToken() {
return token;
}
public UserRole getRole() {
return role;
}
public String getLogin() {
return login;
}
}

View File

@ -0,0 +1,25 @@
package com.example.maxim.lab3.controller;
import jakarta.validation.constraints.NotBlank;
public class UserLoginDTO {
@NotBlank
private String login;
@NotBlank
private String password;
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;
}
}

View File

@ -1,41 +0,0 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.lab3.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

@ -3,7 +3,7 @@ package com.example.maxim.lab3.controller;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
public class UserSignUpDTO { public class UserSignupDTO {
@NotBlank @NotBlank
@Size(min = 3, max = 64) @Size(min = 3, max = 64)
private String login; private String login;

View File

@ -1,48 +0,0 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.User;
import com.example.maxim.lab3.service.UserService;
import com.example.maxim.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,29 @@
package com.example.maxim.lab3.controller;
import org.springframework.data.domain.Page;
import java.util.List;
public class UsersPageDTO {
private Page<UserDTO> users;
private List<Integer> pageNumbers;
private int totalPages;
public UsersPageDTO(Page<UserDTO> users, List<Integer> pageNumbers, int totalPages) {
this.users = users;
this.pageNumbers = pageNumbers;
this.totalPages = totalPages;
}
public Page<UserDTO> getUsers() {
return users;
}
public List<Integer> getPageNumbers() {
return pageNumbers;
}
public int getTotalPages() {
return totalPages;
}
}

View File

@ -17,9 +17,6 @@ public class Buyer {
@NotNull(message = "Second name can't be empty") @NotNull(message = "Second name can't be empty")
@Column(name = "second_name") @Column(name = "second_name")
private String buyerSecondName; private String buyerSecondName;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Buyer(){ public Buyer(){
} }
public Buyer(String buyerFirstName, String buyerSecondName){ public Buyer(String buyerFirstName, String buyerSecondName){
@ -41,12 +38,6 @@ public class Buyer {
public void setBuyerSecondName(String buyerSecondName) { public void setBuyerSecondName(String buyerSecondName) {
this.buyerSecondName = buyerSecondName; this.buyerSecondName = buyerSecondName;
} }
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
@ -64,7 +55,6 @@ public class Buyer {
"id=" + id + "id=" + id +
", buyerFirstName='" + buyerFirstName + '\'' + ", buyerFirstName='" + buyerFirstName + '\'' +
", buyerSecondName='" + buyerSecondName + '\'' + ", buyerSecondName='" + buyerSecondName + '\'' +
", user='" + user + '\'' +
'}'; '}';
} }
} }

View File

@ -24,9 +24,6 @@ public class Car {
joinColumns = @JoinColumn(name = "car_fk"), joinColumns = @JoinColumn(name = "car_fk"),
inverseJoinColumns = @JoinColumn(name = "store_fk")) inverseJoinColumns = @JoinColumn(name = "store_fk"))
private List<Store> stores; private List<Store> stores;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Car(){ public Car(){
} }
public Car(String carName, List<Store> stores, List<Buyer> buyers){ public Car(String carName, List<Store> stores, List<Buyer> buyers){
@ -86,12 +83,6 @@ public class Car {
this.buyers.remove(buyer); this.buyers.remove(buyer);
} }
} }
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@ -109,8 +100,7 @@ public class Car {
public String toString() { public String toString() {
return "Car{" + return "Car{" +
"id=" + id + "id=" + id +
", carName='" + carName + '\'' + ", carName='" + carName + '\'' + +
", user='" + user + '\'' +
'}'; '}';
} }
} }

View File

@ -1,7 +1,6 @@
package com.example.maxim.lab3.model; package com.example.maxim.lab3.model;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -10,21 +9,21 @@ import java.util.Objects;
@Entity @Entity
public class Store { public class Store {
@Id @Id
@GeneratedValue @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@NotNull(message = "Name can't be empty") // @NotNull(message = "Name can't be empty")
@Column(name = "storeName") @Column(name = "storeName")
private String storeName; private String storeName;
//@NotNull(message = "Price can't be null or empty")
@Column(name = "price")
private Integer price;
@ManyToMany(mappedBy = "stores",cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @ManyToMany(mappedBy = "stores",cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
private List<Car> car; private List<Car> car;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Store() { public Store() {
} }
public Store(String storeName, Integer price) {
public Store(String storeName) {
this.storeName = storeName; this.storeName = storeName;
this.price = price;
} }
public Long getId() { public Long getId() {
@ -38,6 +37,15 @@ public class Store {
public void setStoreName(String storeName) { public void setStoreName(String storeName) {
this.storeName = storeName; this.storeName = storeName;
} }
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public List<Car> getCar() { public List<Car> getCar() {
return car; return car;
} }
@ -58,12 +66,6 @@ public class Store {
if (this.car.contains(car)) if (this.car.contains(car))
this.car.remove(car); this.car.remove(car);
} }
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@ -82,7 +84,7 @@ public class Store {
return "Store{" + return "Store{" +
"id=" + id + "id=" + id +
", storeName='" + storeName + '\'' + ", storeName='" + storeName + '\'' +
", user='" + user + '\'' + ", price='" + price + '\'' +
'}'; '}';
} }
} }

View File

@ -1,5 +1,6 @@
package com.example.maxim.lab3.model; package com.example.maxim.lab3.model;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
@ -64,20 +65,20 @@ public class User {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
User user = (User) o; User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(login, user.login); return Objects.equals(id, user.id);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, login); return Objects.hash(id);
} }
@Override @Override
public String toString() { public String toString() {
return "User{" + return "User{" +
"id=" + id + "id=" + id +
", login='" + login + '\'' + ", login='" + login + '\'' +
", password='" + password + '\'' + ", password='" + password + '\'' +
", role='" + role + '\'' +
'}'; '}';
} }
} }

View File

@ -4,11 +4,7 @@ import com.example.maxim.lab3.Respository.IBuyerRespository;
import com.example.maxim.lab3.controller.BuyerDTO; import com.example.maxim.lab3.controller.BuyerDTO;
import com.example.maxim.lab3.controller.CarDTO; import com.example.maxim.lab3.controller.CarDTO;
import com.example.maxim.lab3.model.Buyer; import com.example.maxim.lab3.model.Buyer;
import com.example.maxim.lab3.model.User;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.util.validation.ValidatorUtil; import com.example.maxim.util.validation.ValidatorUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -19,26 +15,14 @@ import java.util.Optional;
public class BuyerService { public class BuyerService {
private final IBuyerRespository buyerRespository; private final IBuyerRespository buyerRespository;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
private final UserService userService; public BuyerService(IBuyerRespository buyerRespositroy, ValidatorUtil validatorUtil){
this.buyerRespository = buyerRespositroy;
public BuyerService(IBuyerRespository buyerRespository, ValidatorUtil validatorUtil, UserService userService) {
this.buyerRespository = buyerRespository;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
this.userService = userService;
} }
@Transactional @Transactional
public Buyer addBuyer(BuyerDTO buyerDTO) { public Buyer addBuyer(BuyerDTO buyerDTO) {
final Buyer buyer = new Buyer(buyerDTO.getBuyerFirstName(), buyerDTO.getBuyerSecondName()); final Buyer buyer = new Buyer(buyerDTO.getBuyerFirstName(), buyerDTO.getBuyerSecondName());
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //validatorUtil.validate(buyer);
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
buyer.setUser(user);
}
}
validatorUtil.validate(buyer);
buyerRespository.save(buyer); buyerRespository.save(buyer);
return buyer; return buyer;
} }
@ -78,11 +62,15 @@ public class BuyerService {
@Transactional @Transactional
public Buyer deleteBuyer(Long id) { public Buyer deleteBuyer(Long id) {
final Buyer currentBuyer = findBuyer(id); final Buyer currentBuyer= findBuyer(id);
buyerRespository.delete(currentBuyer); buyerRespository.delete(currentBuyer);
return currentBuyer; return currentBuyer;
} }
@Transactional
public List<Buyer> findBuyersOnWorkPlace(Long id){
return buyerRespository.findBuyersOnWorkPlace(findBuyer(id));
}
@Transactional @Transactional
public void deleteAllBuyers() { public void deleteAllBuyers() {

View File

@ -2,9 +2,9 @@ package com.example.maxim.lab3.service;
import com.example.maxim.lab3.Respository.ICarRespository; import com.example.maxim.lab3.Respository.ICarRespository;
import com.example.maxim.lab3.controller.CarDTO; import com.example.maxim.lab3.controller.CarDTO;
import com.example.maxim.lab3.model.*; import com.example.maxim.lab3.model.Store;
import org.springframework.security.core.context.SecurityContextHolder; import com.example.maxim.lab3.model.Buyer;
import org.springframework.security.core.userdetails.UserDetails; import com.example.maxim.lab3.model.Car;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -16,16 +16,13 @@ public class CarService {
private final ICarRespository carRespository; private final ICarRespository carRespository;
private final StoreService storeService; private final StoreService storeService;
private final BuyerService buyerService; private final BuyerService buyerService;
private final UserService userService;
public CarService(ICarRespository carRespository, public CarService(ICarRespository carRespository,
StoreService storeService, StoreService storeService,
BuyerService buyerService, BuyerService buyerService
UserService userService
){ ){
this.carRespository = carRespository; this.carRespository = carRespository;
this.storeService = storeService; this.storeService = storeService;
this.buyerService = buyerService; this.buyerService = buyerService;
this.userService = userService;
} }
@Transactional @Transactional
@ -34,14 +31,6 @@ public class CarService {
List<Buyer> buyers = buyerService.findAllBuyerByid(carDTO); List<Buyer> buyers = buyerService.findAllBuyerByid(carDTO);
final Car car = new Car( final Car car = new Car(
carDTO.getCarName(), stores, buyers); carDTO.getCarName(), stores, buyers);
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
car.setUser(user);
}
}
carRespository.save(car); carRespository.save(car);
return car; return car;
} }

View File

@ -3,9 +3,10 @@ package com.example.maxim.lab3.service;
import com.example.maxim.lab3.Respository.IStoreRespository; import com.example.maxim.lab3.Respository.IStoreRespository;
import com.example.maxim.lab3.controller.StoreDTO; import com.example.maxim.lab3.controller.StoreDTO;
import com.example.maxim.lab3.controller.CarDTO; import com.example.maxim.lab3.controller.CarDTO;
import com.example.maxim.lab3.model.*; import com.example.maxim.lab3.model.Store;
import org.springframework.security.core.context.SecurityContextHolder; import com.example.maxim.lab3.model.Buyer;
import org.springframework.security.core.userdetails.UserDetails; import com.example.maxim.lab3.model.Car;
import com.example.maxim.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -15,22 +16,16 @@ import java.util.Optional;
@Service @Service
public class StoreService { public class StoreService {
private final IStoreRespository storeRespository; private final IStoreRespository storeRespository;
private final UserService userService; private final ValidatorUtil validatorUtil;
public StoreService(IStoreRespository storeRespository, UserService userService){ public StoreService(IStoreRespository storeRespository,
ValidatorUtil validatorUtil){
this.storeRespository = storeRespository; this.storeRespository = storeRespository;
this.userService = userService; this.validatorUtil = validatorUtil;
} }
@Transactional @Transactional
public Store addStore(StoreDTO storeDTO) { public Store addStore(StoreDTO storeDTO) {
Store store =new Store(storeDTO.getStoreName()); final Store store = new Store(storeDTO.getStoreName(), storeDTO.getPrice());
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); validatorUtil.validate(store);
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
store.setUser(user);
}
}
storeRespository.save(store); storeRespository.save(store);
return store; return store;
} }
@ -61,6 +56,7 @@ public class StoreService {
public Store updateStore(Long id, StoreDTO storeDTO) { public Store updateStore(Long id, StoreDTO storeDTO) {
final Store currentStore = findStore(id); final Store currentStore = findStore(id);
currentStore.setStoreName(storeDTO.getStoreName()); currentStore.setStoreName(storeDTO.getStoreName());
currentStore.setPrice(storeDTO.getPrice());
storeRespository.save(currentStore); storeRespository.save(currentStore);
return currentStore; return currentStore;
} }

View File

@ -0,0 +1,7 @@
package com.example.maxim.lab3.service;
public class UserExistsException extends RuntimeException {
public UserExistsException(String login) {
super(String.format("User '%s' already exists", login));
}
}

View File

@ -0,0 +1,7 @@
package com.example.maxim.lab3.service;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String login) {
super(String.format("User not found '%s'", login));
}
}

View File

@ -1,6 +1,10 @@
package com.example.maxim.lab3.service; package com.example.maxim.lab3.service;
import com.example.maxim.lab3.Respository.IUserRespository; import com.example.maxim.Configuration.jwt.JwtException;
import com.example.maxim.Configuration.jwt.JwtProvider;
import com.example.maxim.lab3.Respository.UserRepository;
import com.example.maxim.lab3.controller.UserDTO;
import com.example.maxim.lab3.controller.UserInfoDTO;
import com.example.maxim.lab3.model.User; import com.example.maxim.lab3.model.User;
import com.example.maxim.lab3.model.UserRole; import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.util.validation.ValidationException; import com.example.maxim.util.validation.ValidationException;
@ -16,31 +20,39 @@ import org.springframework.stereotype.Service;
import java.util.Collections; import java.util.Collections;
import java.util.Objects; import java.util.Objects;
@Service @Service
public class UserService implements UserDetailsService { public class UserService implements UserDetailsService{
private final IUserRespository userRepository; private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
private final JwtProvider jwtProvider;
public UserService(IUserRespository userRepository, public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder, PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil) { ValidatorUtil validatorUtil,
JwtProvider jwtProvider) {
this.userRepository = userRepository; this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
this.jwtProvider = jwtProvider;
} }
public Page<User> findAllPages(int page, int size) { public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending())); return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
} }
public User findByLogin(String login) { public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login); return userRepository.findOneByLoginIgnoreCase(login);
} }
public User createUser(String login, String password, String passwordConfirm) { public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER); return createUser(login, password, passwordConfirm, UserRole.USER);
} }
public User createUser(String login, String password, String passwordConfirm, UserRole role) { public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) { if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login)); throw new UserExistsException(login);
} }
final User user = new User(login, passwordEncoder.encode(password), role); final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user); validatorUtil.validate(user);
@ -50,6 +62,31 @@ public class UserService implements UserDetailsService {
return userRepository.save(user); return userRepository.save(user);
} }
public String loginAndGetToken(UserDTO userDto) {
final User user = findByLogin(userDto.getLogin());
if (user == null) {
throw new UserNotFoundException(userDto.getLogin());
}
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
throw new UserNotFoundException(user.getLogin());
}
return jwtProvider.generateToken(user.getLogin());
}
public UserInfoDTO signupAndGetToken(UserDTO userDto) {
final User user = createUser(userDto.getLogin(), userDto.getPassword(), userDto.getPasswordConfirm(), UserRole.USER);
return new UserInfoDTO(jwtProvider.generateToken(user.getLogin()), user.getLogin(), UserRole.USER);
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> new JwtException("Token is not contain Login"));
return loadUserByUsername(userLogin);
}
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username); final User userEntity = findByLogin(username);

View File

@ -6,7 +6,7 @@ public class ValidationException extends RuntimeException {
public <T> 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) { public ValidationException(String message) {
super(error); super(message);
} }
} }

View File

@ -1,6 +1,6 @@
spring.main.banner-mode=off spring.main.banner-mode=off
server.port=8080 server.port=8080
#server.tomcat.relaxed-query-chars=|,{,},[,] server.tomcat.relaxed-query-chars=|,{,},[,]
spring.datasource.url=jdbc:h2:file:./data spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa spring.datasource.username=sa
@ -10,3 +10,5 @@ spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true spring.h2.console.enabled=true
spring.h2.console.settings.trace=false spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false spring.h2.console.settings.web-allow-others=false
jwt.dev-token=my-secret-jwt
jwt.dev=true

View File

@ -1,10 +0,0 @@
.footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
background-color: #f5f5f5;
color: #333;
text-align: center;
padding: 10px;
}

View File

@ -1,33 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/buyer/{id}(id=*{id})}" th:object="${BuyerDTO}" method="post">
<div class="mb-3">
<label for="buyerFirstName" class="form-label">Имя</label>
<input type="text" class="form-control" id="buyerFirstName" th:field="*{buyerFirstName}"
required="true">
</div>
<div class="mb-3">
<label for="buyerSecondName" class="form-label">Фамилия</label>
<input type="text" class="form-control" id="buyerSecondName" th:field="*{buyerSecondName}"
required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-outline-dark text-center button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/buyer}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,34 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div 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="buyer, iterator: ${buyers}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${buyer.id}"></td>
<td th:text="${buyer.buyerFirstName}" style="width: 40%"></td>
<td th:text="${buyer.buyerSecondName}" style="width: 40%"></td>
</tr>
</tbody>
</table>
</div>
<a class="btn btn-secondary button-fixed d-flex justify-content-center mt-3" th:href="@{/} + ${page}">
Назад
</a>
</div>
</body>
</html>

View File

@ -1,56 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ultraq.net.nz/thymeleaf/layout " xmlns:th="http://www.w3.org/1999/xhtml"
xmlns:sec="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:href="@{/buyer/edit}">
Добавить
</a>
</div>
<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="buyer, iterator: ${buyers}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${buyer.id}"></td>
<td th:text="${buyer.buyerFirstName}" style="width: 40%"></td>
<td th:text="${buyer.buyerSecondName}" style="width: 40%"></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:href="@{/buyer/edit/{id}(id=${buyer.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" type="button" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${buyer.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/buyer/delete/{id}(id=${buyer.id})}" method="post">
<button th:id="'remove-' + ${buyer.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -1,70 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ultraq.net.nz/thymeleaf/layout " xmlns:th="http://www.w3.org/1999/xhtml"
xmlns:sec="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content" class="mw-100">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<div class="d-flex container-fluid ">
<div style="width: 100%;" class="container-fluid">
<form action="#" th:action="@{/car/{id}/buyer(id=*{id})}" method="post" >
<input name="wpName" type="hidden" th:value="${name}" />
<input name="PW" type="hidden" th:value="W" />
<div sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="mb-3">
<label for="idW" class="form-label">Работник</label>
<select class="form-select" id = "idW" th:name="buyer">
<option th:each="value: ${buyers}"
th:value="${value.id}"
th:text="${value.buyerFirstName} + ' ' + ${value.buyerSecondName}">
</option>
</select>
</div>
<div>
<button sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5">
<span>Добавить</span>
</button>
</div>
</form>
<table class="table" id="tbl-items">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Имя</th>
<th scope="col">Фамилия</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="carBuyer, iterator: ${carBuyers}">
<td th:text="${iterator.index} + 1"></td>
<td th:text="${carBuyer.buyerFirstName}"></td>
<td th:text="${carBuyer.buyerSecondName}"></td>
<td>
<div>
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" type="button" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${carBuyer.id}').click()|">
<i class="fa fa-trash"></i>
</a>
</div>
<form th:action="@{'/car/' + ${id} + '/buyer/?buyer='+ ${carBuyer.id} + '&delete=true'}" method="post">
<button th:id="'remove-' + ${carBuyer.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<a class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" th:href="@{/car}">
Назад
</a>
</div>
</div>
</body>
</html>

View File

@ -1,27 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/car/{id}(id=${CarDTO.id})}" th:object="${CarDTO}" method="post">
<div class="mb-3">
<label for="carName" class="form-label">Название</label>
<input type="text" class="form-control" id="carName" th:field="*{carName}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-outline-dark text-center button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed mx-1" th:href="@{/car}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,132 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ultraq.net.nz/thymeleaf/layout " xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content" class="mw-100">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/car/{id}(id=${id})}" method="post" class="mb-3">
<div class="d-flex justify-content-center">
<input name="PW" type="hidden" th:value="N" />
<label for="wpName" class="form-label mt-2">Название</label>
<input type="text" class="d-flex justify-content-center form-control" id="wpName" style="width: 30vw; margin-left: 2vw;" th:value="${name}" name="wpName"/>
<div style="margin-left: 2vw;">
<button type="submit" class="btn btn-outline-dark text-center button-fixed">
<span>Обновить</span>
</button>
</div>
<div style="margin-left: 2vw;">
<a class="btn btn-outline-dark text-center button-fixed" th:href="@{/car}">
Назад
</a>
</div>
</div>
</form>
<div class="d-flex container-fluid ">
<div style="width: 45vw; margin-right: 2vw" class="container-fluid">
<form action="#" th:action="@{/car/{id}(id=${id})}" method="post" >
<input name="wpName" type="hidden" th:value="${name}" />
<input name="PW" type="hidden" th:value="W" />
<div class="mb-3">
<label for="idW" class="form-label">Покупатель</label>
<select class="form-select" id = "idW" th:name="idPW">
<option th:each="value: ${buyers}"
th:value="${value.id}"
th:text="${value.buyerFirstName} + ' ' + ${value.buyerSecondName}">
</option>
</select>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-outline-dark text-center button-fixed">
<span>Добавить</span>
</button>
</div>
</form>
<table class="table" id="tbl-items">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Имя</th>
<th scope="col">Фамилия</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="carBuyer, iterator: ${carBuyers}">
<td th:text="${iterator.index} + 1"></td>
<td th:text="${carBuyer.buyerFirstName}"></td>
<td th:text="${carBuyer.buyerSecondName}"></td>
<td>
<div>
<a type="button" class="btn btn-outline-dark text-center button-fixed"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${carBuyer.id}').click()|">
<i class="fa fa-trash"></i>
</a>
</div>
<form th:action="@{'/car/' + ${id} + '?PW=W&wpName='+ ${name} +'&idPW=' + ${carBuyer.id} + '&delete=true'}" method="post">
<button th:id="'remove-' + ${carBuyer.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<div style="width: 45vw; margin-left: 2vw" class="container-fluid">
<form action="#" th:action="@{/car/{id}(id=${id})}" method="post" class="mb-3">
<input name="wpName" type="hidden" th:value="${name}" />
<input type="hidden" th:value="P" name="PW"/>
<div class="mb-3">
<label for="idP" class="form-label">Магазин</label>
<select class="form-select" id = "idP" th:name="idPW">
<option th:each="store, iterator: ${stores}"
th:value="${store.id}"
th:text="${store.storeName}">
</option>
</select>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-outline-dark text-center button-fixed">
<span>Добавить</span>
</button>
</div>
</form>
<table class="table" id="tbl-items">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Название</th>
<th scope="col">Цена</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="carStore, iterator: ${carStores}">
<td th:text="${iterator.index} + 1"></td>
<td th:text="${carStore.storeName}"></td>
<td>
<div>
<a type="button" class="btn btn-outline-dark text-center button-fixed"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${carStore.id}').click()|">
<i class="fa fa-trash"></i>
</a>
</div>
<form th:action="@{'/car/' + ${id} + '?PW=P&wpName='+ ${name} + '&idPW=' + ${carStore.id} + '&delete=true'}" method="post">
<button class = "btn btn-outline-dark text-center button-fixed" th:id="'remove-' + ${carStore.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>

View File

@ -1,66 +0,0 @@
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ultraq.net.nz/thymeleaf/layout " xmlns:th="http://www.w3.org/1999/xhtml"
xmlns:sec="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content" class="mw-100">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<div style="width: 100%;" class="container-fluid">
<form action="#" th:action="@{/car/{id}/store(id=*{id})}" method="post" class="mb-3">
<div sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="mb-3">
<label for="idP" class="form-label">Продукт</label>
<select class="form-select" id = "idP" th:name="store">
<option th:each="store, iterator: ${stores}"
th:value="${store.id}"
th:text="${store.storeName}">
</option>
</select>
</div>
<div class="mb-3">
<button sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5">
<span>Добавить</span>
</button>
</div>
</form>
<table class="table" id="tbl-items">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Название</th>
<th scope="col">Цена</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="carStore, iterator: ${carStores}">
<td th:text="${iterator.index} + 1"></td>
<td th:text="${carStore.storeName}"></td>
<td>
<div>
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" type="button" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${carStore.id}').click()|">
<i class="fa fa-trash"></i>
</a>
</div>
<form th:action="@{'/car/' + ${id} + '/store/?store='+ ${carStore.id} + '&delete=true'}" method="post">
<button th:id="'remove-' + ${carStore.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<a class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" th:href="@{/car}">
Назад
</a>
</div>
</div>
</div>
</body>
</html>

View File

@ -1,61 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:sec="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:href="@{/car/edit}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<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="car, iterator: ${cars}">
<th scope="row" th:text="${iterator.index} + 1"/>
<td th:text="${car.id}"/>
<td th:text="${car.carName}" style="width: 60%"/>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:href="@{/car/edit/{id}?PW=W(id=${car.id})}">
<i class="fa fa-user-secret" aria-hidden="true"></i> Покупатели
</a>
<a class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:href="@{/car/edit/{id}?PW=P(id=${car.id})}">
<i class="fa fa-tag" aria-hidden="true"></i> Магазины
</a>
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:href="@{/car/edit/{id}?PW=N(id=${car.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Редактировать
</a>
<button sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" type="button" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${car.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/car/delete/{id}(id=${car.id})}" method="post">
<button th:id="'remove-' + ${car.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -1,56 +0,0 @@
<!DOCTYPE html>
<html lang="ru"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:sec="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>Кашин Максим ПИбд-22</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
<link href="public/styles/style.css"/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav" th:with="activeLink=${#requestURI}">
<a class="nav-link" href="/store"
th:classappend="${#strings.equals(activeLink, '/store')} ? 'active' : ''">Магазин</a>
<a class="nav-link" href="/buyer"
th:classappend="${#strings.equals(activeLink, '/buyer')} ? 'active' : ''">Покупатели</a>
<a class="nav-link" href="/car"
th:classappend="${#strings.equals(activeLink, '/car')} ? 'active' : ''">Машины</a>
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="nav-link" href="/users"
th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
<a sec:authorize="isAuthenticated()" class="nav-link" href="/logout">
Выход (<span th:text="${#authentication.name}"></span>)
</a>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="container p-3" layout:fragment="content">
</div>
</div>
<footer class="ft d-flex justify-content-center"
style=" position: fixed;
left: 0;
bottom: 0;
width: 100%;
background-color: #f5f5f5;
color: #333;
text-align: center;
padding: 10px;">
Кашин Максим ПИбд-22
</footer>
</body>
</html>

View File

@ -1,9 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
</body>
</html>

View File

@ -1,9 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
</body>
</html>

View File

@ -1,32 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
>
<head>
</head>
<body>
<div layout:fragment="content">
<div th:if="${param.error}" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5">
Пользователь не найден или пароль указан не верно
</div>
<div th:if="${param.logout}" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5">
Выход успешно произведен
</div>
<div th:if="${param.created}" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5">
Пользователь '<span th:text="${param.created}"></span>' успешно создан
</div>
<form th:action="@{/login}" method="post" class="center-m">
<h4>Логин</h4>
<input class="form-control my-2" name="username" id="username" type="text" placeholder="Логин" required="true" autofocus="true"/>
<h4>Пароль</h4>
<input class="form-control my-2" name="password" id="password" type="password" placeholder="Пароль" required="true" />
<div class="d-flex justify-content-center">
<button class="btn btn-outline-dark text-center button-fixed">Войти</button>
<a class="btn btn-secondary button-fixed mx-1" href="/signup">Зарегистироваться</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,29 +0,0 @@
<!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 container-padding mt-3" layout:fragment="content">
<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="mx-4">
<button class="btn btn-outline-dark text-center button-fixed">Создать</button>
<a class="btn btn-secondary button-fixed mx-1" href="/login">Назад</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,27 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/store/{id}(id=*{id})}" th:object="${StoreDTO}" method="post">
<div class="mb-3">
<label for="storeName" class="form-label">Название</label>
<input type="text" class="form-control" id="storeName" th:field="*{storeName}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-outline-dark text-center button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/store}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -1,56 +0,0 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:sec="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:href="@{/store/edit}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Название</th>
</tr>
</thead>
<tbody>
<tr th:each="store, iterator: ${stores}">
<th scope="row" th:text="${iterator.index} + 1"/>
<td th:text="${store.id}"/>
<td th:text="${store.storeName}" style="width: 40%"></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:href="@{/store/info/{id}(id=${store.id})}">
<i class="fa fa-info" aria-hidden="true"></i> Инфо
</a>
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:href="@{/store/edit/{id}(id=${store.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" type="button" class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5" style="min-width: 120px;"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${store.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/store/delete/{id}(id=${store.id})}" method="post">
<button th:id="'remove-' + ${store.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -1,38 +0,0 @@
<!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="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>
</div>
</body>
</html>