izi katka

This commit is contained in:
VictoriaPresnyakova 2023-05-24 21:29:55 +04:00
parent 12f90d5cad
commit d62cb90848
34 changed files with 716 additions and 282 deletions

View File

@ -12,7 +12,13 @@ repositories {
mavenCentral()
}
jar {
enabled = false
}
dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
@ -22,6 +28,10 @@ dependencies {
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'

View File

@ -13,30 +13,50 @@ function toJSON(data) {
}
export default class DataService {
static dataUrlPrefix = 'http://localhost:8080/';
static dataUrlPrefix = 'http://localhost:8080/api/1.0/';
static async readAll(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url);
const response = (await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).get(this.dataUrlPrefix + url));
return response.data.map(item => transformer(item));
}
static async read(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url);
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).get(this.dataUrlPrefix + url);
return transformer(response.data);
}
static async create(url, data) {
const response = await axios.post(this.dataUrlPrefix + url, toJSON(data));
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).post(this.dataUrlPrefix + url, toJSON(data));
return true;
}
static async update(url, data) {
const response = await axios.put(this.dataUrlPrefix + url, toJSON(data));
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).put(this.dataUrlPrefix + url, toJSON(data));
return true;
}
static async delete(url) {
const response = await axios.delete(this.dataUrlPrefix + url);
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).delete(this.dataUrlPrefix + url);
return response.data.id;
}
}

View File

@ -1,21 +0,0 @@
package ru.ulstu.is.sbapp;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
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) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("rest-test");
}
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -1,27 +0,0 @@
package ru.ulstu.is.sbapp.calc.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.ulstu.is.sbapp.calc.domain.TypeInt;
import ru.ulstu.is.sbapp.calc.domain.TypeString;
import ru.ulstu.is.sbapp.calc.domain.TypeArray;
@Configuration
public class TypeConfiguration {
@Bean(value = "int")
public TypeInt createIntType(){
return new TypeInt();
}
@Bean(value = "str")
public TypeString createStrType(){
return new TypeString();
}
@Bean(value = "arr")
public TypeArray createArrayType(){
return new TypeArray();
}
}

View File

@ -1,43 +0,0 @@
package ru.ulstu.is.sbapp.calc.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.calc.service.TypeService;
@RestController
public class MainController {
private final TypeService Service;
public MainController(TypeService service) {
Service = service;
}
@GetMapping("/Sum")
public Object Sum(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Sum(value1,value2,Type);
}
@GetMapping("/Min")
public Object Min(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Min(value1,value2,Type);
}
@GetMapping("/Mul")
public Object Mul(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Mul(value1,value2,Type);
}
@GetMapping("/Del")
public Object Del(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Del(value1,value2,Type);
}
}

View File

@ -1,8 +0,0 @@
package ru.ulstu.is.sbapp.calc.domain;
public interface ITypeInterface<T> {
T Sum(T value1, T value2);
T Min(T value1, T value2);
T Mul(T value1, T value2);
T Del(T value1, T value2);
}

View File

@ -1,39 +0,0 @@
package ru.ulstu.is.sbapp.calc.domain;
public class TypeArray implements ITypeInterface<int[]>{
@Override
public int[] Sum(int[] value1, int[] value2) {
int [] ans = new int[Math.min(value1.length, value2.length)];
for (int i = 0; i < Math.min(value1.length, value2.length); i ++){
ans[i] = value1[i] + value2[i];
}
return ans;
}
@Override
public int[] Min(int[] value1, int[] value2) {
int [] ans = new int[Math.min(value1.length, value2.length)];
for (int i = 0; i < Math.min(value1.length, value2.length); i ++){
ans[i] = value1[i] - value2[i];
}
return ans;
}
@Override
public int[] Mul(int[] value1, int[] value2) {
int [] ans = new int[Math.min(value1.length, value2.length)];
for (int i = 0; i < Math.min(value1.length, value2.length); i ++){
ans[i] = value1[i] * value2[i];
}
return ans;
}
@Override
public int[] Del(int[] value1, int[] value2) {
int [] ans = new int[Math.min(value1.length, value2.length)];
for (int i = 0; i < Math.min(value1.length, value2.length); i ++){
ans[i] = value1[i] / value2[i];
}
return ans;
}
}

View File

