diff --git a/build.gradle b/build.gradle index fe4e924..a721612 100644 --- a/build.gradle +++ b/build.gradle @@ -24,6 +24,10 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'com.h2database:h2:2.1.210' + + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5' + implementation 'org.hibernate.validator:hibernate-validator' implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5' diff --git a/data.mv.db b/data.mv.db index 9b852fc..52eb686 100644 Binary files a/data.mv.db and b/data.mv.db differ diff --git a/src/main/java/ru/ulstu/is/lab1/DataBase/Repository/IUserRepository.java b/src/main/java/ru/ulstu/is/lab1/DataBase/Repository/IUserRepository.java new file mode 100644 index 0000000..d9c9503 --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/DataBase/Repository/IUserRepository.java @@ -0,0 +1,8 @@ +package ru.ulstu.is.lab1.DataBase.Repository; + +import ru.ulstu.is.lab1.DataBase.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface IUserRepository extends JpaRepository { + User findOneByLoginIgnoreCase(String login); +} diff --git a/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserDTO.java b/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserDTO.java new file mode 100644 index 0000000..f380f52 --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserDTO.java @@ -0,0 +1,24 @@ +package ru.ulstu.is.lab1.DataBase.controller; + +import ru.ulstu.is.lab1.DataBase.model.User; +import ru.ulstu.is.lab1.DataBase.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; + } +} diff --git a/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserMvcController.java b/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserMvcController.java new file mode 100644 index 0000000..12418a4 --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserMvcController.java @@ -0,0 +1,39 @@ +package ru.ulstu.is.lab1.DataBase.controller; + +import ru.ulstu.is.lab1.DataBase.model.UserRole; +import ru.ulstu.is.lab1.DataBase.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 users = userService.findAllPages(page, size) + .map(UserDTO::new); + model.addAttribute("users", users); + final int totalPages = users.getTotalPages(); + final List pageNumbers = IntStream.rangeClosed(1, totalPages) + .boxed() + .toList(); + model.addAttribute("pages", pageNumbers); + model.addAttribute("totalPages", totalPages); + return "users"; + } +} diff --git a/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserSignupDTO.java b/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserSignupDTO.java new file mode 100644 index 0000000..0c449fc --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserSignupDTO.java @@ -0,0 +1,34 @@ +package ru.ulstu.is.lab1.DataBase.controller; + +import javax.validation.constraints.NotBlank; +import javax.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; + } +} diff --git a/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserSignupMvcController.java b/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserSignupMvcController.java new file mode 100644 index 0000000..16d30e8 --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/DataBase/controller/UserSignupMvcController.java @@ -0,0 +1,46 @@ +package ru.ulstu.is.lab1.DataBase.controller; + +import ru.ulstu.is.lab1.DataBase.model.User; +import ru.ulstu.is.lab1.DataBase.service.UserService; +import ru.ulstu.is.lab1.util.validation.ValidationException; +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 javax.validation.Valid; + +@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"; + } + } +} diff --git a/src/main/java/ru/ulstu/is/lab1/DataBase/model/User.java b/src/main/java/ru/ulstu/is/lab1/DataBase/model/User.java new file mode 100644 index 0000000..5408a8c --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/DataBase/model/User.java @@ -0,0 +1,83 @@ +package ru.ulstu.is.lab1.DataBase.model; + +import javax.persistence.*; +import javax.validation.constraints.NotBlank; +import javax.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); + } + @Override + public String toString() { + return "User{" + + "id=" + id + + ", login='" + login + '\'' + + ", password='" + password + '\'' + + ", role='" + role + '\'' + + '}'; + } +} diff --git a/src/main/java/ru/ulstu/is/lab1/DataBase/model/UserRole.java b/src/main/java/ru/ulstu/is/lab1/DataBase/model/UserRole.java new file mode 100644 index 0000000..8788472 --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/DataBase/model/UserRole.java @@ -0,0 +1,17 @@ +package ru.ulstu.is.lab1.DataBase.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"; + } +} diff --git a/src/main/java/ru/ulstu/is/lab1/DataBase/service/UserService.java b/src/main/java/ru/ulstu/is/lab1/DataBase/service/UserService.java new file mode 100644 index 0000000..f445643 --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/DataBase/service/UserService.java @@ -0,0 +1,61 @@ +package ru.ulstu.is.lab1.DataBase.service; + +import ru.ulstu.is.lab1.DataBase.model.User; +import ru.ulstu.is.lab1.DataBase.model.UserRole; +import ru.ulstu.is.lab1.DataBase.Repository.IUserRepository; +import ru.ulstu.is.lab1.util.validation.ValidationException; +import ru.ulstu.is.lab1.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 IUserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final ValidatorUtil validatorUtil; + public UserService(IUserRepository userRepository, + PasswordEncoder passwordEncoder, + ValidatorUtil validatorUtil) { + this.userRepository = userRepository; + this.passwordEncoder = passwordEncoder; + this.validatorUtil = validatorUtil; + } + public Page 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())); + } +} diff --git a/src/main/java/ru/ulstu/is/lab1/PasswordEncoderConfiguration.java b/src/main/java/ru/ulstu/is/lab1/PasswordEncoderConfiguration.java new file mode 100644 index 0000000..3e62ac6 --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/PasswordEncoderConfiguration.java @@ -0,0 +1,14 @@ +package ru.ulstu.is.lab1; + +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(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/is/lab1/SecurityConfiguration.java b/src/main/java/ru/ulstu/is/lab1/SecurityConfiguration.java new file mode 100644 index 0000000..59137bc --- /dev/null +++ b/src/main/java/ru/ulstu/is/lab1/SecurityConfiguration.java @@ -0,0 +1,68 @@ +package ru.ulstu.is.lab1; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +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.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import ru.ulstu.is.lab1.DataBase.controller.UserSignupMvcController; +import ru.ulstu.is.lab1.DataBase.model.UserRole; +import ru.ulstu.is.lab1.DataBase.service.UserService; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(securedEnabled = true) +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + 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); + } + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.headers().frameOptions().sameOrigin().and() + .cors().and() + .csrf().disable() + .authorizeRequests() + .antMatchers(UserSignupMvcController.SIGNUP_URL).permitAll() + .antMatchers(HttpMethod.GET, LOGIN_URL).permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage(LOGIN_URL).permitAll() + .and() + .logout().permitAll(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userService); + } + + @Override + public void configure(WebSecurity web) { + web.ignoring() + .antMatchers("/css/**") + .antMatchers("/images/**") + .antMatchers("/js/**") + .antMatchers("/templates/**") + .antMatchers("/webjars/**"); + } +} diff --git a/src/main/java/ru/ulstu/is/lab1/WebConfiguration.java b/src/main/java/ru/ulstu/is/lab1/WebConfiguration.java index 4f079e4..29f56e7 100644 --- a/src/main/java/ru/ulstu/is/lab1/WebConfiguration.java +++ b/src/main/java/ru/ulstu/is/lab1/WebConfiguration.java @@ -11,7 +11,7 @@ public class WebConfiguration implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { WebMvcConfigurer.super.addViewControllers(registry); - registry.addViewController("rest-test"); + registry.addViewController("login"); } @Override public void addCorsMappings(CorsRegistry registry){ diff --git a/src/main/java/ru/ulstu/is/lab1/util/validation/ValidationException.java b/src/main/java/ru/ulstu/is/lab1/util/validation/ValidationException.java index fe4527b..34b4f74 100644 --- a/src/main/java/ru/ulstu/is/lab1/util/validation/ValidationException.java +++ b/src/main/java/ru/ulstu/is/lab1/util/validation/ValidationException.java @@ -6,4 +6,6 @@ public class ValidationException extends RuntimeException{ public ValidationException(Set errors) { super(String.join("\n", errors)); } + + public ValidationException(String error) { super(error); } } diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html index 29bdbb5..05f268e 100644 --- a/src/main/resources/templates/default.html +++ b/src/main/resources/templates/default.html @@ -13,7 +13,7 @@
-