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 {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
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-validation'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.4'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
implementation 'com.auth0:java-jwt:4.4.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'}
tasks.named('test') {
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
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder createPasswordEncoder(){
public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -1,6 +1,7 @@
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.service.UserService;
import org.slf4j.Logger;
@ -11,19 +12,23 @@ 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.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.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
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 JwtFilter jwtFilter;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup();
}
@ -34,32 +39,54 @@ public class SecurityConfiguration {
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
log.info("Creating security configuration");
http.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers(UserSignUpMVCController.SIGNUP_URL).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL)
.permitAll()
.anyRequest().authenticated()
.requestMatchers("/", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_SIGNUP).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.requestMatchers(HttpMethod.GET, "/users/*").permitAll()
.requestMatchers(HttpMethod.GET, "/h2-console").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.and()
.logout().permitAll();
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
return http.build();
}
@Bean
public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http
.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userService);
return authenticationManagerBuilder.build();
public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoderConfiguration bCryptPasswordEncoder)
throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(userService)
.passwordEncoder(bCryptPasswordEncoder.createPasswordEncoder())
.and()
.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("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;
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.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override
public void addCorsMappings(CorsRegistry registry){
@ -18,20 +18,33 @@ public class WebConfiguration implements WebMvcConfigurer {
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK);
registry.addViewController("login");
}
//@Override
//public void addViewControllers(ViewControllerRegistry registry) {
// WebMvcConfigurer.super.addViewControllers(registry);
// registry.addViewController("rest-test");
//}
// @Bean
// public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
// return container -> {
// container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
// };
// }
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> {
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;
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;
import com.example.maxim.lab3.model.Buyer;
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.Query;
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;
import com.example.maxim.Configuration.WebConfiguration;
import com.example.maxim.lab3.service.BuyerService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("(WebConfiguration.REST_API + /buyer")
@RequestMapping("/buyer")
public class BuyerController {
private final BuyerService buyerService;
public BuyerController(BuyerService buyerService){
this.buyerService = buyerService;
}
@PostMapping
public BuyerDTO addBuyer(@RequestBody @Valid BuyerDTO buyerDTO) {
public BuyerDTO addBuyer(@RequestBody BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.addBuyer(buyerDTO));
}
@PutMapping("/{id}")
public BuyerDTO updateBuyer(@PathVariable Long id, @RequestBody @Valid BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.updateBuyer(id, buyerDTO));
public BuyerDTO updateBuyer(@PathVariable Long id,@RequestBody @Valid BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.updateBuyer(id,buyerDTO));
}
@DeleteMapping("/{id}")
@ -38,8 +36,12 @@ public class BuyerController {
public BuyerDTO findBuyer(@PathVariable Long 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
public List<BuyerDTO> findAllBuyer() {
return buyerService.findAllBuyers()

View File

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

View File

@ -8,7 +8,7 @@ import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/buyer")
@RequestMapping("/buyer2")
public class BuyerMVCController {
private final BuyerService buyerService;
public BuyerMVCController(BuyerService buyerService){
@ -22,10 +22,18 @@ public class BuyerMVCController {
.toList());
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}"})
public String editBuyer(@PathVariable(required = false) Long id,
Model model) {
Model model) {
if (id == null || id <= 0) {
model.addAttribute("BuyerDTO", new BuyerDTO());
} else {
@ -36,9 +44,9 @@ public class BuyerMVCController {
}
@PostMapping(value = {"", "/{id}"})
public String saveBuyer(@PathVariable(required = false) Long id,
@ModelAttribute @Valid BuyerDTO buyerDTO,
BindingResult bindingResult,
Model model) {
@ModelAttribute @Valid BuyerDTO buyerDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "buyer-edit";

View File

@ -1,14 +1,12 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.Configuration.WebConfiguration;
import com.example.maxim.lab3.service.CarService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("WebConfiguration.REST_API + /car")
@RequestMapping("/car")
public class CarController {
private final CarService carService;
public CarController(CarService carService){
@ -37,8 +35,8 @@ public class CarController {
@GetMapping
public List<CarDTO> findAllCars(){
return carService.findAllCars()
.stream()
.map(x -> new CarDTO(x))
.toList();
.stream()
.map(x -> new CarDTO(x))
.toList();
}
}

View File

@ -8,7 +8,7 @@ import java.util.List;
public class CarDTO {
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 List<BuyerDTO> buyerDTOList;
private List<StoreDTO> storeDTOList;
@ -33,24 +33,19 @@ public class CarDTO {
public String getCarName(){
return carName;
}
public void setCarName(String carName){
this.carName = carName;
}
public List<BuyerDTO> getBuyerDTOList(){
return buyerDTOList;
}
public void setCarName(String carName) {
this.carName = carName;
public void setBuyerDTOList(List<BuyerDTO> buyers){
this.buyerDTOList = buyers;
}
public void setBuyerDTOList(List<BuyerDTO> buyerDTOList) {
this.buyerDTOList = buyerDTOList;
}
public void setStoreDTOList(List<StoreDTO> storeDTOList) {
this.storeDTOList = storeDTOList;
}
public List<StoreDTO> getStoreDTOList(){
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.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/car")
@RequestMapping("/car2")
public class CarMVCController {
private final CarService carService;
private final BuyerService buyerService;
@ -32,10 +31,10 @@ public class CarMVCController {
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editCar(@PathVariable(required = false) Long id,
Model model) {
Model model) {
if (id == null || id <= 0) {
List<BuyerDTO> buyers = buyerService.findAllBuyers().stream()
.map(BuyerDTO::new).toList();
.map(BuyerDTO::new).toList();
List<StoreDTO> stores = storeService.findAllStores().stream()
.map(StoreDTO::new).toList();
model.addAttribute("CarDTO", new CarDTO());
@ -53,7 +52,7 @@ public class CarMVCController {
.map(BuyerDTO::new)
.toList();
List<StoreDTO> stores = storeService.findAllStores().stream()
.map(StoreDTO::new).toList();
.map(StoreDTO::new).toList();
List<StoreDTO> carStores = carService
.findCar(id)
.getStores()
@ -72,13 +71,13 @@ public class CarMVCController {
}
@PostMapping(value = {"/"})
public String saveCar(@ModelAttribute @Valid CarDTO carDTO,
BindingResult bindingResult,
Model model) {
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "car-create";
}
carService.addCar(carDTO);
carService.addCar(carDTO);
// } else {
// carService.updateCar(id, carDTO);
// }
@ -86,11 +85,11 @@ public class CarMVCController {
}
@PostMapping(value = {"/{id}"})
public String editCar(@PathVariable Long id,
@RequestParam("PW") String PW,
@RequestParam("wpName") String name,
@RequestParam(value="idPW", required = false) Long idPW,
@RequestParam(value = "delete", required = false) boolean del,
Model model) {
@RequestParam("PW") String PW,
@RequestParam("wpName") String name,
@RequestParam(value="idPW", required = false) Long idPW,
@RequestParam(value = "delete", required = false) boolean del,
Model model) {
if(PW.equals("N")){
carService.findCar(id).setCarName(name);
carService.updateCar(id, new CarDTO(carService.findCar(id)));

View File

@ -1,14 +1,12 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.Configuration.WebConfiguration;
import com.example.maxim.lab3.service.StoreService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("WebConfiguration.REST_API + /store")
@RequestMapping("/store")
public class StoreController {
private final StoreService storeService;
public StoreController(StoreService storeService){
@ -38,12 +36,19 @@ public class StoreController {
public StoreDTO findStore(@PathVariable Long id) {
return new StoreDTO(storeService.findStore(id));
}
@GetMapping("/buyer/{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
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 {
private long id;
@NotBlank(message = "storeName can't be null or empty")
@NotBlank(message = "StoreName can't be null or empty")
private String storeName;
@NotNull
private int price;
private List<CarDTO> carDTOList;
public StoreDTO(Store store){
this.id = store.getId();
this.storeName = store.getStoreName();
this.price = store.getPrice();
this.carDTOList = store.getCar() == null ? null : store.getCar()
.stream()
.filter(x -> x.getStores().contains(store.getId()))
@ -34,8 +37,13 @@ public class StoreDTO {
this.storeName = storeName;
}
public int getPrice() {
return price;
}
public void setPrice(int price){
this.price = price;
}
public List<CarDTO> getCarDTOList(){
return carDTOList;
}
}

View File

@ -8,7 +8,7 @@ import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/store")
@RequestMapping("/store2123")
public class StoreMVCController {
private final StoreService storeService;
public StoreMVCController(StoreService storeService){
@ -23,7 +23,7 @@ public class StoreMVCController {
return "store";
}
@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("buyers", storeService.findAllBuyersProducedStore(id)
.stream()
@ -34,7 +34,7 @@ public class StoreMVCController {
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editStore(@PathVariable(required = false) Long id,
Model model) {
Model model) {
if (id == null || id <= 0) {
model.addAttribute("StoreDTO", new StoreDTO());
} else {
@ -65,4 +65,3 @@ public class StoreMVCController {
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.UserRole;
import jakarta.validation.constraints.NotEmpty;
public class UserDTO {
private final long id;
private final String login;
private final UserRole role;
private long id;
@NotEmpty
private String login;
@NotEmpty
private String password;
private String passwordConfirm;
private UserRole role;
public UserDTO() {
}
public UserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
@ -25,4 +32,12 @@ public class UserDTO {
public UserRole getRole() {
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.Size;
public class UserSignUpDTO {
public class UserSignupDTO {
@NotBlank
@Size(min = 3, max = 64)
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")
@Column(name = "second_name")
private String buyerSecondName;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Buyer(){
}
public Buyer(String buyerFirstName, String buyerSecondName){
@ -41,12 +38,6 @@ public class Buyer {
public void setBuyerSecondName(String buyerSecondName) {
this.buyerSecondName = buyerSecondName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@ -64,7 +55,6 @@ public class Buyer {
"id=" + id +
", buyerFirstName='" + buyerFirstName + '\'' +
", buyerSecondName='" + buyerSecondName + '\'' +
", user='" + user + '\'' +
'}';
}
}

View File

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

View File

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

View File

@ -1,5 +1,6 @@
package com.example.maxim.lab3.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
@ -64,20 +65,20 @@ public class User {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(login, user.login);
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id, login);
return Objects.hash(id);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", 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.CarDTO;
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 org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -19,26 +15,14 @@ import java.util.Optional;
public class BuyerService {
private final IBuyerRespository buyerRespository;
private final ValidatorUtil validatorUtil;
private final UserService userService;
public BuyerService(IBuyerRespository buyerRespository, ValidatorUtil validatorUtil, UserService userService) {
this.buyerRespository = buyerRespository;
public BuyerService(IBuyerRespository buyerRespositroy, ValidatorUtil validatorUtil){
this.buyerRespository = buyerRespositroy;
this.validatorUtil = validatorUtil;
this.userService = userService;
}
@Transactional
public Buyer addBuyer(BuyerDTO buyerDTO) {
final Buyer buyer = new Buyer(buyerDTO.getBuyerFirstName(), buyerDTO.getBuyerSecondName());
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){
buyer.setUser(user);
}
}
validatorUtil.validate(buyer);
//validatorUtil.validate(buyer);
buyerRespository.save(buyer);
return buyer;
}
@ -78,11 +62,15 @@ public class BuyerService {
@Transactional
public Buyer deleteBuyer(Long id) {
final Buyer currentBuyer = findBuyer(id);
final Buyer currentBuyer= findBuyer(id);
buyerRespository.delete(currentBuyer);
return currentBuyer;
}
@Transactional
public List<Buyer> findBuyersOnWorkPlace(Long id){
return buyerRespository.findBuyersOnWorkPlace(findBuyer(id));
}
@Transactional
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.controller.CarDTO;
import com.example.maxim.lab3.model.*;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.example.maxim.lab3.model.Store;
import com.example.maxim.lab3.model.Buyer;
import com.example.maxim.lab3.model.Car;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -16,16 +16,13 @@ public class CarService {
private final ICarRespository carRespository;
private final StoreService storeService;
private final BuyerService buyerService;
private final UserService userService;
public CarService(ICarRespository carRespository,
StoreService storeService,
BuyerService buyerService,
UserService userService
StoreService storeService,
BuyerService buyerService
){
this.carRespository = carRespository;
this.storeService = storeService;
this.buyerService = buyerService;
this.userService = userService;
}
@Transactional
@ -34,14 +31,6 @@ public class CarService {
List<Buyer> buyers = buyerService.findAllBuyerByid(carDTO);
final Car car = new Car(
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);
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.controller.StoreDTO;
import com.example.maxim.lab3.controller.CarDTO;
import com.example.maxim.lab3.model.*;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.example.maxim.lab3.model.Store;
import com.example.maxim.lab3.model.Buyer;
import com.example.maxim.lab3.model.Car;
import com.example.maxim.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -15,22 +16,16 @@ import java.util.Optional;
@Service
public class StoreService {
private final IStoreRespository storeRespository;
private final UserService userService;
public StoreService(IStoreRespository storeRespository, UserService userService){
private final ValidatorUtil validatorUtil;
public StoreService(IStoreRespository storeRespository,
ValidatorUtil validatorUtil){
this.storeRespository = storeRespository;
this.userService = userService;
this.validatorUtil = validatorUtil;
}
@Transactional
public Store addStore(StoreDTO storeDTO) {
Store store =new Store(storeDTO.getStoreName());
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){
store.setUser(user);
}
}
final Store store = new Store(storeDTO.getStoreName(), storeDTO.getPrice());
validatorUtil.validate(store);
storeRespository.save(store);
return store;
}
@ -61,6 +56,7 @@ public class StoreService {
public Store updateStore(Long id, StoreDTO storeDTO) {
final Store currentStore = findStore(id);
currentStore.setStoreName(storeDTO.getStoreName());
currentStore.setPrice(storeDTO.getPrice());
storeRespository.save(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;
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.UserRole;
import com.example.maxim.util.validation.ValidationException;
@ -16,31 +20,39 @@ import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final IUserRespository userRepository;
public class UserService implements UserDetailsService{
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
private final JwtProvider jwtProvider;
public UserService(IUserRespository userRepository,
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil) {
ValidatorUtil validatorUtil,
JwtProvider jwtProvider) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
this.jwtProvider = jwtProvider;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login));
throw new UserExistsException(login);
}
final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
@ -50,6 +62,31 @@ public class UserService implements UserDetailsService {
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
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);

View File

@ -6,7 +6,7 @@ public class ValidationException extends RuntimeException {
public <T> ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
public <T> ValidationException(String error) {
super(error);
public ValidationException(String message) {
super(message);
}
}

View File

@ -1,6 +1,6 @@
spring.main.banner-mode=off
server.port=8080
#server.tomcat.relaxed-query-chars=|,{,},[,]
server.tomcat.relaxed-query-chars=|,{,},[,]
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
@ -10,3 +10,5 @@ spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=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>