LabWork06 MVC WORK

This commit is contained in:
Артём Алейкин 2023-06-13 15:33:09 +04:00
parent 5edb2b497e
commit fbc3160393
13 changed files with 157 additions and 26 deletions

View File

@ -20,9 +20,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.h2database:h2:2.1.210' implementation 'com.h2database:h2:2.1.210'
implementation 'com.auth0:java-jwt:4.4.0' implementation 'com.auth0:java-jwt:4.4.0'
//implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6' implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
implementation 'org.springframework.boot:spring-boot-devtools' implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3' implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0' implementation 'org.webjars:jquery:3.6.0'

View File

@ -1,8 +1,7 @@
/*
package ru.ulstu.is.sbapp.HardwareShop.controller; package ru.ulstu.is.sbapp.HardwareShop.controller;
import ru.ip.labworks.labworks.bookshop.model.User; import ru.ulstu.is.sbapp.HardwareShop.models.User;
import ru.ip.labworks.labworks.bookshop.model.UserRole; import ru.ulstu.is.sbapp.HardwareShop.models.UserRole;
public class UserDto { public class UserDto {
private final long id; private final long id;
@ -26,4 +25,4 @@ public class UserDto {
public UserRole getRole() { public UserRole getRole() {
return role; return role;
} }
}*/ }

View File

@ -0,0 +1,41 @@
package ru.ulstu.is.sbapp.HardwareShop.controller;
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 ru.ulstu.is.sbapp.HardwareShop.models.UserRole;
import ru.ulstu.is.sbapp.HardwareShop.services.UserService;
import java.util.List;
import java.util.stream.IntStream;
@Controller
@RequestMapping("/users")
public class UserMvcController {
private final UserService userService;
public UserMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
@Secured({UserRole.AsString.ADMIN})
public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size,
Model model) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "users";
}
}

View File

@ -0,0 +1,40 @@
package ru.ulstu.is.sbapp.HardwareShop.controller;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignUpDTO {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,48 @@
package ru.ulstu.is.sbapp.HardwareShop.controller;
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;
import ru.ulstu.is.sbapp.HardwareShop.models.User;
import ru.ulstu.is.sbapp.HardwareShop.services.UserService;
import jakarta.validation.Valid;
import jakarta.validation.ValidationException;
@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

@ -1,10 +1,9 @@
/*
package ru.ulstu.is.sbapp.HardwareShop.models; package ru.ulstu.is.sbapp.HardwareShop.models;
import jakarta.persistance.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import javax.persistence.*;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@ -81,4 +80,4 @@ public class User {
", role='" + role + '\'' + ", role='" + role + '\'' +
'}'; '}';
} }
}*/ }

View File

@ -1,4 +1,3 @@
/*
package ru.ulstu.is.sbapp.HardwareShop.repository; package ru.ulstu.is.sbapp.HardwareShop.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
@ -6,4 +5,4 @@ import ru.ulstu.is.sbapp.HardwareShop.models.User;
public interface UserRepository extends JpaRepository<User, Long> { public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login); User findOneByLoginIgnoreCase(String login);
}*/ }

View File

@ -1,4 +1,3 @@
/*
package ru.ulstu.is.sbapp.HardwareShop.services; package ru.ulstu.is.sbapp.HardwareShop.services;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
@ -64,4 +63,4 @@ public class UserService implements UserDetailsService {
final Optional<User> user = userRepository.findById(id); final Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id)); return user.orElseThrow(() -> new UserNotFoundException(id));
} }
}*/ }

View File

@ -1,4 +1,3 @@
/*
package ru.ulstu.is.sbapp; package ru.ulstu.is.sbapp;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -11,9 +10,9 @@ 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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import ru.ip.labworks.labworks.bookshop.controller.UserSignUpMvcController; import ru.ulstu.is.sbapp.HardwareShop.controller.UserSignUpMvcController;
import ru.ip.labworks.labworks.bookshop.model.UserRole; import ru.ulstu.is.sbapp.HardwareShop.models.UserRole;
import ru.ip.labworks.labworks.bookshop.service.UserService; import ru.ulstu.is.sbapp.HardwareShop.services.UserService;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@ -44,13 +43,13 @@ public class SecurityConfiguration {
.cors().and() .cors().and()
.csrf().disable() .csrf().disable()
.authorizeHttpRequests() .authorizeHttpRequests()
.requestMatchers(UserSignUpMvcController.SIGNUP_URL).permitAll() .antMatchers(UserSignUpMvcController.SIGNUP_URL).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll() .antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()
.formLogin() .formLogin()
.loginPage(LOGIN_URL).permitAll() .loginPage(LOGIN_URL).permitAll()
.defaultSuccessUrl("/author", true) .defaultSuccessUrl("/product", true)
.and() .and()
.logout().permitAll(); .logout().permitAll();
return http.userDetailsService(userService).build(); return http.userDetailsService(userService).build();
@ -60,9 +59,9 @@ public class SecurityConfiguration {
@Bean @Bean
public WebSecurityCustomizer webSecurityCustomizer() { public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring() return (web) -> web.ignoring()
.requestMatchers("/css/**") .antMatchers("/css/**")
.requestMatchers("/js/**") .antMatchers("/js/**")
.requestMatchers("/templates/**") .antMatchers("/templates/**")
.requestMatchers("/webjars/**"); .antMatchers("/webjars/**");
}
} }
}*/

View File

@ -11,6 +11,7 @@ public class WebConfiguration implements WebMvcConfigurer {
@Override @Override
public void addViewControllers(ViewControllerRegistry registry) { public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry); WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("login");
registry.addViewController("product"); registry.addViewController("product");
} }

View File

@ -9,3 +9,4 @@ 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

View File

@ -1,7 +1,9 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" <html lang="en"
xmlns:th="http://www.thymeleaf.org" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"> xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Онлайн магазин</title> <title>Онлайн магазин</title>
@ -26,6 +28,8 @@
<a class="nav-link active text-white" aria-current="page" href="/product" th:classappend="${#strings.equals(activeLink, '/product')} ? 'active' : ''">Products</a> <a class="nav-link active text-white" aria-current="page" href="/product" th:classappend="${#strings.equals(activeLink, '/product')} ? 'active' : ''">Products</a>
<a class="nav-link active text-white" href="/category" th:classappend="${#strings.equals(activeLink, '/category')} ? 'active' : ''">Categories</a> <a class="nav-link active text-white" href="/category" th:classappend="${#strings.equals(activeLink, '/category')} ? 'active' : ''">Categories</a>
<a class="nav-link active text-white" href="/manufacturer" th:classappend="${#strings.equals(activeLink, '/manufacturer')} ? 'active' : ''">Manufacturers</a> <a class="nav-link active text-white" href="/manufacturer" th:classappend="${#strings.equals(activeLink, '/manufacturer')} ? 'active' : ''">Manufacturers</a>
<a sec:authorize="hasRole('ROLE_ADMIN')" class="nav-link" href="/users" th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
<a class="nav-link active text-white" href="/logout" th:classappend="${#strings.equals(activeLink, '/login')} ? 'active' : ''">Logout</a>
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,3 +1,4 @@
/*
package ru.ulstu.is.sbapp; package ru.ulstu.is.sbapp;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
@ -89,3 +90,4 @@ class SbappApplicationTests {
Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> calculatorService.getSum(1, 2, "date")); Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> calculatorService.getSum(1, 2, "date"));
} }
} }
*/