накидал всего подряд потом разберусь

This commit is contained in:
Николай 2023-05-02 18:42:54 +04:00
parent 8d3470086b
commit b3f98c6325
24 changed files with 917 additions and 37 deletions

View File

@ -21,6 +21,9 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-devtools' implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.webjars:bootstrap:5.1.3' implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0' implementation 'org.webjars:jquery:3.6.0'

Binary file not shown.

View File

@ -0,0 +1,28 @@
package com.LabWork.app.MangaStore.configuration;
import com.LabWork.app.MangaStore.configuration.jwt.JwtFilter;
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;
@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")));
}
}

View File

@ -0,0 +1,14 @@
package com.LabWork.app.MangaStore.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();
}
}

View File

@ -0,0 +1,91 @@
package com.LabWork.app.MangaStore.configuration;
import com.LabWork.app.MangaStore.configuration.jwt.JwtFilter;
import com.LabWork.app.MangaStore.controller.UserController;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
securedEnabled = true
)
public class SecurityConfiguration {
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.addUser(admin, "admin@gmail.com", admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers("/", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_SING_UP).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_WHO_AM_I).permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
return http.build();
}
@Bean
public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http
.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userService);
return authenticationManagerBuilder.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers(HttpMethod.OPTIONS, "/**")
.requestMatchers("/*.js")
.requestMatchers("/*.html")
.requestMatchers("/*.css")
.requestMatchers("/assets/**")
.requestMatchers("/favicon.ico")
.requestMatchers("/.js", "/.css")
.requestMatchers("/swagger-ui/index.html")
.requestMatchers("/webjars/**")
.requestMatchers("/swagger-resources/**")
.requestMatchers("/v3/api-docs/**")
.requestMatchers("/h2-console");
}
}

View File

@ -0,0 +1,30 @@
package com.LabWork.app.MangaStore.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.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,11 @@
package com.LabWork.app.MangaStore.configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,72 @@
package com.LabWork.app.MangaStore.configuration.jwt;
import com.LabWork.app.MangaStore.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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 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);
}
}

View File

@ -0,0 +1,27 @@
package com.LabWork.app.MangaStore.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;
}
}

View File

@ -0,0 +1,107 @@
package com.LabWork.app.MangaStore.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();
}
}
}

View File