@ -1,23 +0,0 @@
package ru.ulstu.is.sbapp.calc.domain;
public class TypeInt implements ITypeInterface<Integer>{
@Override
public Integer Sum(Integer value1, Integer value2) {
return value1 + value2;
}
@Override
public Integer Min(Integer value1, Integer value2) {
return value1 - value2;
}
@Override
public Integer Mul(Integer value1, Integer value2) {
return value1 * value2;
}
@Override
public Integer Del(Integer value1, Integer value2) {
return value1 / value2;
}
}

View File

@ -1,38 +0,0 @@
package ru.ulstu.is.sbapp.calc.domain;
public class TypeString implements ITypeInterface<String>{
@Override
public String Sum(String value1, String value2) {
return value1 + value2;
}
@Override
public String Min(String value1, String value2) {
if (value1.length() < value2.length()){
String temp = value1;
value1 = value2;
value2 = temp;
}
return value1.substring(value2.length());
}
@Override
public String Mul(String value1, String value2) {
value1 = value1 + value2;
String ans = "";
for (int i = 0; i < value2.length(); i ++){
ans = Sum(ans,value1);
}
return ans;
}
@Override
public String Del(String value1, String value2) {
if (value1.length() < value2.length()){
String temp = value1;
value1 = value2;
value2 = temp;
}
return value1.replaceAll(value2, "");
}
}

View File

@ -1,70 +0,0 @@
package ru.ulstu.is.sbapp.calc.service;
import org.springframework.stereotype.Service;
import org.springframework.context.ApplicationContext;
import ru.ulstu.is.sbapp.calc.domain.ITypeInterface;
import java.util.Arrays;
@Service
public class TypeService {
private final ApplicationContext applicationContext;
private ITypeInterface _type;
private Object _value1;
private Object _value2;
public TypeService(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private void ValidateParams(Object value1, Object value2, String type){
_type = (ITypeInterface)applicationContext.getBean(type);
switch (type) {
case "arr" ->{
try {
_value1 = Arrays.stream(value1.toString().split(",")).mapToInt(Integer::valueOf).toArray();
_value2 = Arrays.stream(value2.toString().split(",")).mapToInt(Integer::valueOf).toArray();
}catch (Exception ex){
_value1 = new int[] {0};
_value2 = new int[] {0};
}
}
case "int" -> {
try {
_value1 = Integer.valueOf(value1.toString());
_value2 = Integer.valueOf(value2.toString());
}catch (Exception ex){
_value1 = 0;
_value2 = 0;
}
}
case "str" -> {
_value1 = value1;
_value2 = value2;
}
}
}
public Object Sum(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return _type.Sum(_value1,_value2);
}
public Object Min(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return _type.Min(_value1,_value2);
}
public Object Mul(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return _type.Mul(_value1,_value2);
}
public Object Del(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return _type.Del(_value1,_value2);
}
}

View File

@ -0,0 +1,27 @@
package ru.ulstu.is.sbapp.repair.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.ulstu.is.sbapp.repair.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")));
}
}

View File

