Compare commits
9 Commits
lab4
...
lab6_react
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d943b9a6b | ||
|
|
89fce66638 | ||
|
|
299a62b364 | ||
|
|
8834071b09 | ||
|
|
69466dca35 | ||
|
|
c793d802ef | ||
|
|
e4c17f1642 | ||
|
|
c7b8f30077 | ||
|
|
efd20a1796 |
15
build.gradle
15
build.gradle
@@ -14,11 +14,24 @@ repositories {
|
||||
|
||||
dependencies {
|
||||
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 'com.h2database:h2:2.1.210'
|
||||
|
||||
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
|
||||
implementation 'org.hibernate.validator:hibernate-validator'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
|
||||
implementation 'com.auth0:java-jwt:4.4.0'
|
||||
|
||||
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
BIN
data.mv.db
BIN
data.mv.db
Binary file not shown.
@@ -1,6 +1,5 @@
|
||||
.banner-block {
|
||||
width: 90%;
|
||||
|
||||
}
|
||||
|
||||
.banner-card {
|
||||
|
||||
@@ -5,8 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class LabsApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LabsApplication.class, args);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LabsApplication.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
package ru.ip.labs.labs;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedMethods("*");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ru.ip.labs.labs.configuration;
|
||||
|
||||
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;
|
||||
import ru.ip.labs.labs.configuration.jwt.JwtFilter;
|
||||
|
||||
@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")));
|
||||
}
|
||||
}
|
||||
@@ -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 passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import ru.ip.labs.labs.configuration.jwt.JwtFilter;
|
||||
import ru.ip.labs.labs.films.controller.UserController;
|
||||
import ru.ip.labs.labs.films.models.UserRole;
|
||||
import ru.ip.labs.labs.films.service.UserService;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
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 {
|
||||
log.info("Creating security configuration");
|
||||
http.cors()
|
||||
.and()
|
||||
.csrf().disable()
|
||||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/", SPA_URL_MASK).permitAll()
|
||||
.antMatchers(HttpMethod.POST, UserController.URL_SIGNUP).permitAll()
|
||||
.antMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.anonymous();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
|
||||
builder.userDetailsService(userService);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(WebSecurity web) {
|
||||
web
|
||||
.ignoring()
|
||||
.antMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.antMatchers("/**/*.{js,html,css,png}")
|
||||
.antMatchers("/swagger-ui/index.html")
|
||||
.antMatchers("/webjars/**")
|
||||
.antMatchers("/swagger-resources/**")
|
||||
.antMatchers("/v3/api-docs/**");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.ip.labs.labs.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.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
public static final String REST_API = "/api";
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
WebMvcConfigurer.super.addViewControllers(registry);
|
||||
registry.addViewController("films");
|
||||
registry.addViewController("contacts");
|
||||
registry.addViewController("catalogs");
|
||||
registry.addViewController("login");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
|
||||
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedMethods("*");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/static/css/**").addResourceLocations("/static/css/");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package ru.ip.labs.labs.configuration.jwt;
|
||||
|
||||
public class JwtException extends RuntimeException {
|
||||
public JwtException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public JwtException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package ru.ip.labs.labs.configuration.jwt;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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 ru.ip.labs.labs.films.service.UserService;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package ru.ip.labs.labs.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;
|
||||
}
|
||||
}
|
||||
107
src/main/java/ru/ip/labs/labs/configuration/jwt/JwtProvider.java
Normal file
107
src/main/java/ru/ip/labs/labs/configuration/jwt/JwtProvider.java
Normal file
@@ -0,0 +1,107 @@
|
||||
package ru.ip.labs.labs.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package ru.ip.labs.labs.films.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ip.labs.labs.configuration.WebConfiguration;
|
||||
import ru.ip.labs.labs.films.dto.ActorDTO;
|
||||
import ru.ip.labs.labs.films.service.ActorService;
|
||||
|
||||
@@ -8,7 +9,7 @@ import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/actors")
|
||||
@RequestMapping(WebConfiguration.REST_API + "/actors")
|
||||
public class ActorController {
|
||||
private final ActorService actorService;
|
||||
|
||||
@@ -31,7 +32,7 @@ public class ActorController {
|
||||
return new ActorDTO(actorService.addActor(actor.getName(), actor.getSurname()));
|
||||
}
|
||||
|
||||
@PatchMapping("")
|
||||
@PatchMapping("/{id}")
|
||||
public ActorDTO updateActor(@PathVariable Long id, @RequestBody @Valid ActorDTO actor) {
|
||||
return new ActorDTO(actorService.updateActor(id, actor.getName(), actor.getSurname()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
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.*;
|
||||
import ru.ip.labs.labs.films.dto.ActorDTO;
|
||||
import ru.ip.labs.labs.films.service.ActorService;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/actor")
|
||||
public class ActorMvcController {
|
||||
private ActorService actorService;
|
||||
public ActorMvcController(ActorService actorService) {
|
||||
this.actorService = actorService;
|
||||
}
|
||||
@GetMapping
|
||||
public String getActors(Model model) {
|
||||
model.addAttribute("actors",
|
||||
actorService.findAllActors().stream()
|
||||
.map(ActorDTO::new).toList());
|
||||
|
||||
model.addAttribute("actorDTO", new ActorDTO());
|
||||
|
||||
return "actors-catalog";
|
||||
}
|
||||
|
||||
@PostMapping(value = {"", "/{id}"})
|
||||
public String saveActor(@PathVariable(required = false) Long id,
|
||||
@ModelAttribute @Valid ActorDTO actorDTO,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "actors-catalog";
|
||||
}
|
||||
if (id == null || id <= 0) {
|
||||
actorService.addActor(actorDTO.getName(), actorDTO.getSurname());
|
||||
} else {
|
||||
actorService.updateActor(id, actorDTO.getName(), actorDTO.getSurname());
|
||||
}
|
||||
return "redirect:/actor";
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deleteGenre(@PathVariable Long id) {
|
||||
actorService.deleteActor(id);
|
||||
return "redirect:/actor";
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,15 @@
|
||||
package ru.ip.labs.labs.films.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
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
|
||||
@RequestMapping("/films")
|
||||
@RequestMapping(WebConfiguration.REST_API + "/films")
|
||||
public class FilmController {
|
||||
private final FilmsService filmService;
|
||||
|
||||
@@ -31,17 +29,13 @@ public class FilmController {
|
||||
|
||||
@PostMapping("")
|
||||
public FilmDTO createFilm(@RequestBody @Valid FilmDTO film) {
|
||||
Film result = filmService.addFilm(film.getName());
|
||||
filmService.updateActors(result.getId(), film.getFullNames());
|
||||
return new FilmDTO(filmService.updateGenres(result.getId(), film.getGenre()));
|
||||
return new FilmDTO(filmService.addFilm(film.getName(), film.getGenre(), film.getFullNames()));
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}")
|
||||
public FilmDTO updateFilm(@PathVariable Long id,
|
||||
@RequestBody @Valid FilmDTO film) {
|
||||
Film result = filmService.updateFilm(id, film.getName());
|
||||
filmService.updateActors(result.getId(), film.getFullNames());
|
||||
return new FilmDTO(filmService.updateGenres(result.getId(), film.getGenre()));
|
||||
return new FilmDTO(filmService.updateFilm(id, film.getName(), film.getGenre(), film.getFullNames()));
|
||||
}
|
||||
|
||||
@PatchMapping("/add_genre/{id}")
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
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.*;
|
||||
import ru.ip.labs.labs.films.dto.FilmDTO;
|
||||
import ru.ip.labs.labs.films.models.Film;
|
||||
import ru.ip.labs.labs.films.service.ActorService;
|
||||
import ru.ip.labs.labs.films.service.FilmsService;
|
||||
import ru.ip.labs.labs.films.service.GenreService;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/film")
|
||||
public class FilmMvcController {
|
||||
private FilmsService filmService;
|
||||
private GenreService genreService;
|
||||
private ActorService actorService;
|
||||
public FilmMvcController(FilmsService filmService, GenreService genreService, ActorService actorService) {
|
||||
this.filmService = filmService;
|
||||
this.genreService = genreService;
|
||||
this.actorService = actorService;
|
||||
}
|
||||
@GetMapping
|
||||
public String getFilms(Model model) {
|
||||
model.addAttribute("films",
|
||||
filmService.findAllFilms().stream()
|
||||
.map(FilmDTO::new).toList());
|
||||
|
||||
model.addAttribute("filmDTO", new FilmDTO());
|
||||
model.addAttribute("allGenres",
|
||||
genreService.findAllGenres().stream()
|
||||
.map(g -> g.getName()).toList());
|
||||
model.addAttribute("allActors",
|
||||
actorService.findAllActors().stream()
|
||||
.map(a -> a.getName() + " " + a.getSurname()).toList());
|
||||
|
||||
return "films-catalog";
|
||||
}
|
||||
|
||||
@PostMapping(value = {"", "/{id}"})
|
||||
public String saveFilm(@PathVariable(required = false) Long id,
|
||||
@ModelAttribute @Valid FilmDTO filmDTO,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "films-catalog";
|
||||
}
|
||||
|
||||
if (id == null || id <= 0) {
|
||||
filmService.addFilm(filmDTO.getName(), filmDTO.getGenre(), filmDTO.getFullNames());
|
||||
} else {
|
||||
filmService.updateFilm(id, filmDTO.getName(), filmDTO.getGenre(), filmDTO.getFullNames());
|
||||
}
|
||||
return "redirect:/film";
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deleteGenre(@PathVariable Long id) {
|
||||
filmService.deleteFilm(id);
|
||||
return "redirect:/film";
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,15 @@
|
||||
package ru.ip.labs.labs.films.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
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;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/genres")
|
||||
@RequestMapping(WebConfiguration.REST_API + "/genres")
|
||||
public class GenreController {
|
||||
private final GenreService genreService;
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
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.*;
|
||||
import ru.ip.labs.labs.films.dto.GenreDTO;
|
||||
import ru.ip.labs.labs.films.service.GenreService;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/genre")
|
||||
public class GenreMvcController {
|
||||
private GenreService genreService;
|
||||
public GenreMvcController(GenreService genreService) {
|
||||
this.genreService = genreService;
|
||||
}
|
||||
@GetMapping
|
||||
public String getGenres(Model model) {
|
||||
model.addAttribute("genres",
|
||||
genreService.findAllGenres().stream()
|
||||
.map(GenreDTO::new).toList());
|
||||
|
||||
model.addAttribute("genreDTO", new GenreDTO());
|
||||
|
||||
return "genres-catalog";
|
||||
}
|
||||
|
||||
@PostMapping(value = {"", "/{id}"})
|
||||
public String saveGenre(@PathVariable(required = false) Long id,
|
||||
@ModelAttribute @Valid GenreDTO genreDTO,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "genres-catalog";
|
||||
}
|
||||
if (id == null || id <= 0) {
|
||||
genreService.addGenre(genreDTO.getName());
|
||||
} else {
|
||||
genreService.updateGenre(id, genreDTO.getName());
|
||||
}
|
||||
return "redirect:/genre";
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String deleteGenre(@PathVariable Long id) {
|
||||
genreService.deleteGenre(id);
|
||||
return "redirect:/genre";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package ru.ip.labs.labs.films.controller;
|
||||
|
||||
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 ru.ip.labs.labs.films.dto.UserDto;
|
||||
import ru.ip.labs.labs.films.dto.UserInfoDTO;
|
||||
import ru.ip.labs.labs.films.dto.UsersPageDTO;
|
||||
import ru.ip.labs.labs.films.models.User;
|
||||
import ru.ip.labs.labs.films.models.UserRole;
|
||||
import ru.ip.labs.labs.films.service.UserService;
|
||||
|
||||
import javax.validation.Valid;
|
||||
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;
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
|
||||
@PostMapping(URL_SIGNUP)
|
||||
public UserInfoDTO signup(@RequestBody @Valid UserDto userDto) {
|
||||
return userService.signupAndGetToken(userDto);
|
||||
}
|
||||
|
||||
@PostMapping(URL_LOGIN)
|
||||
public String login(@RequestBody @Valid UserDto userDto) {
|
||||
return userService.loginAndGetToken(userDto);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@ public class ActorDTO {
|
||||
private String name;
|
||||
private String surname;
|
||||
private String fullName;
|
||||
private byte[] photo;
|
||||
|
||||
private List<Film> films;
|
||||
|
||||
@@ -26,7 +25,6 @@ public class ActorDTO {
|
||||
this.id = actor.getId();
|
||||
this.name = actor.getName();
|
||||
this.surname = actor.getSurname();
|
||||
this.photo = actor.getPhoto();
|
||||
this.fullName = this.name + this.surname;
|
||||
}
|
||||
public ActorDTO(Long id, String name, String surname, byte[] photo) {
|
||||
@@ -34,16 +32,6 @@ public class ActorDTO {
|
||||
this.name = name;
|
||||
this.surname = surname;
|
||||
this.fullName = this.name + this.surname;
|
||||
this.photo = photo;
|
||||
}
|
||||
|
||||
public byte[] getPhoto() {
|
||||
return photo;
|
||||
}
|
||||
|
||||
public void setPhoto(String path) throws IOException {
|
||||
File f = new File(path);
|
||||
photo = Files.readAllBytes(f.toPath());
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
|
||||
@@ -52,10 +52,18 @@ public class FilmDTO {
|
||||
return fullNames;
|
||||
}
|
||||
|
||||
public void setFullNames(List<String> fullNames) {
|
||||
this.fullNames = fullNames;
|
||||
}
|
||||
|
||||
public List<String> getGenre() {
|
||||
return genre;
|
||||
}
|
||||
|
||||
public void setGenre(List<String> genre) {
|
||||
this.genre = genre;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String res = "\nFilm{" +
|
||||
|
||||
38
src/main/java/ru/ip/labs/labs/films/dto/UserDto.java
Normal file
38
src/main/java/ru/ip/labs/labs/films/dto/UserDto.java
Normal file
@@ -0,0 +1,38 @@
|
||||
package ru.ip.labs.labs.films.dto;
|
||||
|
||||
import ru.ip.labs.labs.films.models.User;
|
||||
import ru.ip.labs.labs.films.models.UserRole;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public class UserDto {
|
||||
@NotEmpty
|
||||
private String login;
|
||||
@NotEmpty
|
||||
private String password;
|
||||
private UserRole role;
|
||||
private String passwordConfirm;
|
||||
|
||||
public UserDto(User user) {
|
||||
this.login = user.getLogin();
|
||||
this.password = user.getPassword();
|
||||
this.role = user.getRole();
|
||||
}
|
||||
|
||||
public UserDto() {}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public String getPasswordConfirm() {
|
||||
return passwordConfirm;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
}
|
||||
27
src/main/java/ru/ip/labs/labs/films/dto/UserInfoDTO.java
Normal file
27
src/main/java/ru/ip/labs/labs/films/dto/UserInfoDTO.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package ru.ip.labs.labs.films.dto;
|
||||
|
||||
|
||||
import ru.ip.labs.labs.films.models.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;
|
||||
}
|
||||
}
|
||||
29
src/main/java/ru/ip/labs/labs/films/dto/UsersPageDTO.java
Normal file
29
src/main/java/ru/ip/labs/labs/films/dto/UsersPageDTO.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package ru.ip.labs.labs.films.dto;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
73
src/main/java/ru/ip/labs/labs/films/models/User.java
Normal file
73
src/main/java/ru/ip/labs/labs/films/models/User.java
Normal file
@@ -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);
|
||||
}
|
||||
}
|
||||
20
src/main/java/ru/ip/labs/labs/films/models/UserRole.java
Normal file
20
src/main/java/ru/ip/labs/labs/films/models/UserRole.java
Normal file
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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, Long> {
|
||||
User findOneByLoginIgnoreCase(String login);
|
||||
}
|
||||
@@ -36,6 +36,19 @@ public class FilmsService {
|
||||
return repo.save(film);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Film addFilm(String name, List<String> genres, List<String> fullNames) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Student name is null or empty");
|
||||
}
|
||||
|
||||
Film film = new Film(name);
|
||||
Film result = repo.save(film);
|
||||
|
||||
updateGenres(result.getId(), genres);
|
||||
return updateActors(film.getId(), fullNames);
|
||||
}
|
||||
|
||||
// фильмы по жанру
|
||||
// фильмы по актеру
|
||||
|
||||
@@ -149,6 +162,26 @@ public class FilmsService {
|
||||
return repo.save(currentFilm);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Film updateFilm(Long id, String name, List<String> genres, List<String> fullNames) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Film name is null or empty");
|
||||
}
|
||||
final Optional<Film> currentFilmOpt = repo.findById(id);
|
||||
|
||||
if(currentFilmOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Film currentFilm = currentFilmOpt.get();
|
||||
|
||||
currentFilm.setName(name);
|
||||
repo.save(currentFilm);
|
||||
|
||||
updateGenres(id, genres);
|
||||
return updateActors(id, fullNames);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Film deleteFilm(Long id) {
|
||||
final Optional<Film> currentFilm = repo.findById(id);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.ip.labs.labs.films.service;
|
||||
|
||||
public class UserExistsException extends RuntimeException {
|
||||
public UserExistsException(String login) {
|
||||
super(String.format("User '%s' already exists", login));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.ip.labs.labs.films.service;
|
||||
|
||||
public class UserNotFoundException extends RuntimeException {
|
||||
public UserNotFoundException(String login) {
|
||||
super(String.format("User not found '%s'", login));
|
||||
}
|
||||
}
|
||||
99
src/main/java/ru/ip/labs/labs/films/service/UserService.java
Normal file
99
src/main/java/ru/ip/labs/labs/films/service/UserService.java
Normal file
@@ -0,0 +1,99 @@
|
||||
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.configuration.jwt.JwtException;
|
||||
import ru.ip.labs.labs.configuration.jwt.JwtProvider;
|
||||
import ru.ip.labs.labs.films.dto.UserDto;
|
||||
import ru.ip.labs.labs.films.dto.UserInfoDTO;
|
||||
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;
|
||||
private final JwtProvider jwtProvider;
|
||||
|
||||
public UserService(UserRepository userRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
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 UserExistsException(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);
|
||||
}
|
||||
|
||||
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 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);
|
||||
if (userEntity == null) {
|
||||
throw new UsernameNotFoundException(username);
|
||||
}
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<Object> handleException(Throwable e) {
|
||||
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<Object> 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<Object> handleUnknownException(Throwable e) {
|
||||
e.printStackTrace();
|
||||
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package ru.ip.labs.labs.films.util.validation;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class ValidationException extends RuntimeException {
|
||||
public <T> ValidationException(Set<String> errors) {
|
||||
super(String.join("\n", errors));
|
||||
}
|
||||
|
||||
public <T> ValidationException(String error) {
|
||||
super(error);
|
||||
}
|
||||
}
|
||||
@@ -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 <T> void validate(T object) {
|
||||
final Set<ConstraintViolation<T>> errors = validator.validate(object);
|
||||
if (!errors.isEmpty()) {
|
||||
throw new ValidationException(errors.stream()
|
||||
.map(ConstraintViolation::getMessage)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,3 +9,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
|
||||
|
||||
23
src/main/resources/static/css/Banner.css
Normal file
23
src/main/resources/static/css/Banner.css
Normal file
@@ -0,0 +1,23 @@
|
||||
.banner-block {
|
||||
width: 90%;
|
||||
|
||||
}
|
||||
|
||||
.banner-card {
|
||||
width: 0;
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
opacity: 0.2;
|
||||
transition: 0.5s opacity ease;
|
||||
}
|
||||
|
||||
.banner-card.active {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
opacity: 1;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.banner-card.active img {
|
||||
height: 75vh;
|
||||
}
|
||||
5
src/main/resources/static/css/Contacts.css
Normal file
5
src/main/resources/static/css/Contacts.css
Normal file
@@ -0,0 +1,5 @@
|
||||
.map__frame {
|
||||
width: 90%;
|
||||
height: 500px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
21
src/main/resources/static/css/Header.css
Normal file
21
src/main/resources/static/css/Header.css
Normal file
@@ -0,0 +1,21 @@
|
||||
.navbar__logo {
|
||||
text-decoration: none;
|
||||
margin-left: 30px;
|
||||
}
|
||||
|
||||
.navbar__logo-text {
|
||||
font-size: 30px;
|
||||
text-decoration: none;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.navbar__logo-text_first {
|
||||
color: yellow;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: linear-gradient(135deg, #8bf292, #a5ebb1) fixed;
|
||||
min-height: 100vh;
|
||||
position: relative;
|
||||
}
|
||||
3
src/main/resources/static/css/Table.css
Normal file
3
src/main/resources/static/css/Table.css
Normal file
@@ -0,0 +1,3 @@
|
||||
.selected {
|
||||
background: #2150de;
|
||||
}
|
||||
BIN
src/main/resources/static/img/1.jpg
Normal file
BIN
src/main/resources/static/img/1.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
BIN
src/main/resources/static/img/2.jpg
Normal file
BIN
src/main/resources/static/img/2.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
BIN
src/main/resources/static/img/3.jpg
Normal file
BIN
src/main/resources/static/img/3.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
BIN
src/main/resources/static/img/4.jpg
Normal file
BIN
src/main/resources/static/img/4.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
BIN
src/main/resources/static/img/5.jpg
Normal file
BIN
src/main/resources/static/img/5.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
BIN
src/main/resources/static/img/play.png
Normal file
BIN
src/main/resources/static/img/play.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 54 KiB |
114
src/main/resources/templates/actors-catalog.html
Normal file
114
src/main/resources/templates/actors-catalog.html
Normal file
@@ -0,0 +1,114 @@
|
||||
<!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>
|
||||
<link rel="stylesheet" href="/css/Table.css">
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="m-3">
|
||||
<div class="btn-group">
|
||||
<button data-bs-target="#edit-modal" data-bs-toggle="modal" class="btn btn-success" id="addBtn">Добавить</button>
|
||||
<button data-bs-target="#edit-modal" data-bs-toggle="modal" class="btn btn-info" id="editBtn">Изменить</button>
|
||||
<button class="btn btn-danger" id="deleteBtn">Удалить</button>
|
||||
</div>
|
||||
<table class="table table-hover" id="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Имя</th>
|
||||
<th>Фамилия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="actor, iterator: ${actors}" th:attr="onclick=|selectRow(${iterator.index})|" th:id="${actor.id}">
|
||||
<!-- th:attr="onclick=|selectRow(1)"-->
|
||||
<td th:text="${iterator.index} + 1"></td>
|
||||
<td th:text="${actor.name}"></td>
|
||||
<td th:text="${actor.surname}"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="modal fade" tabIndex="-1" id="edit-modal"><!-- style={{ display: props.visible ? 'block' : 'none' }}-->
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Добавление</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть" onClick={props.closeHandler}></button>
|
||||
</div>
|
||||
<form class="modal-body" method="post" id="edit-form">
|
||||
<div class="mb-3">
|
||||
<label htmlFor="genre" class="form-label">Имя</label>
|
||||
<input type="text" th:field="${actorDTO.name}" name="name" class="form-control" required autoComplete="off">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label htmlFor="genre" class="form-label">Фамилия</label>
|
||||
<input type="text" th:field="${actorDTO.surname}" name="surname" class="form-control" required autoComplete="off">
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" id="closeBtn" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button class="btn btn-primary" id="submitBtn" type="submit">Добавить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<form method="post" style="display: none" id="delete-form">
|
||||
</form>
|
||||
</div>
|
||||
<th:block layout:fragment="scripts">
|
||||
|
||||
<script>
|
||||
let table = document.getElementById("table");
|
||||
let addBtn = document.getElementById("addBtn");
|
||||
let editBtn = document.getElementById("editBtn");
|
||||
let deleteBtn = document.getElementById("deleteBtn");
|
||||
let submitBtn = document.getElementById("submitBtn");
|
||||
let closeBtn = document.getElementById("closeBtn");
|
||||
let editForm = document.getElementById("edit-form");
|
||||
let deleteForm = document.getElementById("delete-form");
|
||||
|
||||
let selectRow = (index) => {
|
||||
table.children[1].children[index].classList.toggle("selected");
|
||||
}
|
||||
|
||||
addBtn.onclick = () => {
|
||||
editForm.action = "/actor";
|
||||
editForm.previousElementSibling.children[0].textContent = "Добавление";
|
||||
editForm.children[1].children[1].textContent = "Добавить";
|
||||
|
||||
editForm.name.value = "";
|
||||
editForm.surname.value = "";
|
||||
}
|
||||
|
||||
editBtn.onclick = () => {
|
||||
let elem = document.querySelector(".selected");
|
||||
if(elem == undefined) {
|
||||
setTimeout(() => {
|
||||
closeBtn.click();
|
||||
}, 500);
|
||||
return;
|
||||
}
|
||||
editForm.action = "/actor/" + elem.id;
|
||||
editForm.previousElementSibling.children[0].textContent = "Изменение";
|
||||
submitBtn.textContent = "Изменить";
|
||||
editForm.name.value = elem.children[1].textContent;
|
||||
editForm.surname.value = elem.children[2].textContent;
|
||||
|
||||
}
|
||||
|
||||
deleteBtn.onclick = () => {
|
||||
let elem = document.querySelector(".selected");
|
||||
if(elem == undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
deleteForm.action = "/actor/delete/" + elem.id;
|
||||
deleteForm.submit();
|
||||
}
|
||||
</script>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
||||
14
src/main/resources/templates/catalogs.html
Normal file
14
src/main/resources/templates/catalogs.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}">
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<a href="/film" class="btn btn-success mt-1">фильмы</a>
|
||||
<a href="/genre" class="btn btn-success mt-1">жанры</a>
|
||||
<a href="/actor" class="btn btn-success mt-1">актеры</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
14
src/main/resources/templates/contacts.html
Normal file
14
src/main/resources/templates/contacts.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}">
|
||||
<head>
|
||||
<link rel="stylesheet" href="/css/Contacts.css">
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<h2 class="text-white">Контакты</h2>
|
||||
<iframe class="map__frame" title="map" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d158855.07580070102!2d-0.2470504135400737!3d51.52953198005434!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47d8a00baf21de75%3A0x52963a5addd52a99!2z0JvQvtC90LTQvtC9LCDQktC10LvQuNC60L7QsdGA0LjRgtCw0L3QuNGP!5e0!3m2!1sru!2sru!4v1664443841067!5m2!1sru!2sru" loading="lazy"/>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
64
src/main/resources/templates/default.html
Normal file
64
src/main/resources/templates/default.html
Normal file
@@ -0,0 +1,64 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru"
|
||||
xmlns:th="http://www.thymeleaf.org"
|
||||
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<title>lumer</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<link rel="icon" href="/favicon.svg">
|
||||
<link rel="stylesheet" href="/css/Header.css">
|
||||
<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"/>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar navbar-dark navbar-expand-lg bg-success">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand" href="/">
|
||||
<span class="navbar__logo-text navbar__logo-text_first">L</span><span class="navbar__logo-text navbar__logo-text_second">umer</span>
|
||||
</a>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Переключатель навигации">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
|
||||
<div class="collapse navbar-collapse" id="navbarNav">
|
||||
<ul class="navbar-nav" th:with="activeLink=${#request.requestURI}" sec:authorize="isAuthenticated()">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link btn btn-success" aria-current="page" href="/"
|
||||
th:classappend="${#strings.equals(activeLink, '/')} ? 'active' : ''">Главная</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link btn btn-success" aria-current="page" href="/films"
|
||||
th:classappend="${#strings.equals(activeLink, '/films')} ? 'active' : ''">Фильмы</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link btn btn-success" aria-current="page" href="/contacts"
|
||||
th:classappend="${#strings.equals(activeLink, '/contacts')} ? 'active' : ''">Контакты</a>
|
||||
</li>
|
||||
<li>
|
||||
<a sec:authorize="hasRole('ROLE_ADMIN')" class="nav-link" href="/users"
|
||||
th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link btn btn-success" aria-current="page" href="/catalogs"
|
||||
th:classappend="${#strings.equals(activeLink, '/catalogs')} ? 'active' : ''">Каталог</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="nav-link" href="/logout">
|
||||
Выход (<span th:text="${#authentication.name}"></span>)
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="container-fluid">
|
||||
<div layout:fragment="content">
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<th:block layout:fragment="scripts">
|
||||
</th:block>
|
||||
</html>
|
||||
242
src/main/resources/templates/films-catalog.html
Normal file
242
src/main/resources/templates/films-catalog.html
Normal file
@@ -0,0 +1,242 @@
|
||||
<!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>
|
||||
<link rel="stylesheet" href="/css/Table.css">
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="m-3">
|
||||
<div class="btn-group">
|
||||
<button data-bs-target="#edit-modal" data-bs-toggle="modal" class="btn btn-success" id="addBtn">Добавить</button>
|
||||
<button data-bs-target="#edit-modal" data-bs-toggle="modal" class="btn btn-info" id="editBtn">Изменить</button>
|
||||
<button class="btn btn-danger" id="deleteBtn">Удалить</button>
|
||||
</div>
|
||||
<table class="table table-hover" id="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Название</th>
|
||||
<th>Жанры</th>
|
||||
<th>Актеры</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="film, iterator: ${films}" th:attr="onclick=|selectRow(${iterator.index})|" th:id="${film.id}">
|
||||
<!-- th:attr="onclick=|selectRow(1)"-->
|
||||
<td th:text="${iterator.index} + 1"></td>
|
||||
<td th:text="${film.name}"></td>
|
||||
<td th:text="${#strings.arrayJoin(film.genre ,', ')}"></td>
|
||||
<td th:text="${#strings.arrayJoin(film.fullNames ,', ')}"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="modal fade" tabIndex="-1" id="edit-modal"><!-- style={{ display: props.visible ? 'block' : 'none' }}-->
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Добавление</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть" onClick={props.closeHandler}></button>
|
||||
</div>
|
||||
<form class="modal-body" method="post" id="edit-form">
|
||||
<div class="mb-3">
|
||||
<label htmlFor="nameInput" class="form-label">Название</label>
|
||||
<input id="nameInput" type="text" th:field="${filmDTO.name}" name="name" class="form-control" required autoComplete="off">
|
||||
</div>
|
||||
<select name="selectedGenre" class="form-select">
|
||||
<option disabled value="">Укажите жанр</option>
|
||||
<option th:each="g : ${allGenres}"
|
||||
th:value="${g}"
|
||||
th:text="${g}"></option>
|
||||
</select>
|
||||
<div id="selectedGenres">
|
||||
</div>
|
||||
<br>
|
||||
<button type="button" class="btn btn-success" id="addGenre">Добавить жанр</button>
|
||||
|
||||
<select name="selectedActor" class="form-select">
|
||||
<option disabled value="">Укажите актера</option>
|
||||
<option th:each="a : ${allActors}"
|
||||
th:value="${a}"
|
||||
th:text="${a}"></option>
|
||||
</select>
|
||||
<div id="selectedActors">
|
||||
</div>
|
||||
<br>
|
||||
<button type="button" class="btn btn-success" id="addActor">Добавить актера</button>
|
||||
|
||||
<select name="genre" class="form-select" th:field="${filmDTO.genre}" multiple="multiple" hidden>
|
||||
<option th:each="g : ${allGenres}"
|
||||
th:value="${g}"
|
||||
th:text="${g}"></option>
|
||||
</select>
|
||||
<select name="fullNames" class="form-select" th:field="${filmDTO.fullNames}" multiple="multiple" hidden>
|
||||
<option th:each="a : ${allActors}"
|
||||
th:value="${a}"
|
||||
th:text="${a}"></option>
|
||||
</select>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" id="closeBtn" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button class="btn btn-primary" id="submitBtn" type="submit">Добавить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<form method="post" style="display: none" id="delete-form">
|
||||
</form>
|
||||
</div>
|
||||
<th:block layout:fragment="scripts">
|
||||
|
||||
<script>
|
||||
let table = document.getElementById("table");
|
||||
let addBtn = document.getElementById("addBtn");
|
||||
let editBtn = document.getElementById("editBtn");
|
||||
let submitBtn = document.getElementById("submitBtn");
|
||||
let closeBtn = document.getElementById("closeBtn");
|
||||
let addGenreBtn = document.getElementById("addGenre");
|
||||
let addActorBtn = document.getElementById("addActor");
|
||||
let editForm = document.getElementById("edit-form");
|
||||
let deleteForm = document.getElementById("delete-form");
|
||||
|
||||
let selectRow = (index) => {
|
||||
table.children[1].children[index].classList.toggle("selected");
|
||||
}
|
||||
|
||||
addBtn.onclick = (e) => {
|
||||
editForm.action = "/film";
|
||||
editForm.previousElementSibling.children[0].textContent = "Добавление";
|
||||
submitBtn.textContent = "Добавить";
|
||||
|
||||
editForm.name.value = "";
|
||||
|
||||
document.getElementById("selectedGenres").innerHTML = "";
|
||||
for(let opt of editForm.genre.options) {
|
||||
opt.selected = false;
|
||||
}
|
||||
|
||||
document.getElementById("selectedActors").innerHTML = "";
|
||||
for(let opt of editForm.fullNames.options) {
|
||||
opt.selected = false;
|
||||
}
|
||||
}
|
||||
|
||||
editBtn.onclick = (e) => {
|
||||
let elem = document.querySelector(".selected");
|
||||
if(elem == undefined) {
|
||||
setTimeout(() => {
|
||||
closeBtn.click();
|
||||
}, 500);
|
||||
return;
|
||||
}
|
||||
editForm.action = "/film/" + elem.id;
|
||||
editForm.previousElementSibling.children[0].textContent = "Изменение";
|
||||
submitBtn.textContent = "Изменить";
|
||||
editForm.name.value = elem.children[1].textContent;
|
||||
|
||||
let genresArr = elem.children[2].textContent.split(", ");
|
||||
document.getElementById("selectedGenres").innerHTML = "";
|
||||
for(let opt of editForm.genre.options) {
|
||||
if(genresArr.indexOf(opt.value) == -1) continue;
|
||||
let budge = document.createElement("div");
|
||||
budge.className = "badge bg-secondary m-1";
|
||||
budge.innerHTML = `
|
||||
<span>${opt.value}</span>
|
||||
<button type="button" class="btn-close bg-danger m-1"></button>
|
||||
`;
|
||||
|
||||
budge.children[1].onclick = () => {
|
||||
budge.remove();
|
||||
opt.selected = false;
|
||||
}
|
||||
|
||||
document.getElementById("selectedGenres").appendChild(budge);
|
||||
opt.selected = true;
|
||||
}
|
||||
|
||||
let actorsArr = elem.children[3].textContent.split(", ");
|
||||
document.getElementById("selectedActors").innerHTML = "";
|
||||
|
||||
for(let opt of editForm.fullNames.options) {
|
||||
if(actorsArr.indexOf(opt.value) == -1) continue;
|
||||
let budge = document.createElement("div");
|
||||
budge.className = "badge bg-secondary m-1";
|
||||
budge.innerHTML = `
|
||||
<span>${opt.value}</span>
|
||||
<button type="button" class="btn-close bg-danger m-1"></button>
|
||||
`;
|
||||
|
||||
budge.children[1].onclick = () => {
|
||||
budge.remove();
|
||||
opt.selected = false;
|
||||
}
|
||||
|
||||
document.getElementById("selectedActors").appendChild(budge);
|
||||
opt.selected = true;
|
||||
}
|
||||
}
|
||||
deleteBtn.onclick = () => {
|
||||
let elem = document.querySelector(".selected");
|
||||
if(elem == undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
deleteForm.action = "/film/delete/" + elem.id;
|
||||
deleteForm.submit();
|
||||
}
|
||||
|
||||
addGenreBtn.onclick = () => {
|
||||
let selectedIndex = editForm.selectedGenre.selectedIndex;
|
||||
let g = editForm.selectedGenre.options[selectedIndex].value;
|
||||
|
||||
for(let elem of editForm.genre.options) {
|
||||
if(g != elem.value) continue;
|
||||
if(elem.selected) return;
|
||||
elem.selected = true;
|
||||
|
||||
let budge = document.createElement("div");
|
||||
budge.className = "badge bg-secondary m-1";
|
||||
budge.innerHTML = `
|
||||
<span>${g}</span>
|
||||
<button type="button" class="btn-close bg-danger m-1"></button>
|
||||
`;
|
||||
|
||||
budge.children[1].onclick = () => {
|
||||
budge.remove();
|
||||
elem.selected = false;
|
||||
}
|
||||
|
||||
document.getElementById("selectedGenres").appendChild(budge);
|
||||
}
|
||||
}
|
||||
|
||||
addActorBtn.onclick = () => {
|
||||
let selectedIndex = editForm.selectedActor.selectedIndex;
|
||||
let a = editForm.selectedActor.options[selectedIndex].value;
|
||||
|
||||
for(let elem of editForm.fullNames.options) {
|
||||
if(a != elem.value) continue;
|
||||
if(elem.selected) return;
|
||||
elem.selected = true;
|
||||
|
||||
let budge = document.createElement("div");
|
||||
budge.className = "badge bg-secondary m-1";
|
||||
budge.innerHTML = `
|
||||
<span>${a}</span>
|
||||
<button type="button" class="btn-close bg-danger m-1"></button>
|
||||
`;
|
||||
|
||||
budge.children[1].onclick = () => {
|
||||
budge.remove();
|
||||
elem.selected = false;
|
||||
}
|
||||
|
||||
document.getElementById("selectedActors").appendChild(budge);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
||||
61
src/main/resources/templates/films.html
Normal file
61
src/main/resources/templates/films.html
Normal file
@@ -0,0 +1,61 @@
|
||||
<!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>
|
||||
<link rel="stylesheet" href="/css/Banner.css">
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<section class="categories">
|
||||
<h2 class="text-white">Категории</h2>
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-success">Комедии</button>
|
||||
<button class="btn btn-success">Драмы</button>
|
||||
<button class="btn btn-success">Трилер</button>
|
||||
</div>
|
||||
</section>
|
||||
<section class="banner">
|
||||
<h2 class="text-white">Все фильмы</h2>
|
||||
<div class="banner-block" id="banner">
|
||||
<div class="banner-card active">
|
||||
<a href="/film">
|
||||
<img src="/img/1.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="banner-card">
|
||||
<a href="/film">
|
||||
<img src="/img/2.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="banner-card">
|
||||
<a href="/film">
|
||||
<img src="/img/3.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="banner-card">
|
||||
<a href="/film">
|
||||
<img src="/img/4.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="banner-card">
|
||||
<a href="/film">
|
||||
<img src="/img/5.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<th:block layout:fragment="scripts">
|
||||
<script>
|
||||
let active = 0;
|
||||
let banner = document.getElementById("banner")
|
||||
setInterval(() => {
|
||||
active += active == 4 ? -4 : 1;
|
||||
document.querySelector(".banner-card.active").classList.remove("active");
|
||||
banner.children[active].classList.add("active");
|
||||
}, 3000);
|
||||
</script>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
||||
102
src/main/resources/templates/genres-catalog.html
Normal file
102
src/main/resources/templates/genres-catalog.html
Normal file
@@ -0,0 +1,102 @@
|
||||
<!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>
|
||||
<link rel="stylesheet" href="/css/Table.css">
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<div class="m-3">
|
||||
<div class="btn-group">
|
||||
<button data-bs-target="#edit-modal" data-bs-toggle="modal" class="btn btn-success" id="addBtn">Добавить</button>
|
||||
<button data-bs-target="#edit-modal" data-bs-toggle="modal" class="btn btn-info" id="editBtn">Изменить</button>
|
||||
<button class="btn btn-danger" id="deleteBtn">Удалить</button>
|
||||
</div>
|
||||
<table class="table table-hover" id="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Жанр</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="genre, iterator: ${genres}" th:attr="onclick=|selectRow(${iterator.index})|" th:id="${genre.id}">
|
||||
<!-- th:attr="onclick=|selectRow(1)"-->
|
||||
<td th:text="${iterator.index} + 1"></td>
|
||||
<td th:text="${genre.name}"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="modal fade" tabIndex="-1" id="edit-modal"><!-- style={{ display: props.visible ? 'block' : 'none' }}-->
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Добавление</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть" onClick={props.closeHandler}></button>
|
||||
</div>
|
||||
<form class="modal-body" method="post" id="edit-form">
|
||||
<div class="mb-3">
|
||||
<label htmlFor="genre" class="form-label">Название</label>
|
||||
<input type="text" th:field="${genreDTO.name}" name="name" class="form-control" required autoComplete="off">
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" id="closeBtn" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button class="btn btn-primary" id="submitBtn" type="submit">Добавить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<form method="post" style="display: none" id="delete-form">
|
||||
</form>
|
||||
</div>
|
||||
<th:block layout:fragment="scripts">
|
||||
|
||||
<script>
|
||||
let table = document.getElementById("table");
|
||||
let addBtn = document.getElementById("addBtn");
|
||||
let editBtn = document.getElementById("editBtn");
|
||||
let submitBtn = document.getElementById("submitBtn");
|
||||
let closeBtn = document.getElementById("closeBtn");
|
||||
let editForm = document.getElementById("edit-form");
|
||||
let deleteForm = document.getElementById("delete-form");
|
||||
|
||||
let selectRow = (index) => {
|
||||
table.children[1].children[index].classList.toggle("selected");
|
||||
}
|
||||
|
||||
addBtn.onclick = (e) => {
|
||||
editForm.action = "/genre";
|
||||
editForm.previousElementSibling.children[0].textContent = "Добавление";
|
||||
editForm.children[1].children[1].textContent = "Добавить";
|
||||
editForm.name.value = "";
|
||||
}
|
||||
|
||||
editBtn.onclick = (e) => {
|
||||
let elem = document.querySelector(".selected");
|
||||
if(elem == undefined) {
|
||||
setTimeout(() => {
|
||||
closeBtn.click();
|
||||
}, 500);
|
||||
return;
|
||||
}
|
||||
editForm.action = "/genre/" + elem.id;
|
||||
editForm.previousElementSibling.children[0].textContent = "Изменение";
|
||||
submitBtn.textContent = "Изменить";
|
||||
editForm.name.value = elem.children[1].textContent;
|
||||
}
|
||||
deleteBtn.onclick = () => {
|
||||
let elem = document.querySelector(".selected");
|
||||
if(elem == undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
deleteForm.action = "/genre/delete/" + elem.id;
|
||||
deleteForm.submit();
|
||||
}
|
||||
</script>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
||||
51
src/main/resources/templates/index.html
Normal file
51
src/main/resources/templates/index.html
Normal file
@@ -0,0 +1,51 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/html">
|
||||
<head>
|
||||
<link rel="stylesheet" href="/css/Banner.css">
|
||||
</head>
|
||||
<body>
|
||||
<div layout:fragment="content">
|
||||
<h2 class="text-white">Популярные</h2>
|
||||
<div class="banner-block" id="banner">
|
||||
<div class="banner-card active">
|
||||
<a href="/film">
|
||||
<img src="/img/1.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="banner-card">
|
||||
<a href="/film">
|
||||
<img src="/img/2.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="banner-card">
|
||||
<a href="/film">
|
||||
<img src="/img/3.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="banner-card">
|
||||
<a href="/film">
|
||||
<img src="/img/4.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="banner-card">
|
||||
<a href="/film">
|
||||
<img src="/img/5.jpg"/>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<th:block layout:fragment="scripts">
|
||||
<script>
|
||||
let active = 0;
|
||||
let banner = document.getElementById("banner")
|
||||
setInterval(() => {
|
||||
active += active == 4 ? -4 : 1;
|
||||
document.querySelector(".banner-card.active").classList.remove("active");
|
||||
banner.children[active].classList.add("active");
|
||||
}, 3000);
|
||||
</script>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
||||
30
src/main/resources/templates/login.html
Normal file
30
src/main/resources/templates/login.html
Normal file
@@ -0,0 +1,30 @@
|
||||
<!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">
|
||||
<body>
|
||||
<div class="container" layout:fragment="content">
|
||||
<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="container-padding">
|
||||
<div class="mb-3">
|
||||
<input type="text" name="username" id="username" class="form-control"
|
||||
placeholder="Логин" required="true" autofocus="true"/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<input type="password" name="password" id="password" class="form-control"
|
||||
placeholder="Пароль" required="true"/>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success button-fixed">Войти</button>
|
||||
<a class="btn btn-primary button-fixed" href="/signup">Регистрация</a>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
28
src/main/resources/templates/signup.html
Normal file
28
src/main/resources/templates/signup.html
Normal file
@@ -0,0 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
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>
|
||||
37
src/main/resources/templates/users.html
Normal file
37
src/main/resources/templates/users.html
Normal file
@@ -0,0 +1,37 @@
|
||||
<!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">
|
||||
<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>
|
||||
Reference in New Issue
Block a user