@ -1,14 +1,13 @@
package com.LabWork.app.MangaStore.controller.Creator; package com.LabWork.app.MangaStore.controller;
import com.LabWork.app.MangaStore.model.Dto.CreatorMangaDto; import com.LabWork.app.MangaStore.model.Dto.CreatorMangaDto;
import com.LabWork.app.MangaStore.service.CreatorService; import com.LabWork.app.MangaStore.service.CreatorService;
import com.LabWork.app.WebConfiguration;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import com.LabWork.app.MangaStore.configuration.OpenAPI30Configuration;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping(WebConfiguration.REST_API + "/creator") @RequestMapping(OpenAPI30Configuration.API_PREFIX + "/creator")
public class CreatorController { public class CreatorController {
private final CreatorService creatorService; private final CreatorService creatorService;

View File

@ -1,18 +1,18 @@
package com.LabWork.app.MangaStore.controller.Manga; package com.LabWork.app.MangaStore.controller;
import com.LabWork.app.MangaStore.model.Dto.MangaReaderDto; import com.LabWork.app.MangaStore.model.Dto.MangaReaderDto;
import com.LabWork.app.MangaStore.model.Dto.ReaderMangaDto; import com.LabWork.app.MangaStore.model.Dto.ReaderMangaDto;
import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto; import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto;
import com.LabWork.app.MangaStore.service.MangaService; import com.LabWork.app.MangaStore.service.MangaService;
import com.LabWork.app.WebConfiguration; import com.LabWork.app.MangaStore.configuration.OpenAPI30Configuration;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping(WebConfiguration.REST_API + "/manga") @RequestMapping(OpenAPI30Configuration.API_PREFIX + "/manga")
public class MangaController { public class MangaController {
private final MangaService mangaService; private final MangaService mangaService;

View File

@ -0,0 +1,19 @@
package com.LabWork.app.MangaStore.controller;
public class Pair<F, S> {
private final F first;
private final S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
public F getFirst() {
return first;
}
public S getSecond() {
return second;
}
}

View File

@ -1,16 +1,16 @@
package com.LabWork.app.MangaStore.controller.Reader; package com.LabWork.app.MangaStore.controller;
import com.LabWork.app.MangaStore.configuration.OpenAPI30Configuration;
import com.LabWork.app.MangaStore.model.Dto.ReaderMangaDto; import com.LabWork.app.MangaStore.model.Dto.ReaderMangaDto;
import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto; import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto;
import com.LabWork.app.MangaStore.service.ReaderService; import com.LabWork.app.MangaStore.service.ReaderService;
import com.LabWork.app.WebConfiguration;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping(WebConfiguration.REST_API + "/reader") @RequestMapping(OpenAPI30Configuration.API_PREFIX + "/reader")
public class ReaderController { public class ReaderController {
private final ReaderService readerService; private final ReaderService readerService;

View File

@ -0,0 +1,89 @@
package com.LabWork.app.MangaStore.controller;
import com.LabWork.app.MangaStore.configuration.OpenAPI30Configuration;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.model.Dto.UserDto;
import com.LabWork.app.MangaStore.model.Dto.UserSignupDto;
import com.LabWork.app.MangaStore.service.UserService;
import com.LabWork.app.MangaStore.util.validation.ValidationException;
import jakarta.validation.Valid;
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 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_SING_UP = "/sing_up";
public static final String URL_WHO_AM_I = "/who_am_i";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDto userDto) {
return userService.loginAndGetToken(userDto);
}
@PostMapping(URL_SING_UP)
public String singUp(@RequestBody @Valid UserSignupDto userSignupDto) {
try {
final User user = userService.addUser(userSignupDto.getLogin(), userSignupDto.getEmail(),
userSignupDto.getPassword(), userSignupDto.getPasswordConfirm(), UserRole.USER);
return "created " + user.getLogin();
} catch (ValidationException e) {
return e.getMessage();
}
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/user")
public UserDto getUser(@RequestParam("login") String login) {
User user = userService.findByLogin(login);
return new UserDto(user);
}
@PostMapping(OpenAPI30Configuration.API_PREFIX + "/user")
public String updateUser(@RequestBody @Valid UserDto userDto) {
try {
userService.updateUser(userDto);
return "Profile updated";
} catch (ValidationException e) {
return e.getMessage();
}
}
@DeleteMapping(OpenAPI30Configuration.API_PREFIX + "/user/{id}")
@Secured({UserRole.AsString.USER})
public UserDto removeUser(@PathVariable Long id) {
User user = userService.deleteUser(id);
return new UserDto(user);
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/users")
@Secured({UserRole.AsString.ADMIN})
public Pair<Page<UserDto>, List<Integer>> 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 Pair<>(users, pageNumbers);
}
@GetMapping(URL_WHO_AM_I)
public String whoAmI(@RequestParam("token") String token) {
UserDetails userDetails = userService.loadUserByToken(token);
User user = userService.findByLogin(userDetails.getUsername());
return user.getRole().toString();
}
}

View File

@ -0,0 +1,120 @@
package com.LabWork.app.MangaStore.model.Default;
import com.LabWork.app.MangaStore.model.Dto.UserDto;
import com.LabWork.app.MangaStore.model.Dto.UserSignupDto;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "Login can't be null or empty")
@Size(min = 3, max = 64, message = "Incorrect login length")
private String login;
@NotBlank(message = "Email can't be null or empty")
@Size(min = 3, max = 64, message = "Incorrect login length")
private String email;
@NotBlank(message = "Password can't be null or empty")
@Size(min = 3, max = 64, message = "Incorrect password length")
private String password;
private UserRole role;
public User() {
}
public User(String login, String email, String password, UserRole role) {
this.login = login;
this.email = email;
this.password = password;
this.role = role;
}
public User(UserDto userDto) {
this.login = userDto.getLogin();
this.email = userDto.getEmail();
this.password = userDto.getPassword();
this.role = userDto.getRole();
}
public User(UserSignupDto userSignupDto) {
this.login = userSignupDto.getLogin();
this.email = userSignupDto.getEmail();
this.password = userSignupDto.getPassword();
this.role = UserRole.USER;
}
// Properties
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
// ![Properties]
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User marketUser = (User) o;
return Objects.equals(id, marketUser.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + login + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
", role='" + role + '\'' +
'}';
}
}

View File

@ -0,0 +1,20 @@
package com.LabWork.app.MangaStore.model.Default;
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";
}
}

View File

@ -0,0 +1,66 @@
package com.LabWork.app.MangaStore.model.Dto;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.model.Default.UserRole;
public class UserDto {
private Long id;
private String login;
private String email;
private String password;
private UserRole role;
private Long cartId;
public UserDto() {
}
public UserDto(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.email = user.getEmail();
this.password = user.getPassword();
this.role = user.getRole();
}
public void setId(Long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setLogin(String login) {
this.login = login;
}
public String getLogin() {
return login;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
public Long getCartId() {
return cartId;
}
}

View File

@ -0,0 +1,40 @@
package com.LabWork.app.MangaStore.model.Dto;
public class UserSignupDto {
private String login;
private String email;
private String password;
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,10 @@
package com.LabWork.app.MangaStore.service.Exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super(String.format("User with id [%s] is not found", id));
}
public UserNotFoundException(String login) {
super(String.format("User not found '%s'", login));
}
}

View File

@ -0,0 +1,8 @@
package com.LabWork.app.MangaStore.service.Repository;
import com.LabWork.app.MangaStore.model.Default.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,148 @@
package com.LabWork.app.MangaStore.service;
import com.LabWork.app.MangaStore.configuration.jwt.JwtException;
import com.LabWork.app.MangaStore.configuration.jwt.JwtProvider;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.model.Dto.UserDto;
import com.LabWork.app.MangaStore.service.Exception.UserNotFoundException;
import com.LabWork.app.MangaStore.service.Repository.UserRepository;
import com.LabWork.app.MangaStore.util.validation.ValidationException;
import com.LabWork.app.MangaStore.util.validation.ValidatorUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final ValidatorUtil validatorUtil;
private final PasswordEncoder passwordEncoder;
private final JwtProvider jwtProvider;
public UserService(UserRepository userRepository,
ValidatorUtil validatorUtil,
PasswordEncoder passwordEncoder,
JwtProvider jwtProvider) {
this.userRepository = userRepository;
this.validatorUtil = validatorUtil;
this.passwordEncoder = passwordEncoder;
this.jwtProvider = jwtProvider;
}
@Transactional(readOnly = true)
public User findUser(Long id) {
final Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id));
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
@Transactional(readOnly = true)
public List<User> findAllUsers() {
return userRepository.findAll();
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
@Transactional
public User addUser(String login, String email, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login));
}
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
final User user = new User(login, email, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
return userRepository.save(user);
}
@Transactional
public User updateUser(UserDto userDto) {
final User currentUser = findUser(userDto.getId());
final User sameUser = findByLogin(userDto.getLogin());
if (sameUser != null && !Objects.equals(sameUser.getId(), currentUser.getId())) {
throw new ValidationException(String.format("User '%s' already exists", userDto.getLogin()));
}
if (!passwordEncoder.matches(userDto.getPassword(), currentUser.getPassword())) {
throw new ValidationException("Incorrect password");
}
currentUser.setLogin(userDto.getLogin());
currentUser.setEmail(userDto.getEmail());
validatorUtil.validate(currentUser);
return userRepository.save(currentUser);
}
@Transactional
public User deleteUser(Long id) {
final User currentUser = findUser(id);
userRepository.delete(currentUser);
return currentUser;
}
@Transactional
public void deleteAllUsers() {
userRepository.deleteAll();
}
/* @Transactional
public User bindCart(Long id, Long cartId) {
final User user = findUser(id);
final Cart cart = cartService.findCart(cartId);
user.setCart(cart);
return userRepository.save(user);
}
@Transactional
public User unbindCart(Long id) {
final User user = findUser(id);
user.setCart(null);
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 ValidationException("Incorrect password");
}
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()));
}
}

View File

@ -3,7 +3,11 @@ package com.LabWork.app.MangaStore.util.validation;
import java.util.Set; import java.util.Set;
public class ValidationException extends RuntimeException { public class ValidationException extends RuntimeException {
public ValidationException(Set<String> errors) { public <T> ValidationException(Set<String> errors) {
super(String.join("\n", errors)); super(String.join("\n", errors));
} }
public <T> ValidationException(String error) {
super(error);
}
} }

View File

@ -1,26 +0,0 @@
package com.LabWork.app;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseTrailingSlashMatch(true);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK);
}
}