diff --git a/build.gradle b/build.gradle index e1ad653..8fd4e4b 100644 --- a/build.gradle +++ b/build.gradle @@ -27,6 +27,9 @@ dependencies { implementation 'org.hibernate.validator:hibernate-validator' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5' + implementation 'org.springdoc:springdoc-openapi-ui:1.6.5' testImplementation 'org.springframework.boot:spring-boot-starter-test' diff --git a/data.mv.db b/data.mv.db index 0b87f4a..2c4a847 100644 Binary files a/data.mv.db and b/data.mv.db differ diff --git a/src/main/java/ru/ip/labs/labs/LabsApplication.java b/src/main/java/ru/ip/labs/labs/LabsApplication.java index b7e5532..ef8df06 100644 --- a/src/main/java/ru/ip/labs/labs/LabsApplication.java +++ b/src/main/java/ru/ip/labs/labs/LabsApplication.java @@ -5,4 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class LabsApplication { + public static void main(String[] args) { + SpringApplication.run(LabsApplication.class, args); + } } diff --git a/src/main/java/ru/ip/labs/labs/configuration/PasswordEncoderConfiguration.java b/src/main/java/ru/ip/labs/labs/configuration/PasswordEncoderConfiguration.java new file mode 100644 index 0000000..5aef121 --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/configuration/PasswordEncoderConfiguration.java @@ -0,0 +1,14 @@ +package ru.ip.labs.labs.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(); + } +} diff --git a/src/main/java/ru/ip/labs/labs/configuration/SecurityConfiguration.java b/src/main/java/ru/ip/labs/labs/configuration/SecurityConfiguration.java new file mode 100644 index 0000000..ec3ec4a --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/configuration/SecurityConfiguration.java @@ -0,0 +1,67 @@ +package ru.ip.labs.labs.configuration; + +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.ip.labs.labs.films.controller.UserSignupMvcController; +import ru.ip.labs.labs.films.models.UserRole; +import ru.ip.labs.labs.films.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("/js/**") + .antMatchers("/templates/**") + .antMatchers("/webjars/**"); + } +} \ No newline at end of file diff --git a/src/main/java/ru/ip/labs/labs/WebConfiguration.java b/src/main/java/ru/ip/labs/labs/configuration/WebConfiguration.java similarity index 92% rename from src/main/java/ru/ip/labs/labs/WebConfiguration.java rename to src/main/java/ru/ip/labs/labs/configuration/WebConfiguration.java index f01a266..56c9ee5 100644 --- a/src/main/java/ru/ip/labs/labs/WebConfiguration.java +++ b/src/main/java/ru/ip/labs/labs/configuration/WebConfiguration.java @@ -1,4 +1,4 @@ -package ru.ip.labs.labs; +package ru.ip.labs.labs.configuration; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; @@ -15,6 +15,7 @@ public class WebConfiguration implements WebMvcConfigurer { registry.addViewController("films"); registry.addViewController("contacts"); registry.addViewController("catalogs"); + registry.addViewController("login"); } @Override public void addCorsMappings(CorsRegistry registry) { diff --git a/src/main/java/ru/ip/labs/labs/films/controller/ActorController.java b/src/main/java/ru/ip/labs/labs/films/controller/ActorController.java index 20fbd2e..c7ea2c2 100644 --- a/src/main/java/ru/ip/labs/labs/films/controller/ActorController.java +++ b/src/main/java/ru/ip/labs/labs/films/controller/ActorController.java @@ -1,7 +1,7 @@ package ru.ip.labs.labs.films.controller; import org.springframework.web.bind.annotation.*; -import ru.ip.labs.labs.WebConfiguration; +import ru.ip.labs.labs.configuration.WebConfiguration; import ru.ip.labs.labs.films.dto.ActorDTO; import ru.ip.labs.labs.films.service.ActorService; diff --git a/src/main/java/ru/ip/labs/labs/films/controller/FilmController.java b/src/main/java/ru/ip/labs/labs/films/controller/FilmController.java index d847926..3c6c96a 100644 --- a/src/main/java/ru/ip/labs/labs/films/controller/FilmController.java +++ b/src/main/java/ru/ip/labs/labs/films/controller/FilmController.java @@ -1,14 +1,11 @@ package ru.ip.labs.labs.films.controller; import org.springframework.web.bind.annotation.*; -import ru.ip.labs.labs.WebConfiguration; +import ru.ip.labs.labs.configuration.WebConfiguration; import ru.ip.labs.labs.films.dto.FilmDTO; -import ru.ip.labs.labs.films.models.Film; -import ru.ip.labs.labs.films.models.Genre; import ru.ip.labs.labs.films.service.FilmsService; import javax.validation.Valid; -import java.util.Iterator; import java.util.List; @RestController diff --git a/src/main/java/ru/ip/labs/labs/films/controller/GenreController.java b/src/main/java/ru/ip/labs/labs/films/controller/GenreController.java index b8d9df8..52945fb 100644 --- a/src/main/java/ru/ip/labs/labs/films/controller/GenreController.java +++ b/src/main/java/ru/ip/labs/labs/films/controller/GenreController.java @@ -1,12 +1,8 @@ package ru.ip.labs.labs.films.controller; import org.springframework.web.bind.annotation.*; -import ru.ip.labs.labs.WebConfiguration; -import ru.ip.labs.labs.films.dto.FilmDTO; +import ru.ip.labs.labs.configuration.WebConfiguration; import ru.ip.labs.labs.films.dto.GenreDTO; -import ru.ip.labs.labs.films.models.Film; -import ru.ip.labs.labs.films.models.Genre; -import ru.ip.labs.labs.films.service.FilmsService; import ru.ip.labs.labs.films.service.GenreService; import javax.validation.Valid; diff --git a/src/main/java/ru/ip/labs/labs/films/controller/UserMvcController.java b/src/main/java/ru/ip/labs/labs/films/controller/UserMvcController.java new file mode 100644 index 0000000..e8dfc78 --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/controller/UserMvcController.java @@ -0,0 +1,42 @@ +package ru.ip.labs.labs.films.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.ip.labs.labs.films.dto.UserDto; +import ru.ip.labs.labs.films.models.UserRole; +import ru.ip.labs.labs.films.service.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 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/ip/labs/labs/films/controller/UserSignupMvcController.java b/src/main/java/ru/ip/labs/labs/films/controller/UserSignupMvcController.java new file mode 100644 index 0000000..bb842b5 --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/controller/UserSignupMvcController.java @@ -0,0 +1,51 @@ +package ru.ip.labs.labs.films.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.ip.labs.labs.films.models.User; +import ru.ip.labs.labs.films.models.UserSignupDto; +import ru.ip.labs.labs.films.service.UserService; +import ru.ip.labs.labs.films.util.validation.ValidationException; + +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/ip/labs/labs/films/dto/UserDto.java b/src/main/java/ru/ip/labs/labs/films/dto/UserDto.java new file mode 100644 index 0000000..7c20374 --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/dto/UserDto.java @@ -0,0 +1,28 @@ +package ru.ip.labs.labs.films.dto; + +import ru.ip.labs.labs.films.models.User; +import ru.ip.labs.labs.films.models.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/ip/labs/labs/films/models/User.java b/src/main/java/ru/ip/labs/labs/films/models/User.java new file mode 100644 index 0000000..b48b26a --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/models/User.java @@ -0,0 +1,73 @@ +package ru.ip.labs.labs.films.models; + +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); + } +} diff --git a/src/main/java/ru/ip/labs/labs/films/models/UserRole.java b/src/main/java/ru/ip/labs/labs/films/models/UserRole.java new file mode 100644 index 0000000..6aa4498 --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/models/UserRole.java @@ -0,0 +1,20 @@ +package ru.ip.labs.labs.films.models; + +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/ip/labs/labs/films/models/UserSignupDto.java b/src/main/java/ru/ip/labs/labs/films/models/UserSignupDto.java new file mode 100644 index 0000000..48623fe --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/models/UserSignupDto.java @@ -0,0 +1,40 @@ +package ru.ip.labs.labs.films.models; + +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/ip/labs/labs/films/repository/UserRepository.java b/src/main/java/ru/ip/labs/labs/films/repository/UserRepository.java new file mode 100644 index 0000000..9df007c --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/repository/UserRepository.java @@ -0,0 +1,8 @@ +package ru.ip.labs.labs.films.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.ip.labs.labs.films.models.User; + +public interface UserRepository extends JpaRepository { + User findOneByLoginIgnoreCase(String login); +} diff --git a/src/main/java/ru/ip/labs/labs/films/service/UserService.java b/src/main/java/ru/ip/labs/labs/films/service/UserService.java new file mode 100644 index 0000000..247031b --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/service/UserService.java @@ -0,0 +1,67 @@ +package ru.ip.labs.labs.films.service; + +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 ru.ip.labs.labs.films.models.User; +import ru.ip.labs.labs.films.models.UserRole; +import ru.ip.labs.labs.films.repository.UserRepository; +import ru.ip.labs.labs.films.util.validation.ValidationException; +import ru.ip.labs.labs.films.util.validation.ValidatorUtil; + +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 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/ip/labs/labs/films/util/error/AdviceController.java b/src/main/java/ru/ip/labs/labs/films/util/error/AdviceController.java new file mode 100644 index 0000000..5413939 --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/util/error/AdviceController.java @@ -0,0 +1,37 @@ +package ru.ip.labs.labs.films.util.error; + +import org.springframework.context.support.DefaultMessageSourceResolvable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestController; +import ru.ip.labs.labs.films.util.validation.ValidationException; + +import java.util.stream.Collectors; + +@ControllerAdvice(annotations = RestController.class) +public class AdviceController { + @ExceptionHandler({ + ValidationException.class + }) + public ResponseEntity handleException(Throwable e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleBindException(MethodArgumentNotValidException e) { + final ValidationException validationException = new ValidationException( + e.getBindingResult().getAllErrors().stream() + .map(DefaultMessageSourceResolvable::getDefaultMessage) + .collect(Collectors.toSet())); + return handleException(validationException); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleUnknownException(Throwable e) { + e.printStackTrace(); + return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/src/main/java/ru/ip/labs/labs/films/util/validation/ValidationException.java b/src/main/java/ru/ip/labs/labs/films/util/validation/ValidationException.java new file mode 100644 index 0000000..be0282f --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/util/validation/ValidationException.java @@ -0,0 +1,13 @@ +package ru.ip.labs.labs.films.util.validation; + +import java.util.Set; + +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/java/ru/ip/labs/labs/films/util/validation/ValidatorUtil.java b/src/main/java/ru/ip/labs/labs/films/util/validation/ValidatorUtil.java new file mode 100644 index 0000000..c7cd72a --- /dev/null +++ b/src/main/java/ru/ip/labs/labs/films/util/validation/ValidatorUtil.java @@ -0,0 +1,27 @@ +package ru.ip.labs.labs.films.util.validation; + +import org.springframework.stereotype.Component; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import java.util.Set; +import java.util.stream.Collectors; + +@Component +public class ValidatorUtil { + private final Validator validator; + + public ValidatorUtil() { + this.validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + public void validate(T object) { + final Set> errors = validator.validate(object); + if (!errors.isEmpty()) { + throw new ValidationException(errors.stream() + .map(ConstraintViolation::getMessage) + .collect(Collectors.toSet())); + } + } +} diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html index 1573168..5a18284 100644 --- a/src/main/resources/templates/default.html +++ b/src/main/resources/templates/default.html @@ -1,6 +1,7 @@ @@ -23,7 +24,7 @@ diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html new file mode 100644 index 0000000..019f575 --- /dev/null +++ b/src/main/resources/templates/login.html @@ -0,0 +1,30 @@ + + + +
+
+ Пользователь не найден или пароль указан не верно +
+
+ Выход успешно произведен +
+
+ Пользователь '' успешно создан +
+
+
+ +
+
+ +
+ + Регистрация +
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/signup.html b/src/main/resources/templates/signup.html new file mode 100644 index 0000000..8cd75f5 --- /dev/null +++ b/src/main/resources/templates/signup.html @@ -0,0 +1,28 @@ + + + +
+
+
+
+ +
+
+ +
+
+ +
+
+ + Назад +
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/users.html b/src/main/resources/templates/users.html new file mode 100644 index 0000000..7a21a02 --- /dev/null +++ b/src/main/resources/templates/users.html @@ -0,0 +1,37 @@ + + + +
+
+ + + + + + + + + + + + + + + + + +
#IDЛогинРоль
+
+ +
+ + \ No newline at end of file