Compare commits
2 Commits
495e376d9d
...
df5f6487f3
Author | SHA1 | Date | |
---|---|---|---|
df5f6487f3 | |||
c349fa70eb |
@ -27,6 +27,9 @@ dependencies {
|
||||
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'
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
package com.labwork01.app.author.controller;
|
||||
|
||||
import com.labwork01.app.WebConfiguration;
|
||||
import com.labwork01.app.author.service.AuthorService;
|
||||
import com.labwork01.app.configuration.WebConfiguration;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.labwork01.app.author.model;
|
||||
|
||||
import com.labwork01.app.book.model.Book;
|
||||
import com.labwork01.app.user.model.User;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@ -19,6 +20,9 @@ public class Author {
|
||||
private String patronymic;
|
||||
@OneToMany(cascade = CascadeType.REMOVE, mappedBy = "author", fetch = FetchType.EAGER)
|
||||
private List<Book> books =new ArrayList<>();
|
||||
@ManyToOne
|
||||
@JoinColumn(name= "user_id", nullable = false)
|
||||
private User user;
|
||||
|
||||
public List<Book> getBooks() {
|
||||
return books;
|
||||
@ -71,6 +75,12 @@ public class Author {
|
||||
public void setPatronymic(String patronymic) {
|
||||
this.patronymic = patronymic;
|
||||
}
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
@ -88,6 +98,7 @@ public class Author {
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' + '}' +
|
||||
", surname='" + surname + '\'' + '}' +
|
||||
", patronymic='" + patronymic + '\'' + '}';
|
||||
", patronymic='" + patronymic + '\'' +
|
||||
", user='" + user.toString() + '\'' + '}' + '}';
|
||||
}
|
||||
}
|
||||
|
@ -2,7 +2,12 @@ package com.labwork01.app.author.service;
|
||||
|
||||
import com.labwork01.app.author.model.Author;
|
||||
import com.labwork01.app.author.repository.AuthorRepository;
|
||||
import com.labwork01.app.user.model.User;
|
||||
import com.labwork01.app.user.model.UserRole;
|
||||
import com.labwork01.app.user.service.UserService;
|
||||
import com.labwork01.app.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;
|
||||
|
||||
@ -12,15 +17,25 @@ import java.util.Optional;
|
||||
@Service
|
||||
public class AuthorService {
|
||||
private final AuthorRepository authorRepository;
|
||||
private final UserService userService;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
public AuthorService(AuthorRepository authorRepository, ValidatorUtil validatorUtil){
|
||||
public AuthorService(AuthorRepository authorRepository, UserService userService, ValidatorUtil validatorUtil){
|
||||
this.authorRepository = authorRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Author addAuthor(String name, String surname, String patronymic) {
|
||||
final Author author = new Author(name,surname,patronymic);
|
||||
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){
|
||||
author.setUser(user);
|
||||
}
|
||||
}
|
||||
validatorUtil.validate(author);
|
||||
return authorRepository.save(author);
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
package com.labwork01.app.book.controller;
|
||||
|
||||
import com.labwork01.app.WebConfiguration;
|
||||
import com.labwork01.app.author.service.AuthorService;
|
||||
import com.labwork01.app.book.service.BookService;
|
||||
import com.labwork01.app.configuration.WebConfiguration;
|
||||
import com.labwork01.app.genre.controller.GenreDto;
|
||||
import com.labwork01.app.genre.model.Genre;
|
||||
import com.labwork01.app.genre.service.GenreService;
|
||||
|
@ -2,6 +2,7 @@ package com.labwork01.app.book.model;
|
||||
|
||||
import com.labwork01.app.author.model.Author;
|
||||
import com.labwork01.app.genre.model.Genre;
|
||||
import com.labwork01.app.user.model.User;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@ -25,6 +26,9 @@ public class Book {
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "author_id", nullable = false)
|
||||
private Author author;
|
||||
@ManyToOne
|
||||
@JoinColumn(name= "user_id", nullable = false)
|
||||
private User user;
|
||||
public Book() {
|
||||
}
|
||||
|
||||
@ -92,6 +96,12 @@ public class Book {
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
@ -114,6 +124,7 @@ public class Book {
|
||||
", description='" + description + '\'' +
|
||||
", author='" + author.toString() + '\'' +
|
||||
", genres='" + String.join(", ",getGenresName()) + '\'' +
|
||||
", user='" + user.toString() + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
@ -6,7 +6,12 @@ import com.labwork01.app.book.model.Book;
|
||||
import com.labwork01.app.book.repository.BookRepository;
|
||||
import com.labwork01.app.genre.model.Genre;
|
||||
import com.labwork01.app.genre.service.GenreService;
|
||||
import com.labwork01.app.user.model.User;
|
||||
import com.labwork01.app.user.model.UserRole;
|
||||
import com.labwork01.app.user.service.UserService;
|
||||
import com.labwork01.app.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;
|
||||
|
||||
@ -18,11 +23,13 @@ public class BookService {
|
||||
private final BookRepository bookRepository;
|
||||
private final GenreService genreService;
|
||||
private final AuthorService authorService;
|
||||
private final UserService userService;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
public BookService(BookRepository bookRepository,GenreService genreService, AuthorService authorService, ValidatorUtil validatorUtil){
|
||||
public BookService(BookRepository bookRepository,GenreService genreService, AuthorService authorService, UserService userService, ValidatorUtil validatorUtil){
|
||||
this.bookRepository = bookRepository;
|
||||
this.genreService = genreService;
|
||||
this.authorService = authorService;
|
||||
this.userService = userService;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
@ -33,6 +40,14 @@ public class BookService {
|
||||
for (Genre genre: genres) {
|
||||
book.addGenre(genre);
|
||||
}
|
||||
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){
|
||||
book.setUser(user);
|
||||
}
|
||||
}
|
||||
validatorUtil.validate(book);
|
||||
return bookRepository.save(book);
|
||||
}
|
||||
|
@ -0,0 +1,14 @@
|
||||
package com.labwork01.app.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class PasswordEncoderConfiguration {
|
||||
@Bean
|
||||
public PasswordEncoder createPasswordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package com.labwork01.app.configuration;
|
||||
|
||||
import com.labwork01.app.user.controller.UserSignupMvcController;
|
||||
import com.labwork01.app.user.model.UserRole;
|
||||
import com.labwork01.app.user.service.UserService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true)
|
||||
public class SecurityConfiguration {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
private static final String LOGIN_URL = "/login";
|
||||
private final UserService userService;
|
||||
|
||||
public SecurityConfiguration(UserService userService) {
|
||||
this.userService = userService;
|
||||
createAdminOnStartup();
|
||||
}
|
||||
|
||||
private void createAdminOnStartup() {
|
||||
final String admin = "admin";
|
||||
if (userService.findByLogin(admin) == null) {
|
||||
log.info("Admin user successfully created");
|
||||
userService.createUser(admin, admin, admin, UserRole.ADMIN);
|
||||
}
|
||||
}
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.headers().frameOptions().sameOrigin().and()
|
||||
.cors().and()
|
||||
.csrf().disable()
|
||||
.authorizeHttpRequests()
|
||||
.requestMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
|
||||
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage(LOGIN_URL).permitAll()
|
||||
.and()
|
||||
.logout().permitAll();
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception {
|
||||
AuthenticationManagerBuilder authenticationManagerBuilder = http
|
||||
.getSharedObject(AuthenticationManagerBuilder.class);
|
||||
authenticationManagerBuilder.userDetailsService(userService);
|
||||
return authenticationManagerBuilder.build();
|
||||
}
|
||||
@Bean
|
||||
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web.ignoring().requestMatchers("/css/**", "/js/**","/templates/**","/webjars/**");
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.labwork01.app;
|
||||
package com.labwork01.app.configuration;
|
||||
|
||||
import org.springframework.boot.web.server.ErrorPage;
|
||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
@ -23,6 +23,7 @@ public class WebConfiguration implements WebMvcConfigurer {
|
||||
ViewControllerRegistration registration = registry.addViewController("/notFound");
|
||||
registration.setViewName("forward:/index.html");
|
||||
registration.setStatusCode(HttpStatus.OK);
|
||||
registry.addViewController("login");
|
||||
|
||||
// Alternative way (404 error hits the console):
|
||||
// > registry.addViewController("/notFound").setViewName("forward:/index.html");
|
@ -1,6 +1,6 @@
|
||||
package com.labwork01.app.genre.controller;
|
||||
|
||||
import com.labwork01.app.WebConfiguration;
|
||||
import com.labwork01.app.configuration.WebConfiguration;
|
||||
import com.labwork01.app.genre.service.GenreService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
@ -1,5 +1,6 @@
|
||||
package com.labwork01.app.genre.model;
|
||||
|
||||
import com.labwork01.app.user.model.User;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.util.Objects;
|
||||
@ -11,6 +12,9 @@ public class Genre {
|
||||
private Long id;
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
@ManyToOne
|
||||
@JoinColumn(name= "user_id", nullable = false)
|
||||
private User user;
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
@ -23,6 +27,12 @@ public class Genre {
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
public Genre() {
|
||||
}
|
||||
public Genre(String name) {
|
||||
@ -44,6 +54,7 @@ public class Genre {
|
||||
public String toString() {
|
||||
return "Genre{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' + '}';
|
||||
", name='" + name + '\'' +
|
||||
", user='" + user.toString() + '\'' + '}';
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,12 @@ package com.labwork01.app.genre.service;
|
||||
import com.labwork01.app.book.model.Book;
|
||||
import com.labwork01.app.genre.model.Genre;
|
||||
import com.labwork01.app.genre.repository.GenreRepository;
|
||||
import com.labwork01.app.user.model.User;
|
||||
import com.labwork01.app.user.model.UserRole;
|
||||
import com.labwork01.app.user.service.UserService;
|
||||
import com.labwork01.app.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;
|
||||
|
||||
@ -13,15 +18,25 @@ import java.util.Optional;
|
||||
@Service
|
||||
public class GenreService {
|
||||
private final GenreRepository genreRepository;
|
||||
private final UserService userService;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
public GenreService(GenreRepository genreRepository, ValidatorUtil validatorUtil){
|
||||
public GenreService(GenreRepository genreRepository, UserService userService, ValidatorUtil validatorUtil){
|
||||
this.genreRepository = genreRepository;
|
||||
this.userService = userService;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Genre addGenre(String name) {
|
||||
final Genre genre = new Genre(name);
|
||||
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){
|
||||
genre.setUser(user);
|
||||
}
|
||||
}
|
||||
validatorUtil.validate(genre);
|
||||
return genreRepository.save(genre);
|
||||
}
|
||||
|
28
src/main/java/com/labwork01/app/user/controller/UserDto.java
Normal file
28
src/main/java/com/labwork01/app/user/controller/UserDto.java
Normal file
@ -0,0 +1,28 @@
|
||||
package com.labwork01.app.user.controller;
|
||||
|
||||
import com.labwork01.app.user.model.User;
|
||||
import com.labwork01.app.user.model.UserRole;
|
||||
|
||||
public class UserDto {
|
||||
private final long id;
|
||||
private final String login;
|
||||
private final UserRole role;
|
||||
|
||||
public UserDto(User user) {
|
||||
this.id = user.getId();
|
||||
this.login = user.getLogin();
|
||||
this.role = user.getRole();
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.labwork01.app.user.controller;
|
||||
|
||||
import com.labwork01.app.user.model.UserRole;
|
||||
import com.labwork01.app.user.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";
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.labwork01.app.user.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;
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.labwork01.app.user.controller;
|
||||
|
||||
import com.labwork01.app.user.model.User;
|
||||
import com.labwork01.app.user.service.UserService;
|
||||
import com.labwork01.app.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";
|
||||
}
|
||||
}
|
||||
}
|
74
src/main/java/com/labwork01/app/user/model/User.java
Normal file
74
src/main/java/com/labwork01/app/user/model/User.java
Normal file
@ -0,0 +1,74 @@
|
||||
package com.labwork01.app.user.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@Column(nullable = false, unique = true, length = 64)
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 64)
|
||||
private String login;
|
||||
@Column(nullable = false, length = 64)
|
||||
@NotBlank
|
||||
@Size(min = 6, max = 64)
|
||||
private String password;
|
||||
private UserRole role;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String login, String password) {
|
||||
this(login, password, UserRole.USER);
|
||||
}
|
||||
|
||||
public User(String login, String password, UserRole role) {
|
||||
this.login = login;
|
||||
this.password = password;
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
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 UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, login);
|
||||
}
|
||||
}
|
20
src/main/java/com/labwork01/app/user/model/UserRole.java
Normal file
20
src/main/java/com/labwork01/app/user/model/UserRole.java
Normal file
@ -0,0 +1,20 @@
|
||||
package com.labwork01.app.user.model;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public enum UserRole implements GrantedAuthority {
|
||||
ADMIN,
|
||||
USER;
|
||||
|
||||
private static final String PREFIX = "ROLE_";
|
||||
|
||||
@Override
|
||||
public String getAuthority() {
|
||||
return PREFIX + this.name();
|
||||
}
|
||||
|
||||
public static final class AsString {
|
||||
public static final String ADMIN = PREFIX + "ADMIN";
|
||||
public static final String USER = PREFIX + "USER";
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.labwork01.app.user.repository;
|
||||
|
||||
import com.labwork01.app.user.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
User findOneByLoginIgnoreCase(String login);
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package com.labwork01.app.user.service;
|
||||
|
||||
import com.labwork01.app.user.model.User;
|
||||
import com.labwork01.app.user.model.UserRole;
|
||||
import com.labwork01.app.user.repository.UserRepository;
|
||||
import com.labwork01.app.util.validation.ValidationException;
|
||||
import com.labwork01.app.util.validation.ValidatorUtil;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class UserService implements UserDetailsService {
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public UserService(UserRepository userRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
ValidatorUtil validatorUtil) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
final User user = new User(login, passwordEncoder.encode(password), role);
|
||||
validatorUtil.validate(user);
|
||||
if (!Objects.equals(password, passwordConfirm)) {
|
||||
throw new ValidationException("Passwords not equals");
|
||||
}
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
final User userEntity = findByLogin(username);
|
||||
if (userEntity == null) {
|
||||
throw new UsernameNotFoundException(username);
|
||||
}
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
|
||||
}
|
||||
}
|
@ -1,7 +1,11 @@
|
||||
package com.labwork01.app.util.validation;
|
||||
import java.util.Set;
|
||||
public class ValidationException extends RuntimeException{
|
||||
public ValidationException(Set<String> errors) {
|
||||
public <T> ValidationException(Set<String> errors) {
|
||||
super(String.join("\n", errors));
|
||||
}
|
||||
|
||||
public <T> ValidationException(String error) {
|
||||
super(error);
|
||||
}
|
||||
}
|
||||
|
@ -2,13 +2,14 @@
|
||||
<html lang="en"
|
||||
xmlns:th="http://www.thymeleaf.org"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6"
|
||||
layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div>
|
||||
<a class="btn btn-success button-fixed"
|
||||
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-success button-fixed"
|
||||
th:href="@{/authors/edit}">
|
||||
<i class="fa-solid fa-plus"></i> Добавить
|
||||
</a>
|
||||
@ -30,11 +31,11 @@
|
||||
<td th:text="${author.name} + ' ' + ${author.surname} + ' ' + ${author.patronymic}" style="width: 60%"></td>
|
||||
<td style="width: 10%">
|
||||
<div class="btn-group" role="group" aria-label="Basic example">
|
||||
<a class="btn btn-warning button-fixed button-sm"
|
||||
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-warning button-fixed button-sm"
|
||||
th:href="@{/authors/edit/{id}(id=${author.id})}">
|
||||
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
|
||||
</a>
|
||||
<button type="button" class="btn btn-danger button-fixed button-sm"
|
||||
<button sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" type="button" class="btn btn-danger button-fixed button-sm"
|
||||
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${author.id}').click()|">
|
||||
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
|
||||
</button>
|
||||
|
@ -2,6 +2,7 @@
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
xmlns:th="http://www.thymeleaf.org"
|
||||
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6"
|
||||
layout:decorate="~{default}">
|
||||
>
|
||||
<head>
|
||||
@ -13,7 +14,7 @@
|
||||
<div class="col-3 genres" style="background-color: rgb(211,211,211); min-height: 68vh">
|
||||
<div class="d-flex flex-row justify-content-between div-with-button">
|
||||
<h2>Список жанров</h2>
|
||||
<a class="btn btn-success button-fixed"
|
||||
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-success button-fixed"
|
||||
th:href="@{/books/edit}">
|
||||
<i class="fa fa-pencil" aria-hidden="true"></i> Добавить
|
||||
</a>
|
||||
@ -51,12 +52,14 @@
|
||||
</div>
|
||||
<div class="d-flex justify-content-end">
|
||||
<a
|
||||
sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')"
|
||||
role="button"
|
||||
class="text-end align-self-end"
|
||||
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${book.id}').click()|">
|
||||
Удалить
|
||||
</a>
|
||||
<a
|
||||
sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')"
|
||||
class="px-2 text-end align-self-end"
|
||||
th:href="@{/books/edit/{id}(id=${book.id})}"
|
||||
>
|
||||
|
@ -1,7 +1,8 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru"
|
||||
xmlns:th="http://www.thymeleaf.org"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<title>Онлайн-библиотека</title>
|
||||
@ -59,6 +60,10 @@
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/forum">Форум</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="nav-link" href="/users"
|
||||
th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<form class="w-100">
|
||||
@ -72,7 +77,9 @@
|
||||
</nav>
|
||||
</div>
|
||||
<span class="col text-end">
|
||||
<a class="nav-link" href="/login">Вход/регистрация</a>
|
||||
<a sec:authorize="isAuthenticated()" class="nav-link" href="/logout">
|
||||
Выход (<span th:text="${#authentication.name}"></span>)
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -2,13 +2,14 @@
|
||||
<html lang="en"
|
||||
xmlns:th="http://www.thymeleaf.org"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6"
|
||||
layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div>
|
||||
<a class="btn btn-success button-fixed"
|
||||
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-success button-fixed"
|
||||
th:href="@{/genres/edit}">
|
||||
<i class="fa-solid fa-plus"></i> Добавить
|
||||
</a>
|
||||
@ -30,11 +31,11 @@
|
||||
<td th:text="${genre.name}" style="width: 60%"></td>
|
||||
<td style="width: 10%">
|
||||
<div class="btn-group" role="group" aria-label="Basic example">
|
||||
<a class="btn btn-warning button-fixed button-sm"
|
||||
<a sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" class="btn btn-warning button-fixed button-sm"
|
||||
th:href="@{/genres/edit/{id}(id=${genre.id})}">
|
||||
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
|
||||
</a>
|
||||
<button type="button" class="btn btn-danger button-fixed button-sm"
|
||||
<button sec:authorize="isAuthenticated() and hasRole('ROLE_ADMIN')" type="button" class="btn btn-danger button-fixed button-sm"
|
||||
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${genre.id}').click()|">
|
||||
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
|
||||
</button>
|
||||
|
@ -8,25 +8,27 @@
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<form class="w-50 ms-2 needs-validation"novalidate>
|
||||
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
|
||||
Пользователь не найден или пароль указан не верно
|
||||
</div>
|
||||
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
|
||||
Выход успешно произведен
|
||||
</div>
|
||||
<div th:if="${param.created}" class="alert alert-success margin-bottom">
|
||||
Пользователь '<span th:text="${param.created}"></span>' успешно создан
|
||||
</div>
|
||||
<form th:action="@{/login}" method="post" class="w-50 ms-2">
|
||||
<h2 class="py-3">Вход</h2>
|
||||
<h4>Логин</h4>
|
||||
<input class="form-control my-2" type="email" required />
|
||||
<div class="invalid-feedback">
|
||||
Пожалуйста введите электронную почту вида: "..@.."
|
||||
</div>
|
||||
<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" type="password" required />
|
||||
<input class="form-control my-2" name="password" id="password" type="password" placeholder="Пароль" required="true" />
|
||||
<div>
|
||||
<button class="btn btn-primary m-2" type="submit">Войти</button>
|
||||
<a href="" style="margin-top: 1em; margin-left: 1em"
|
||||
>Зарегистрируйтесь, если нет аккаунта, здесь</a
|
||||
>
|
||||
<a href="/signup" style="margin-top: 1em; margin-left: 1em"
|
||||
>Зарегистрируйтесь, если нет аккаунта, здесь</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<th:block layout:fragment="scripts">
|
||||
<script src="js/formValid.js"></script>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
29
src/main/resources/templates/signup.html
Normal file
29
src/main/resources/templates/signup.html
Normal file
@ -0,0 +1,29 @@
|
||||
<!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" 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="mb-3">
|
||||
<button type="submit" class="btn btn-success button-fixed">Создать</button>
|
||||
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
38
src/main/resources/templates/users.html
Normal file
38
src/main/resources/templates/users.html
Normal file
@ -0,0 +1,38 @@
|
||||
<!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>
|
Loading…
Reference in New Issue
Block a user