@ -0,0 +1,14 @@
package ru.ulstu.is.sbapp.repair.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,73 @@
package ru.ulstu.is.sbapp.repair.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import ru.ulstu.is.sbapp.repair.configuration.jwt.JwtFilter;
import ru.ulstu.is.sbapp.repair.controller.UserController;
import ru.ulstu.is.sbapp.repair.controller.UserSignupController;
import ru.ulstu.is.sbapp.repair.model.UserRole;
import ru.ulstu.is.sbapp.repair.service.UserService;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
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_LOGIN).permitAll()
.antMatchers(HttpMethod.POST, UserSignupController.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/**");
}
}

View File

@ -0,0 +1,29 @@
package ru.ulstu.is.sbapp.repair.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,10 @@
package ru.ulstu.is.sbapp.repair.configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,67 @@
package ru.ulstu.is.sbapp.repair.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.ulstu.is.sbapp.repair.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);
}
}

View File

@ -0,0 +1,27 @@
package ru.ulstu.is.sbapp.repair.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,99 @@
package ru.ulstu.is.sbapp.repair.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

@ -2,6 +2,7 @@ package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.repair.configuration.OpenAPI30Configuration;
import ru.ulstu.is.sbapp.repair.dtos.ComponentDTO;
import ru.ulstu.is.sbapp.repair.service.ComponentService;
@ -10,7 +11,7 @@ import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/component")
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/component")
public class ComponentController {
private final ComponentService componentService;
public ComponentController(ComponentService productService){

View File

@ -2,6 +2,7 @@ package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.repair.configuration.OpenAPI30Configuration;
import ru.ulstu.is.sbapp.repair.dtos.ComponentDTO;
import ru.ulstu.is.sbapp.repair.dtos.FavorDTO;
import ru.ulstu.is.sbapp.repair.service.FavorService;
@ -10,7 +11,7 @@ import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/favor")
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/favor")
public class FavorController {
private final FavorService favorService;
public FavorController(FavorService favorService){

View File

@ -1,6 +1,7 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.repair.configuration.OpenAPI30Configuration;
import ru.ulstu.is.sbapp.repair.dtos.FavorDTO;
import ru.ulstu.is.sbapp.repair.dtos.OrderDTO;
import ru.ulstu.is.sbapp.repair.service.OrderService;
@ -9,7 +10,7 @@ import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/order")
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/order")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService productService){

View File

@ -0,0 +1,30 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.repair.configuration.OpenAPI30Configuration;
import ru.ulstu.is.sbapp.repair.dtos.UserDto;
import ru.ulstu.is.sbapp.repair.model.User;
import ru.ulstu.is.sbapp.repair.service.UserService;
import javax.validation.Valid;
import java.util.List;
@RestController
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/user")
public List<User> getUsers() {
return userService.findAllUsers();
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDto userDto) {
return userService.loginAndGetToken(userDto);
}
}

View File

@ -0,0 +1,32 @@
package ru.ulstu.is.sbapp.repair.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.repair.dtos.UserSignupDto;
import ru.ulstu.is.sbapp.repair.model.User;
import ru.ulstu.is.sbapp.repair.service.UserService;
import ru.ulstu.is.sbapp.repair.util.validation.ValidationException;
import javax.validation.Valid;
@Controller
@RestController
public class UserSignupController {
public static final String URL_LOGIN = "/signup";
private final UserService userService;
public UserSignupController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String signup(@RequestBody @Valid UserSignupDto userSignupDto) {
try {
final User user = userService.createUser(
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return user.getLogin();
} catch (ValidationException e) {
return "error";
}
}
}

View File

@ -0,0 +1,23 @@
package ru.ulstu.is.sbapp.repair.dtos;
import ru.ulstu.is.sbapp.repair.model.User;
import javax.validation.constraints.NotEmpty;
public class UserDto {
@NotEmpty
private String login;
@NotEmpty
private String password;
public UserDto() {}
UserDto(User user) {
login = user.getLogin();
password = user.getPassword();
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
}

View File

@ -0,0 +1,34 @@
package ru.ulstu.is.sbapp.repair.dtos;
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;
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.repair.exception;
public class UserExistsException extends RuntimeException {
public UserExistsException(String login) {
super(String.format("User '%s' already exists", login));
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.repair.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String login) {
super(String.format("User not found '%s'", login));
}
}

View File

@ -0,0 +1,70 @@
package ru.ulstu.is.sbapp.repair.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
'}';
}
}

View File

@ -0,0 +1,17 @@
package ru.ulstu.is.sbapp.repair.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -0,0 +1,8 @@
package ru.ulstu.is.sbapp.repair.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.repair.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,91 @@
package ru.ulstu.is.sbapp.repair.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.ulstu.is.sbapp.repair.configuration.jwt.JwtException;
import ru.ulstu.is.sbapp.repair.configuration.jwt.JwtProvider;
import ru.ulstu.is.sbapp.repair.dtos.UserDto;
import ru.ulstu.is.sbapp.repair.exception.UserExistsException;
import ru.ulstu.is.sbapp.repair.exception.UserNotFoundException;
import ru.ulstu.is.sbapp.repair.model.User;
import ru.ulstu.is.sbapp.repair.model.UserRole;
import ru.ulstu.is.sbapp.repair.repository.UserRepository;
import ru.ulstu.is.sbapp.repair.util.validation.ValidationException;
import ru.ulstu.is.sbapp.repair.util.validation.ValidatorUtil;
import java.util.Collections;
import java.util.List;
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 List<User> findAllUsers() {
return userRepository.findAll();
}
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()));
}
}

View File

@ -19,7 +19,8 @@ public class AdviceController {
ValidationException.class,
ComponentNotFoundException.class,
FavorNotFoundException.class,
OrderNotFoundException.class
OrderNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);

View File

@ -2,7 +2,9 @@ package ru.ulstu.is.sbapp.repair.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException{
public ValidationException(String message) {
super(message);
}
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}
}}

View File

@ -1,5 +1,5 @@
spring.main.banner-mode=off
#server.port=8080
server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
@ -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