From 8ae10007bb0cbdae3547c8d519b13a6faeea2d2e Mon Sep 17 00:00:00 2001 From: 1yuee Date: Mon, 19 Jun 2023 19:06:46 +0400 Subject: [PATCH] template --- .../lab1/SecurityConfiguration.java | 85 +++++----- .../lab1/SecurityConfigurationSPA.java | 105 ------------ .../webproglabs/lab1/WebConfiguration.java | 3 +- .../webproglabs/lab1/lab1/Lab1Controller.java | 44 ----- .../com/webproglabs/lab1/lab2/Lab2Config.java | 27 --- .../webproglabs/lab1/lab2/Lab2Controller.java | 35 ---- .../webproglabs/lab1/lab2/Lab2Service.java | 47 ------ .../webproglabs/lab1/lab2/domain/Lab2Int.java | 58 ------- .../lab1/lab2/domain/Lab2Interface.java | 11 -- .../lab1/lab2/domain/Lab2String.java | 61 ------- .../lab1/lab34/OpenAPI30Configuration.java | 28 ---- .../lab34/controller/CommentController.java | 59 ------- .../lab1/lab34/controller/CommentDto.java | 23 --- .../lab1/lab34/controller/PostController.java | 64 ------- .../lab1/lab34/controller/PostDto.java | 34 ---- .../lab34/controller/ProfileController.java | 88 ---------- .../lab1/lab34/controller/ProfileDto.java | 50 ------ .../mvc_controllers/FeedMvcController.java | 121 -------------- .../mvc_controllers/ProfileMvcController.java | 52 ------ .../mvc_controllers/UserSignupDto.java | 40 ----- .../UserSignupMvcController.java | 49 ------ .../lab1/lab34/jwt/JwtException.java | 11 -- .../webproglabs/lab1/lab34/jwt/JwtFilter.java | 72 -------- .../lab1/lab34/jwt/JwtProperties.java | 27 --- .../lab1/lab34/jwt/JwtProvider.java | 107 ------------ .../webproglabs/lab1/lab34/model/Comment.java | 81 --------- .../webproglabs/lab1/lab34/model/Post.java | 90 ---------- .../webproglabs/lab1/lab34/model/Profile.java | 133 --------------- .../lab1/lab34/model/UserRole.java | 20 --- .../lab34/repository/CommentRepository.java | 10 -- .../lab1/lab34/repository/PostRepository.java | 11 -- .../lab34/repository/ProfileRepository.java | 12 -- .../lab1/lab34/services/CommentService.java | 102 ----------- .../lab1/lab34/services/PostService.java | 90 ---------- .../lab1/lab34/services/ProfileService.java | 158 ------------------ .../resources/templates/commentModal.html | 31 ---- src/main/resources/templates/default.html | 46 ----- .../resources/templates/editCommentModal.html | 30 ---- .../resources/templates/editPostModal.html | 32 ---- src/main/resources/templates/error.html | 13 -- src/main/resources/templates/feed.html | 32 ---- src/main/resources/templates/feedPosts.html | 106 ------------ src/main/resources/templates/login.html | 30 ---- src/main/resources/templates/profilePage.html | 29 ---- src/main/resources/templates/profiles.html | 56 ------- src/main/resources/templates/signup.html | 28 ---- 46 files changed, 39 insertions(+), 2402 deletions(-) delete mode 100644 src/main/java/com/webproglabs/lab1/SecurityConfigurationSPA.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab1/Lab1Controller.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab2/Lab2Config.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab2/Lab2Controller.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab2/Lab2Service.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab2/domain/Lab2Int.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab2/domain/Lab2Interface.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab2/domain/Lab2String.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/OpenAPI30Configuration.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/CommentController.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/CommentDto.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/PostController.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/PostDto.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/ProfileController.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/ProfileDto.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/FeedMvcController.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/ProfileMvcController.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/UserSignupDto.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/UserSignupMvcController.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/jwt/JwtException.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/jwt/JwtFilter.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/jwt/JwtProperties.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/jwt/JwtProvider.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/model/Comment.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/model/Post.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/model/Profile.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/model/UserRole.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/repository/CommentRepository.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/repository/PostRepository.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/repository/ProfileRepository.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/services/CommentService.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/services/PostService.java delete mode 100644 src/main/java/com/webproglabs/lab1/lab34/services/ProfileService.java delete mode 100644 src/main/resources/templates/commentModal.html delete mode 100644 src/main/resources/templates/default.html delete mode 100644 src/main/resources/templates/editCommentModal.html delete mode 100644 src/main/resources/templates/editPostModal.html delete mode 100644 src/main/resources/templates/error.html delete mode 100644 src/main/resources/templates/feed.html delete mode 100644 src/main/resources/templates/feedPosts.html delete mode 100644 src/main/resources/templates/login.html delete mode 100644 src/main/resources/templates/profilePage.html delete mode 100644 src/main/resources/templates/profiles.html delete mode 100644 src/main/resources/templates/signup.html diff --git a/src/main/java/com/webproglabs/lab1/SecurityConfiguration.java b/src/main/java/com/webproglabs/lab1/SecurityConfiguration.java index 7b54521..b5e5539 100644 --- a/src/main/java/com/webproglabs/lab1/SecurityConfiguration.java +++ b/src/main/java/com/webproglabs/lab1/SecurityConfiguration.java @@ -1,10 +1,5 @@ package com.webproglabs.lab1; -import com.webproglabs.lab1.lab34.controller.ProfileController; -import com.webproglabs.lab1.lab34.controller.mvc_controllers.UserSignupMvcController; -import com.webproglabs.lab1.lab34.jwt.JwtFilter; -import com.webproglabs.lab1.lab34.model.UserRole; -import com.webproglabs.lab1.lab34.services.ProfileService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; @@ -17,12 +12,10 @@ 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.AuthenticationEntryPoint; import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint; import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; @@ -36,49 +29,47 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private static final String LOGIN_URL = "/login"; public static final String SPA_URL_MASK = "/{path:[^\\.]*}"; - private final ProfileService userService; - private final JwtFilter jwtFilter; +// private final ProfileService userService; +// +// public SecurityConfiguration(ProfileService userService) { +// this.userService = userService; +// createAdminOnStartup(); +// } - public SecurityConfiguration(ProfileService 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"); +// try { +// userService.createUser(admin, admin, admin, UserRole.ADMIN); +// } catch (Exception e) { +// throw new RuntimeException(e); +// } +// } +// } - private void createAdminOnStartup() { - final String admin = "admin"; - if (userService.findByLogin(admin) == null) { - log.info("Admin user successfully created"); - try { - userService.createUser(admin, admin, admin, UserRole.ADMIN); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } +// @Override +// protected void configure(HttpSecurity http) throws Exception { +// +// http.exceptionHandling().authenticationEntryPoint(delegatingEntryPoint()); +// http.headers().frameOptions().sameOrigin().and() +// .cors().and() +// .csrf().disable() +// .authorizeRequests() +// .antMatchers(UserSignupMvcController.SIGNUP_URL).permitAll() +// .antMatchers(HttpMethod.GET, LOGIN_URL).permitAll() +// .anyRequest().authenticated() +// .and() +// .formLogin() +// .loginPage(LOGIN_URL).permitAll() +// .and() +// .logout().permitAll(); +// } - @Override - protected void configure(HttpSecurity http) throws Exception { - - http.exceptionHandling().authenticationEntryPoint(delegatingEntryPoint()); - http.headers().frameOptions().sameOrigin().and() - .cors().and() - .csrf().disable() - .authorizeRequests() - .antMatchers(UserSignupMvcController.SIGNUP_URL).permitAll() - .antMatchers(HttpMethod.GET, LOGIN_URL).permitAll() - .anyRequest().authenticated() - .and() - .formLogin() - .loginPage(LOGIN_URL).permitAll() - .and() - .logout().permitAll(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userService); - } +// @Override +// protected void configure(AuthenticationManagerBuilder auth) throws Exception { +// auth.userDetailsService(userService); +// } @Override public void configure(WebSecurity web) { diff --git a/src/main/java/com/webproglabs/lab1/SecurityConfigurationSPA.java b/src/main/java/com/webproglabs/lab1/SecurityConfigurationSPA.java deleted file mode 100644 index 1508432..0000000 --- a/src/main/java/com/webproglabs/lab1/SecurityConfigurationSPA.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.webproglabs.lab1; - -import com.webproglabs.lab1.lab34.controller.ProfileController; -import com.webproglabs.lab1.lab34.controller.mvc_controllers.UserSignupMvcController; -import com.webproglabs.lab1.lab34.jwt.JwtFilter; -import com.webproglabs.lab1.lab34.model.UserRole; -import com.webproglabs.lab1.lab34.services.ProfileService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint; -import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; -import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import org.springframework.security.web.util.matcher.RequestMatcher; - -import java.util.LinkedHashMap; - -@Configuration -@EnableWebSecurity -@EnableGlobalMethodSecurity(securedEnabled = true) -@Profile("spa") -public class SecurityConfigurationSPA extends WebSecurityConfigurerAdapter { - private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); - private static final String LOGIN_URL = "/login"; - public static final String SPA_URL_MASK = "/{path:[^\\.]*}"; - private final ProfileService userService; - private final JwtFilter jwtFilter; - - public SecurityConfigurationSPA(ProfileService 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"); - try { - userService.createUser(admin, admin, admin, UserRole.ADMIN); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - @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, WebConfiguration.REST_API + "/profile" + ProfileController.URL_LOGIN).permitAll() - .anyRequest() - .authenticated() - .and() - .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class) - .anonymous(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userService); - } - - @Override - public void configure(WebSecurity web) { - web.ignoring() - .antMatchers("/css/**") - .antMatchers("/js/**") - .antMatchers("/templates/**") - .antMatchers("/webjars/**") - .antMatchers("/swagger-resources/**") - .antMatchers("/v3/api-docs/**"); - } - - @Bean - public AuthenticationEntryPoint delegatingEntryPoint() { - final LinkedHashMap map = new LinkedHashMap(); - map.put(new AntPathRequestMatcher("/"), new LoginUrlAuthenticationEntryPoint("/login")); - map.put(new AntPathRequestMatcher("/api/1.0/**"), new Http403ForbiddenEntryPoint()); - - final DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(map); - entryPoint.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")); - - return entryPoint; - } -} diff --git a/src/main/java/com/webproglabs/lab1/WebConfiguration.java b/src/main/java/com/webproglabs/lab1/WebConfiguration.java index 612b2b6..42ff4a6 100644 --- a/src/main/java/com/webproglabs/lab1/WebConfiguration.java +++ b/src/main/java/com/webproglabs/lab1/WebConfiguration.java @@ -1,6 +1,5 @@ package com.webproglabs.lab1; -import com.webproglabs.lab1.lab34.OpenAPI30Configuration; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; @@ -13,7 +12,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfiguration implements WebMvcConfigurer { - public static final String REST_API = OpenAPI30Configuration.API_PREFIX; + public static final String REST_API = "/api"; @Override public void addViewControllers(ViewControllerRegistry registry) { WebMvcConfigurer.super.addViewControllers(registry); diff --git a/src/main/java/com/webproglabs/lab1/lab1/Lab1Controller.java b/src/main/java/com/webproglabs/lab1/lab1/Lab1Controller.java deleted file mode 100644 index 9675a7e..0000000 --- a/src/main/java/com/webproglabs/lab1/lab1/Lab1Controller.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.webproglabs.lab1.lab1; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Random; - -@RestController -public class Lab1Controller { - @GetMapping("/ilove") - public String ilove(@RequestParam(value = "thing", defaultValue = "cookies") String thing) { - return String.format("I love %s!", thing); - } - - @GetMapping("/ask") - public String question(@RequestParam(value = "question", defaultValue = "Задайте вопрос") String question) { - if (question.contains("Задайте вопрос")) return question; - String[] answers = new String[] { - "Не знаю", - "Да", - "Нет", - "Спросите у мамы" - }; - Random random = new Random(); - return answers[random.nextInt(4)]; - } - - @GetMapping("/touppercase") - public String tuupper(@RequestParam(value = "content", defaultValue = "Введите строку") String content) { - return content.toUpperCase(); - } - - @GetMapping("/date") - public String date () { - DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); - LocalDateTime now = LocalDateTime.now(); - return dtf.format(now); - } - - -} diff --git a/src/main/java/com/webproglabs/lab1/lab2/Lab2Config.java b/src/main/java/com/webproglabs/lab1/lab2/Lab2Config.java deleted file mode 100644 index 67a0224..0000000 --- a/src/main/java/com/webproglabs/lab1/lab2/Lab2Config.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.webproglabs.lab1.lab2.config; - -import com.webproglabs.lab1.lab2.domain.Lab2Int; -import com.webproglabs.lab1.lab2.domain.Lab2String; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class Lab2Config { - - @Bean(value="int") - public Lab2Int createLab2Int() { - return new Lab2Int(); - } - - @Bean(value="String") - public Lab2String createLab2String() { - return new Lab2String(); - } -} - -//фронт на жсон сервер был когда то -//сделать на основе старых сущностей сущности в жпа -//делаем сущности, зависимость для жпа, сервис для круд операций, -//тесты -//фронт не нужно -//двунправленная связь один ко многим \ No newline at end of file diff --git a/src/main/java/com/webproglabs/lab1/lab2/Lab2Controller.java b/src/main/java/com/webproglabs/lab1/lab2/Lab2Controller.java deleted file mode 100644 index e0c5cce..0000000 --- a/src/main/java/com/webproglabs/lab1/lab2/Lab2Controller.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.webproglabs.lab1.lab2.controllers; - -import com.webproglabs.lab1.lab2.Lab2Service; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class Lab2Controller { - private final Lab2Service lab2Service; - - public Lab2Controller(Lab2Service lab2Service) {this.lab2Service = lab2Service;} - - @GetMapping("/lab2/sum") - public Object sum(@RequestParam (value = "first", defaultValue = "hello") String first, - @RequestParam (value = "second", defaultValue = "world") String second, - @RequestParam (value = "type") String type) { - return lab2Service.sum(first, second, type); - } - - @GetMapping("/lab2/makeitbigger") - public Object makeItBigger(@RequestParam (value = "small") String small, @RequestParam (value = "type") String type) { - return lab2Service.makeItBigger(small, type); - } - - @GetMapping("/lab2/reverse") - public Object reverse(@RequestParam(value="value")String value, @RequestParam (value = "type") String type) { - return lab2Service.reverse(value, type); - } - - @GetMapping("lab2/lenght") - public Object lenght(@RequestParam(value = "value") String value, @RequestParam (value = "type") String type) { - return lab2Service.lenght(value, type); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab2/Lab2Service.java b/src/main/java/com/webproglabs/lab1/lab2/Lab2Service.java deleted file mode 100644 index e6d2580..0000000 --- a/src/main/java/com/webproglabs/lab1/lab2/Lab2Service.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.webproglabs.lab1.lab2; - -import com.webproglabs.lab1.lab2.domain.Lab2Interface; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Service; - -@Service -public class Lab2Service { - private final ApplicationContext applicationContext; - - public Lab2Service(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - public Object sum(Object first, Object second, String type) { - if (type.equals("int")) { - first = Integer.parseInt(first.toString()); - second = Integer.parseInt(second.toString()); - } - final Lab2Interface summator =(Lab2Interface)applicationContext.getBean(type); - return summator.sum(first, second); - } - - public Object makeItBigger(Object small, String type) { - if (type.equals("int")) { - small = Integer.parseInt(small.toString()); - } - final Lab2Interface biggernator = (Lab2Interface)applicationContext.getBean(type); - return biggernator.makeItBigger(small); - } - - public Object reverse (Object value, String type) { - if (type.equals("int")) { - value = Integer.parseInt(value.toString()); - } - final Lab2Interface reversenator = (Lab2Interface) applicationContext.getBean(type); - return reversenator.reverse(value); - } - - public Object lenght (Object value, String type) { - if (type.equals("int")) { - value = Integer.parseInt(value.toString()); - } - final Lab2Interface leghtgetter = (Lab2Interface) applicationContext.getBean(type); - return leghtgetter.lenght(value); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2Int.java b/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2Int.java deleted file mode 100644 index 7088e7b..0000000 --- a/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2Int.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.webproglabs.lab1.lab2.domain; - -public class Lab2Int implements Lab2Interface{ -// @Override -// public Object sum(Object first, Object second) { -// if (!(first instanceof Integer && second instanceof Integer)) { -// throw new IllegalArgumentException(); -// } -// return (Integer)first + (Integer)second; -// } -// -// @Override -// public Object makeItBigger(Object small) { -// if (!(small instanceof Integer)) { -// throw new IllegalArgumentException(); -// } -// return (Integer)small * (Integer)small; -// } -// -// @Override -// public Object reverse(Object value) { -// if (!(value instanceof Integer)) { -// throw new IllegalArgumentException(); -// } -// return (Integer)value * (-1); -// } -// -// @Override -// public Object lenght(Object value) { -// if (!(value instanceof Integer)) { -// throw new IllegalArgumentException(); -// } -// int newvalue = (Integer)value; -// if (newvalue < 0) newvalue = newvalue * (-1); -// return newvalue; -// } - - @Override - public Integer sum(Integer first, Integer second) { - return first + second; - } - - @Override - public Integer makeItBigger(Integer small) { - return small*small; - } - - @Override - public Integer reverse(Integer value) { - return value*(-1); - } - - @Override - public Integer lenght(Integer value) { - if (value < 0) return value *(-1); - else return value; - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2Interface.java b/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2Interface.java deleted file mode 100644 index 9c5df55..0000000 --- a/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2Interface.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.webproglabs.lab1.lab2.domain; - -public interface Lab2Interface { - T sum(T first, T second); - - T makeItBigger (T small); - - T reverse (T value); - - T lenght (T value); -} diff --git a/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2String.java b/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2String.java deleted file mode 100644 index a982642..0000000 --- a/src/main/java/com/webproglabs/lab1/lab2/domain/Lab2String.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.webproglabs.lab1.lab2.domain; - -public class Lab2String implements Lab2Interface{ -// @Override -// public Object sum(Object first, Object second) { -// if (!(first instanceof String && second instanceof String)) { -// throw new IllegalArgumentException(); -// } -// return ((String) first).concat((String)second); -// } -// -// @Override -// public Object makeItBigger(Object small) { -// if (!(small instanceof String)) { -// throw new IllegalArgumentException(); -// } -// return ((String) small).toUpperCase(); -// } -// -// @Override -// public Object reverse(Object value) { -// if (!(value instanceof String)) { -// throw new IllegalArgumentException(); -// } -// StringBuilder sb = new StringBuilder((String)value); -// sb.reverse(); -// return sb.toString(); -// } -// -// @Override -// public Object lenght(Object value) { -// if (!(value instanceof String)) { -// throw new IllegalArgumentException(); -// } -// return ((String) value).length(); -// } - - - @Override - public String sum(String first, String second) { - return first.concat(second); - } - - @Override - public String makeItBigger(String small) { - return small.toUpperCase(); - } - - @Override - public String reverse(String value) { - StringBuilder sb = new StringBuilder(value); - sb.reverse(); - return sb.toString(); - } - - @Override - public String lenght(String value) { - int len = value.length(); - return Integer.toString(len); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/OpenAPI30Configuration.java b/src/main/java/com/webproglabs/lab1/lab34/OpenAPI30Configuration.java deleted file mode 100644 index 0b5909f..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/OpenAPI30Configuration.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.webproglabs.lab1.lab34; - -import com.webproglabs.lab1.lab34.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"))); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/CommentController.java b/src/main/java/com/webproglabs/lab1/lab34/controller/CommentController.java deleted file mode 100644 index c1f7732..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/CommentController.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.webproglabs.lab1.lab34.controller; - -import com.webproglabs.lab1.WebConfiguration; -import com.webproglabs.lab1.lab34.model.Comment; -import com.webproglabs.lab1.lab34.model.Profile; -import com.webproglabs.lab1.lab34.services.CommentService; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@RestController -@RequestMapping(WebConfiguration.REST_API + "/comment") -public class CommentController { - private final CommentService commentService; - - public CommentController(CommentService commentService) { - this.commentService = commentService; - } - - @GetMapping("/{id}") - public CommentDto getComment(@PathVariable Long id) { - return new CommentDto(commentService.findComment(id)); - } - - @GetMapping - public List getComments() { - return commentService.findAllComments().stream() - .map(CommentDto::new) - .toList(); - } - @GetMapping("/find") - public List getFilteredComments(@RequestParam("text") String text) { - return commentService.findFilteredComments(text).stream() - .map(PostDto::new) - .toList(); - } - - - @PostMapping - public CommentDto createComment(@RequestParam("text") String text, @RequestParam("ownerId") Long id, @RequestParam("postId") Long postId){ - final Comment comment = commentService.addComment(text, id, postId); - return new CommentDto(comment); - } - - @PutMapping("/{id}") - public CommentDto updateComment(@RequestParam("text") String text, @PathVariable Long id) { - return new CommentDto(commentService.updateComment(id, text)); - } - - @DeleteMapping("/{id}") - public CommentDto deleteComment(@PathVariable Long id) { - return new CommentDto(commentService.deleteComment(id)); - } - - @DeleteMapping - public void deleteAllComments(){ - commentService.deleteAllComments(); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/CommentDto.java b/src/main/java/com/webproglabs/lab1/lab34/controller/CommentDto.java deleted file mode 100644 index 9b6ead5..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/CommentDto.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.webproglabs.lab1.lab34.controller; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.webproglabs.lab1.lab34.model.Comment; - -public class CommentDto { - private Long id; - private String text; - private String authorLogin; - - public CommentDto(Comment comment) { - this.id = comment.getId(); - this.text = comment.getText(); - this.authorLogin = comment.getOwner().getLogin(); - } - - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - public long getId() { - return id; - } - public String getText() {return text;} - public String getAuthor() {return authorLogin;} -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/PostController.java b/src/main/java/com/webproglabs/lab1/lab34/controller/PostController.java deleted file mode 100644 index 73efcce..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/PostController.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.webproglabs.lab1.lab34.controller; - -import com.webproglabs.lab1.WebConfiguration; -import com.webproglabs.lab1.lab34.services.PostService; -import org.springframework.web.bind.annotation.*; - -import java.util.ArrayList; -import java.util.List; - -@RestController -@RequestMapping(WebConfiguration.REST_API + "/post") -public class PostController { - private final PostService postService; - - public PostController(PostService postService) { - this.postService = postService; - } - - @GetMapping("/{id}") - public PostDto getPost(@PathVariable Long id) { - return new PostDto(postService.findPost(id)); - } - - @GetMapping - public List getPosts() { - return postService.findAllPosts().stream() - .map(PostDto::new) - .toList(); - } - - @GetMapping("/find") - public List getFilteredPosts(@RequestParam("text") String text) { - return postService.findFilteredPosts(text).stream() - .map(PostDto::new) - .toList(); - } - - @PostMapping - public PostDto createPost( - @RequestParam("text") String text, - @RequestParam("authorId") Long authorId - ) - { - return new PostDto(postService.addPost(text, new ArrayList<>(),authorId)); - } - - @PutMapping("/{id}") - public PostDto updatePost( - @PathVariable Long id, - @RequestParam("text") String text - ) - { - return new PostDto(postService.updatePost(id, text)); - } - - @DeleteMapping("/{id}") - public PostDto deletePost (@PathVariable Long id) { - return new PostDto(postService.deletePost(id)); - } - @DeleteMapping - public void deleteAllPosts() { - postService.deleteAllPosts(); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/PostDto.java b/src/main/java/com/webproglabs/lab1/lab34/controller/PostDto.java deleted file mode 100644 index 0b6f886..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/PostDto.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.webproglabs.lab1.lab34.controller; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.webproglabs.lab1.lab34.model.Comment; -import com.webproglabs.lab1.lab34.model.Post; -import com.webproglabs.lab1.lab34.model.Profile; - -import java.util.ArrayList; -import java.util.List; - -public class PostDto { - private Long id; - private String text; - private List comments = new ArrayList<>(); - - private String authorLogin; - - public PostDto(Post post){ - this.id = post.getId(); - this.text = post.getText(); - for(Comment comment: post.getComments()){ - comments.add(new CommentDto(comment)); - } - this.authorLogin = post.getAuthor().getLogin(); - } - - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - public long getId() { - return id; - } - public String getText() {return text;} - public List getComments() {return comments;} - public String getAuthor() {return authorLogin;} -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/ProfileController.java b/src/main/java/com/webproglabs/lab1/lab34/controller/ProfileController.java deleted file mode 100644 index a2e9e5c..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/ProfileController.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.webproglabs.lab1.lab34.controller; - -import com.webproglabs.lab1.WebConfiguration; -import com.webproglabs.lab1.lab34.model.Profile; -import com.webproglabs.lab1.lab34.model.UserRole; -import com.webproglabs.lab1.lab34.services.ProfileService; -import org.springframework.web.bind.annotation.*; - -import javax.validation.Valid; -import java.util.ArrayList; -import java.util.List; - -@RestController -@RequestMapping(WebConfiguration.REST_API + "/profile") -public class ProfileController { - - public static final String URL_LOGIN = "/jwt/login"; - - private final ProfileService profileService; - - public ProfileController(ProfileService profileService) { - this.profileService = profileService; - } - - @GetMapping("/{id}") - public ProfileDto getProfile(@PathVariable Long id) { - return new ProfileDto(profileService.findUser(id)); - } - - @GetMapping("/find/{login}") - public ProfileDto getProfileByLogin(@PathVariable String login) { - return new ProfileDto(profileService.findByLogin(login)); - } - - @GetMapping - public List getProfiles() { - return profileService.findAllUsers().stream() - .map(ProfileDto::new) - .toList(); - } - - @PostMapping - public ProfileDto createProfile( - @RequestParam("login") String login, - @RequestParam("password") String password - ) - { - return new ProfileDto(profileService.addUser(login, password, new ArrayList<>(),new ArrayList<>() )); - } - - @PutMapping("/{id}") - public ProfileDto updateProfile( - @PathVariable Long id, - @RequestParam("login") String login, - @RequestParam("password") String password - ) - { - return new ProfileDto(profileService.updateUser(id, login, password)); - } - - @DeleteMapping("/{id}") - public ProfileDto deleteProfile (@PathVariable Long id) { - return new ProfileDto(profileService.deleteUser(id)); - } - @DeleteMapping - public void deleteAllProfiles() { - profileService.deleteAllUsers(); - } - @PostMapping(URL_LOGIN) - public String login(@RequestBody @Valid ProfileDto userDto) { - return profileService.loginAndGetToken(userDto); - } - - - // этот метод юзать для проверки на администраторсткую роль вместо старой проверки по логину админа ЛОЛ - // - @GetMapping("role/{token}") - public String getRoleByToken(@PathVariable String token) { - var userDetails = profileService.loadUserByToken(token); - Profile user = profileService.findByLogin(userDetails.getUsername()); - if (user != null) { - return user.getRole().toString(); - } - return null; - } - - -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/ProfileDto.java b/src/main/java/com/webproglabs/lab1/lab34/controller/ProfileDto.java deleted file mode 100644 index 41f4aa3..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/ProfileDto.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.webproglabs.lab1.lab34.controller; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.webproglabs.lab1.lab34.model.Comment; -import com.webproglabs.lab1.lab34.model.Post; -import com.webproglabs.lab1.lab34.model.Profile; -import com.webproglabs.lab1.lab34.model.UserRole; - -import java.util.ArrayList; -import java.util.List; - -public class ProfileDto { - private Long id; - private String login; - private String password; - private List comments = new ArrayList<>(); - - private List posts = new ArrayList<>(); - - private UserRole role; - - public ProfileDto(){} - - public ProfileDto(Profile profile){ - this.id = profile.getId(); - this.login = profile.getLogin(); - this.password = profile.getPassword(); - this.role = profile.getRole(); - for(Comment comment: profile.getComments()){ - comments.add(new CommentDto(comment)); - } - for (Post post: profile.getPosts()) { - posts.add(new PostDto(post)); - } - } - - @JsonProperty(access = JsonProperty.Access.READ_ONLY) - public long getId() { - return id; - } - public String getLogin() {return login;} - public void setLogin(String login) {this.login = login;} - public String getPassword() {return password;} - - public UserRole getRole() {return role;} - - public void setPassword(String password) {this.password = password;} - public List getComments() {return comments;} - public List getPosts() {return posts;} -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/FeedMvcController.java b/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/FeedMvcController.java deleted file mode 100644 index 3985e0d..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/FeedMvcController.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.webproglabs.lab1.lab34.controller.mvc_controllers; - -import com.webproglabs.lab1.lab34.controller.CommentDto; -import com.webproglabs.lab1.lab34.controller.PostDto; -import com.webproglabs.lab1.lab34.controller.ProfileDto; -import com.webproglabs.lab1.lab34.model.Profile; -import com.webproglabs.lab1.lab34.services.CommentService; -import com.webproglabs.lab1.lab34.services.PostService; -import com.webproglabs.lab1.lab34.services.ProfileService; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.*; - -import java.util.ArrayList; - -@Controller -@RequestMapping("/feed") -public class FeedMvcController { - private final ProfileService profileService; - private final PostService postService; - private final CommentService commentService; - public FeedMvcController(ProfileService profileService, PostService postService, CommentService commentService) { - this.profileService = profileService; - this.postService = postService; - this.commentService = commentService; - } - - @GetMapping - public String getFeedPage(Model model) { - UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - var user = profileService.findByLogin(principal.getUsername()); - if (user != null) { - return "redirect:/feed/" + user.getId().toString(); - } - - model.addAttribute("profiles", profileService.findAllUsers().stream().map(ProfileDto::new).toList()); - return "feed"; - } - - @GetMapping(value = {"/{id}"}) - public String getFeedPageAuthorized(@PathVariable Long id, Model model) { - model.addAttribute("profiles", profileService.findAllUsers().stream().map(ProfileDto::new).toList()); - model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList()); - model.addAttribute("selectedProfile", new ProfileDto(profileService.findUser(id))); - - return "feedPosts"; - } - - @GetMapping(value= {"/filter/{id}/"}) - public String getFeedPageFiltered(@PathVariable Long id, @RequestParam(value="searchField") String searchField, Model model) { - model.addAttribute("profiles", profileService.findAllUsers().stream().map(ProfileDto::new).toList()); - model.addAttribute("posts", postService.findFilteredPosts(searchField).stream().map(PostDto::new).toList()); - model.addAttribute("selectedProfile", new ProfileDto(profileService.findUser(id))); - return "feedPosts"; - } - - @PostMapping(value={"/post/{id}/"}) - public String createPost(@PathVariable Long id, @RequestParam(value="postInputField") String postInputField) { - postService.addPost(postInputField, new ArrayList<>(), id); - return "redirect:/feed/" + id.toString(); - } - - @PostMapping(value = {"/deletePost/{id}/{authorId}"}) - public String deletePost(@PathVariable Long id, @PathVariable Long authorId) { - postService.deletePost(id); - return "redirect:/feed/" + authorId.toString(); - } - - @GetMapping(value = {"postModal/{id}/{authorId}"}) - public String getPostEditModal(@PathVariable Long id,@PathVariable Long authorId, Model model) { - model.addAttribute("selectedPost", new PostDto(postService.findPost(id))); - model.addAttribute("profiles", profileService.findAllUsers().stream().map(ProfileDto::new).toList()); - model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList()); - model.addAttribute("selectedProfile", new ProfileDto(profileService.findUser(authorId))); - return "editPostModal"; - } - - @PostMapping(value = {"editPost/{id}/{authorId}/"}) - public String editPost(@PathVariable Long id, @PathVariable Long authorId, @RequestParam(value="postEditField") String postEditField) { - postService.updatePost(id, postEditField); - return "redirect:/feed/" + authorId.toString(); - } - - @GetMapping(value = {"commentModal/{authorId}/{postId}"}) - public String getCommentModal(@PathVariable Long authorId,@PathVariable Long postId, Model model) { - model.addAttribute("selectedPost", new PostDto(postService.findPost(postId))); - model.addAttribute("profiles", profileService.findAllUsers().stream().map(ProfileDto::new).toList()); - model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList()); - model.addAttribute("selectedProfile", new ProfileDto(profileService.findUser(authorId))); - return "commentModal"; - } - - @PostMapping(value = {"comment/{authorId}/{postId}/"}) - public String createComment(@PathVariable Long authorId,@PathVariable Long postId, @RequestParam(value="commentInputField") String commentInputField) { - commentService.addComment(commentInputField, authorId, postId); - return "redirect:/feed/" + authorId.toString(); - } - - @PostMapping(value = {"/deleteComment/{id}/{authorId}"}) - public String deleteComment(@PathVariable Long id, @PathVariable Long authorId) { - commentService.deleteComment(id); - return "redirect:/feed/" + authorId.toString(); - } - - @GetMapping(value = {"commentEditModal/{id}/{authorId}"}) - public String getCommentEditModal(@PathVariable Long id,@PathVariable Long authorId, Model model) { - model.addAttribute("selectedComment", new CommentDto(commentService.findComment(id))); - model.addAttribute("profiles", profileService.findAllUsers().stream().map(ProfileDto::new).toList()); - model.addAttribute("posts", postService.findAllPosts().stream().map(PostDto::new).toList()); - model.addAttribute("selectedProfile", new ProfileDto(profileService.findUser(authorId))); - return "editCommentModal"; - } - - @PostMapping(value = {"editComment/{authorId}/{commentId}/"}) - public String editComment(@PathVariable Long authorId,@PathVariable Long commentId, @RequestParam(value="commentEditField") String commentEditField) { - commentService.updateComment(commentId, commentEditField); - return "redirect:/feed/" + authorId.toString(); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/ProfileMvcController.java b/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/ProfileMvcController.java deleted file mode 100644 index a59470f..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/ProfileMvcController.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.webproglabs.lab1.lab34.controller.mvc_controllers; - -import com.webproglabs.lab1.lab34.controller.ProfileDto; -import com.webproglabs.lab1.lab34.model.UserRole; -import com.webproglabs.lab1.lab34.services.ProfileService; -import org.springframework.security.access.annotation.Secured; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.*; - -import java.util.ArrayList; - -@Controller -@RequestMapping("/") -public class ProfileMvcController { - private final ProfileService profileService; - - public ProfileMvcController(ProfileService profileService) { - this.profileService = profileService; - } - - @GetMapping - public String index() { - return "default"; - } - - @GetMapping(value={"profiles"}) - @Secured({UserRole.AsString.ADMIN}) - public String getProfiles(Model model) { - model.addAttribute("profiles", profileService.findAllUsers().stream().map(ProfileDto::new).toList()); - model.addAttribute("profileDto", new ProfileDto()); - return "profiles"; - } - - @GetMapping(value = {"profile/{login}"}) - public String getProfile(@PathVariable String login, Model model) { - model.addAttribute("profile", new ProfileDto(profileService.findUserByLogin(login))); - return "profilePage"; - } - - @PostMapping(value = {"profile/{id}"}) - public String deleteProfile(@PathVariable Long id) { - profileService.deleteUser(id); - return "redirect:/profiles"; - } - - @PostMapping(value = {"profile/create/"}) - public String createProfile(@ModelAttribute ProfileDto profileDto) { - profileService.addUser(profileDto.getLogin(), profileDto.getPassword(), new ArrayList<>(), new ArrayList<>()); - return "redirect:/profiles"; - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/UserSignupDto.java b/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/UserSignupDto.java deleted file mode 100644 index 447b057..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/UserSignupDto.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.webproglabs.lab1.lab34.controller.mvc_controllers; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; - -public class UserSignupDto { - @NotBlank - @Size(min = 3, max = 64) - private String login; - @NotBlank - @Size(min = 6, max = 64) - private String password; - @NotBlank - @Size(min = 6, max = 64) - private String passwordConfirm; - - public String getLogin() { - return login; - } - - public void setLogin(String login) { - this.login = login; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getPasswordConfirm() { - return passwordConfirm; - } - - public void setPasswordConfirm(String passwordConfirm) { - this.passwordConfirm = passwordConfirm; - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/UserSignupMvcController.java b/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/UserSignupMvcController.java deleted file mode 100644 index 6f4f399..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/controller/mvc_controllers/UserSignupMvcController.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.webproglabs.lab1.lab34.controller.mvc_controllers; - -import com.webproglabs.lab1.lab34.model.Profile; -import com.webproglabs.lab1.lab34.services.ProfileService; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import javax.validation.Valid; - -@Controller -@RequestMapping(UserSignupMvcController.SIGNUP_URL) -public class UserSignupMvcController { - public static final String SIGNUP_URL = "/signup"; - - private final ProfileService userService; - - public UserSignupMvcController(ProfileService userService) { - this.userService = userService; - } - - @GetMapping - public String showSignupForm(Model model) { - model.addAttribute("userDto", new UserSignupDto()); - return "signup"; - } - - @PostMapping - public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto, - BindingResult bindingResult, - Model model) { - if (bindingResult.hasErrors()) { - model.addAttribute("errors", bindingResult.getAllErrors()); - return "signup"; - } - try { - final Profile user = userService.createUser( - userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm()); - return "redirect:/login?created=" + user.getLogin(); - } catch (Exception e) { - model.addAttribute("errors", e.getMessage()); - return "signup"; - } - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtException.java b/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtException.java deleted file mode 100644 index bdc8572..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.webproglabs.lab1.lab34.jwt; - -public class JwtException extends RuntimeException { - public JwtException(Throwable throwable) { - super(throwable); - } - - public JwtException(String message) { - super(message); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtFilter.java b/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtFilter.java deleted file mode 100644 index ad981bb..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtFilter.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.webproglabs.lab1.lab34.jwt; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.webproglabs.lab1.lab34.services.ProfileService; -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 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 ProfileService userService; - - public JwtFilter(ProfileService 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); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtProperties.java b/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtProperties.java deleted file mode 100644 index e51cfd2..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtProperties.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.webproglabs.lab1.lab34.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; - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtProvider.java b/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtProvider.java deleted file mode 100644 index 2e53566..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/jwt/JwtProvider.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.webproglabs.lab1.lab34.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 getLoginFromToken(String token) { - try { - return Optional.ofNullable(validateToken(token).getSubject()); - } catch (JwtException e) { - LOG.error(e.getMessage()); - return Optional.empty(); - } - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/model/Comment.java b/src/main/java/com/webproglabs/lab1/lab34/model/Comment.java deleted file mode 100644 index f3da3d4..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/model/Comment.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.webproglabs.lab1.lab34.model; - -import javax.persistence.*; -import java.util.Objects; - -@Entity -public class Comment { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String text; - - @ManyToOne() - private Profile owner; - - @ManyToOne() - private Post post; - - public Comment(){}; - public Comment(String text, Profile owner, Post post) { - this.text = text; - this.owner = owner; - this.post = post; - } - - public Long getId() { - return id; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public Profile getOwner() { - return owner; - } - public void setOwner(Profile owner) { - this.owner.getComments().remove(this); - this.owner = owner; - if (!owner.getComments().contains(this)) { - owner.getComments().add(this); - } - } - - public Post getPost() {return post; } - - public void setPost(Post post) { - this.post.getComments().remove(this); - this.post = post; - if (!post.getComments().contains(this)) { - post.getComments().add(this); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Comment comment = (Comment) o; - return Objects.equals(id, comment.id); - } - - @Override - public int hashCode() { - return Objects.hash(id); - } - - public String ToString() { - return "Comment{" + - "id=" + id + - ", text='" + text + '\'' + - ", owner='" + owner.ToString() + '\'' + - ", post='" + post.ToString() + '\'' + - '}'; - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/model/Post.java b/src/main/java/com/webproglabs/lab1/lab34/model/Post.java deleted file mode 100644 index 8779f51..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/model/Post.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.webproglabs.lab1.lab34.model; - -import javax.persistence.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -@Entity -public class Post { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String text; - - @OneToMany(mappedBy = "post", orphanRemoval = true, fetch = FetchType.EAGER) - private List comments = new ArrayList(); - - @ManyToOne() - private Profile author; - - public Post(){} - public Post(String text, Profile author, List comments) { - this.text = text; - this.author = author; - for (int i = 0; i < comments.size(); i++) { - addComment(comments.get(i)); - } - } - - public Long getId() { - return id; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public Profile getAuthor() { - return author; - } - - public void setAuthor(Profile author) { - this.author.getPosts().remove(this); - this.author = author; - if (!author.getPosts().contains(this)) { - author.getPosts().add(this); - } - } - - public List getComments() { return comments; } - public int getCommentsSize() { - if (comments == null) return 0; - else return comments.size(); - } - - public void addComment(Comment comment) { - this.comments.add(comment); - if (comment.getPost() != this) { - comment.setPost(this); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Post post = (Post) o; - return Objects.equals(id, post.id); - } - - @Override - public int hashCode() { - return Objects.hash(id); - } - - public String ToString() { - return "Post{" + - "id=" + id + - ", text='" + text + '\'' + - ", author='" + author.ToString() + '\'' + - ", comments='" + getCommentsSize() + '\'' + - '}'; - } - -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/model/Profile.java b/src/main/java/com/webproglabs/lab1/lab34/model/Profile.java deleted file mode 100644 index be15025..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/model/Profile.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.webproglabs.lab1.lab34.model; - -import javax.persistence.*; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -@Entity -@Table(name="tab_user") -public class Profile { - @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 UserRole getRole() { - return role; - } - - @OneToMany(mappedBy = "owner", orphanRemoval = true, fetch = FetchType.EAGER) - private List comments = new ArrayList(); - - @OneToMany(mappedBy = "author", orphanRemoval = true, fetch = FetchType.EAGER) - private List posts = new ArrayList(); - - public Profile(){} - public Profile(String login, String password, List comments, List posts) { - this.login = login; - this.password=password; - this.role = UserRole.USER; - for (int i = 0; i < comments.size(); i++) { - addComment(comments.get(i)); - } - for (int i = 0; i < posts.size(); i++) { - addPost(posts.get(i)); - } - }; - public Profile(String login, String password, List comments, List posts, UserRole role) { - this.login = login; - this.password=password; - this.role = role; - for (int i = 0; i < comments.size(); i++) { - addComment(comments.get(i)); - } - for (int i = 0; i < posts.size(); i++) { - addPost(posts.get(i)); - } - }; - - 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 List getComments() { return comments; } - - public List getPosts() {return posts; } - - public int getCommentsSize() { - if (comments == null) return 0; - else return comments.size(); - } - - public int getPostsSize() { - if (posts == null) return 0; - else return posts.size(); - } - - public void addComment(Comment comment) { - this.comments.add(comment); - if (comment.getOwner() != this) { - comment.setOwner(this); - } - } - - public void addPost(Post post) { - this.posts.add(post); - if (post.getAuthor() != this) { - post.setAuthor(this); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Profile user = (Profile) o; - return Objects.equals(id, user.id); - } - - @Override - public int hashCode() { - return Objects.hash(id); - } - - public String ToString() { - return "User{" + - "id=" + id + - ", login='" + login + '\'' + - ", password='" + password + '\'' + - ", comments='" + getCommentsSize() + '\'' + - ", comments='" + getPostsSize() + '\'' + - '}'; - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/model/UserRole.java b/src/main/java/com/webproglabs/lab1/lab34/model/UserRole.java deleted file mode 100644 index 03102cc..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/model/UserRole.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.webproglabs.lab1.lab34.model; - -import org.springframework.security.core.GrantedAuthority; - -public enum UserRole implements GrantedAuthority { - ADMIN, - USER; - - private static final String PREFIX = "ROLE_"; - - @Override - public String getAuthority() { - return PREFIX + this.name(); - } - - public static final class AsString { - public static final String ADMIN = PREFIX + "ADMIN"; - public static final String USER = PREFIX + "USER"; - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/repository/CommentRepository.java b/src/main/java/com/webproglabs/lab1/lab34/repository/CommentRepository.java deleted file mode 100644 index 28a53bf..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/repository/CommentRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.webproglabs.lab1.lab34.repository; - -import com.webproglabs.lab1.lab34.model.Comment; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -public interface CommentRepository extends JpaRepository { - List findByTextLike(String text); -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/repository/PostRepository.java b/src/main/java/com/webproglabs/lab1/lab34/repository/PostRepository.java deleted file mode 100644 index 582553e..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/repository/PostRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.webproglabs.lab1.lab34.repository; - -import com.webproglabs.lab1.lab34.model.Comment; -import com.webproglabs.lab1.lab34.model.Post; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -public interface PostRepository extends JpaRepository { - List findByTextLike(String text); -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/repository/ProfileRepository.java b/src/main/java/com/webproglabs/lab1/lab34/repository/ProfileRepository.java deleted file mode 100644 index 0f0be17..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/repository/ProfileRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.webproglabs.lab1.lab34.repository; - -import com.webproglabs.lab1.lab34.model.Post; -import com.webproglabs.lab1.lab34.model.Profile; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -public interface ProfileRepository extends JpaRepository { - List findByLoginLike(String login); - Profile findOneByLoginIgnoreCase(String login); -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/services/CommentService.java b/src/main/java/com/webproglabs/lab1/lab34/services/CommentService.java deleted file mode 100644 index f6af98a..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/services/CommentService.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.webproglabs.lab1.lab34.services; - -import com.webproglabs.lab1.lab34.model.Comment; -import com.webproglabs.lab1.lab34.model.Post; -import com.webproglabs.lab1.lab34.model.Profile; -import com.webproglabs.lab1.lab34.repository.CommentRepository; -import com.webproglabs.lab1.lab34.repository.PostRepository; -import com.webproglabs.lab1.lab34.repository.ProfileRepository; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import javax.persistence.EntityNotFoundException; -import javax.transaction.Transactional; -import java.util.List; -import java.util.Optional; - -@Service -public class CommentService { - - private final ProfileRepository profileRepository; - private final CommentRepository commentRepository; - - private final PostRepository postRepository; - - public CommentService(ProfileRepository profileRepository, CommentRepository commentRepository, PostRepository postRepository) { - this.profileRepository = profileRepository; - this.commentRepository = commentRepository; - this.postRepository = postRepository; - } - - @Transactional - public Comment findComment(Long id) { - final Optional comment = commentRepository.findById(id); - return comment.orElseThrow(EntityNotFoundException::new); - } - - @Transactional - public List findAllComments() { - return commentRepository.findAll(); - } - - @Transactional - public List findFilteredComments(String filter) { - List postList = postRepository.findByTextLike("%" + filter + "%"); - List commentList = commentRepository.findByTextLike("%" + filter + "%"); - List allPosts = postRepository.findAll(); - for(Post post : allPosts) { - for (Comment comm : commentList) { - if (post.getComments().contains(comm) && !(postList.contains(post))) { - postList.add(post); - } - } - } - return postList; - } - - @Transactional - public Comment addComment(String text, Long profileId, Long postId) { - if (!StringUtils.hasText(text)) { - throw new IllegalArgumentException("Comment data is null or empty"); - } - try{ - Profile user = profileRepository.findById(profileId).get(); - Post post = postRepository.findById(postId).get(); - Comment comment = new Comment(text, user, post); - user.addComment(comment); - post.addComment(comment); - profileRepository.save(user); - postRepository.save(post); - return commentRepository.save(comment); - } - catch (Exception exception) { - return null; - } - } - - @Transactional - public Comment updateComment(Long id, String text) { - if (!StringUtils.hasText(text)) { - throw new IllegalArgumentException("Comment data is null or empty"); - } - Comment currentComment = findComment(id); - currentComment.setText(text); - final Profile owner = currentComment.getOwner(); - profileRepository.save(owner); - final Post post = currentComment.getPost(); - postRepository.save(post); - return commentRepository.save(currentComment); - } - - @Transactional - public Comment deleteComment(Long id) { - final Comment currentComment = findComment(id); - commentRepository.delete(currentComment); - return currentComment; - } - @Transactional - public void deleteAllComments() { - commentRepository.deleteAll(); - } - -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/services/PostService.java b/src/main/java/com/webproglabs/lab1/lab34/services/PostService.java deleted file mode 100644 index 5b4abf7..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/services/PostService.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.webproglabs.lab1.lab34.services; - -import com.webproglabs.lab1.lab34.model.Comment; -import com.webproglabs.lab1.lab34.model.Post; -import com.webproglabs.lab1.lab34.model.Profile; -import com.webproglabs.lab1.lab34.repository.CommentRepository; -import com.webproglabs.lab1.lab34.repository.PostRepository; -import com.webproglabs.lab1.lab34.repository.ProfileRepository; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import javax.persistence.EntityNotFoundException; -import javax.transaction.Transactional; -import java.util.List; -import java.util.Optional; - -@Service -public class PostService { - private final PostRepository postRepository; - private final CommentRepository commentRepository; - private final ProfileRepository profileRepository; - - public PostService(PostRepository postRepository, CommentRepository commentRepository, ProfileRepository profileRepository) { - this.postRepository = postRepository; - this.commentRepository = commentRepository; - this.profileRepository = profileRepository; - } - - @Transactional - public Post findPost(Long id) { - final Optional post = postRepository.findById(id); - return post.orElseThrow(EntityNotFoundException::new); - } - - @Transactional - public List findAllPosts() { - return postRepository.findAll(); - } - - @Transactional - public List findFilteredPosts(String filter) { - List postList = postRepository.findByTextLike("%" + filter + "%"); - List commentList = commentRepository.findByTextLike("%" + filter + "%"); - List allPosts = postRepository.findAll(); - for(Post post : allPosts) { - for (Comment comm : commentList) { - if (post.getComments().contains(comm) && !(postList.contains(post))) { - postList.add(post); - } - } - } - return postList; - } - - @Transactional - public Post addPost (String text, List comments, Long authorId) { - if (!StringUtils.hasText(text)) { - throw new IllegalArgumentException("Post data is null or empty"); - } - Profile author = profileRepository.findById(authorId).get(); - Post post = new Post(text, author, comments); - author.addPost(post); - profileRepository.save(author); - return postRepository.save(post); - } - - @Transactional - public Post updatePost(Long id, String text) { - if (!StringUtils.hasText(text)) { - throw new IllegalArgumentException("Post data is null or empty"); - } - final Post currentPost = findPost(id); - currentPost.setText(text); - final Profile author = currentPost.getAuthor(); - profileRepository.save(author); - return postRepository.save(currentPost); - } - - @Transactional - public Post deletePost(Long id) { - final Post currentPost = findPost(id); - postRepository.delete(currentPost); - return currentPost; - } - - @Transactional - public void deleteAllPosts() { - postRepository.deleteAll(); - } -} diff --git a/src/main/java/com/webproglabs/lab1/lab34/services/ProfileService.java b/src/main/java/com/webproglabs/lab1/lab34/services/ProfileService.java deleted file mode 100644 index d205366..0000000 --- a/src/main/java/com/webproglabs/lab1/lab34/services/ProfileService.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.webproglabs.lab1.lab34.services; - -import com.webproglabs.lab1.lab34.controller.ProfileDto; -import com.webproglabs.lab1.lab34.jwt.JwtException; -import com.webproglabs.lab1.lab34.jwt.JwtProvider; -import com.webproglabs.lab1.lab34.model.Comment; -import com.webproglabs.lab1.lab34.model.Post; -import com.webproglabs.lab1.lab34.model.Profile; -import com.webproglabs.lab1.lab34.model.UserRole; -import com.webproglabs.lab1.lab34.repository.ProfileRepository; -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.util.StringUtils; - -import javax.persistence.EntityNotFoundException; -import javax.transaction.Transactional; -import java.util.*; - -@Service -public class ProfileService implements UserDetailsService { - - private final ProfileRepository profileRepository; - private final PasswordEncoder passwordEncoder; - - private final JwtProvider jwtProvider; - - public ProfileService(ProfileRepository profileRepository, PasswordEncoder passwordEncoder, JwtProvider jwtProvider) { - this.profileRepository = profileRepository; - this.passwordEncoder = passwordEncoder; - this.jwtProvider = jwtProvider; - } - - @Transactional - public Profile findUser(Long id) { - final Optional profile = profileRepository.findById(id); - return profile.orElseThrow(EntityNotFoundException::new); - } - - @Transactional - public Profile findUserByLogin(String login) { - final Optional profile = profileRepository.findByLoginLike(login).stream().findFirst(); - return profile.orElseThrow(EntityNotFoundException::new); - } - - @Transactional - public List findAllUsers() { - return profileRepository.findAll(); - } - - @Transactional - public Profile addUser(String login, String password, List comments, List posts) { - if (!StringUtils.hasText(login) || !StringUtils.hasText(password)) { - throw new IllegalArgumentException("User data is null or empty"); - } - final Profile user = new Profile(login, password, comments, posts, UserRole.USER); - return profileRepository.save(user); - } - - @Transactional - public Profile addUser(String login, String password, List comments, List posts, UserRole role) { - if (!StringUtils.hasText(login) || !StringUtils.hasText(password)) { - throw new IllegalArgumentException("User data is null or empty"); - } - final Profile user = new Profile(login, password, comments, posts, role); - return profileRepository.save(user); - } - - @Transactional - public Profile createUser(String login, String password, String passwordConfirm) throws Exception { - if (findByLogin(login) != null) { - throw new Exception("User " + login + " already exists"); - } - final Profile user = new Profile(login, passwordEncoder.encode(password), new ArrayList<>(), new ArrayList<>(), UserRole.USER); - if (!Objects.equals(password, passwordConfirm)) { - throw new Exception("Passwords not equals"); - } - return profileRepository.save(user); - } - - @Transactional - public Profile createUser(String login, String password, String passwordConfirm, UserRole role) throws Exception { - if (findByLogin(login) != null) { - throw new Exception("User " + login + " already exists"); - } - final Profile user = new Profile(login, passwordEncoder.encode(password), new ArrayList<>(), new ArrayList<>(), role); - if (!Objects.equals(password, passwordConfirm)) { - throw new Exception("Passwords not equals"); - } - return profileRepository.save(user); - } - - @Transactional - public Profile updateUser(Long id, String login, String password) { - if (!StringUtils.hasText(login) || !StringUtils.hasText(password)) { - throw new IllegalArgumentException("User data is null or empty"); - } - final Profile currentUser = findUser(id); - currentUser.setLogin(login); - currentUser.setPassword(password); - return profileRepository.save(currentUser); - } - - @Transactional - public Profile deleteUser(Long id) { - final Profile currentUser = findUser(id); - profileRepository.delete(currentUser); - return currentUser; - } - - @Transactional - public void deleteAllUsers() { - profileRepository.deleteAll(); - } - - public Profile findByLogin(String login) { - return profileRepository.findOneByLoginIgnoreCase(login); - } - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - final Profile 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 String loginAndGetToken(ProfileDto userDto) { - - try { - final Profile user = findByLogin(userDto.getLogin()); - if (user == null) { - throw new Exception("Login not found" + userDto.getLogin()); - } - if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) { - throw new Exception("User not found" + user.getLogin()); - } - return jwtProvider.generateToken(user.getLogin()); - } - catch (Exception e) { - var ex = e; - return null; - } - - } - - 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); - } -} diff --git a/src/main/resources/templates/commentModal.html b/src/main/resources/templates/commentModal.html deleted file mode 100644 index a09c141..0000000 --- a/src/main/resources/templates/commentModal.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - -
- - - - - -
- - \ No newline at end of file diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html deleted file mode 100644 index 119f8f7..0000000 --- a/src/main/resources/templates/default.html +++ /dev/null @@ -1,46 +0,0 @@ - - -> - - - Лабораторная работа 5 - - - - - - - - - - - -
-

Лабораторная работа 5

-
- - -
-
-
- - - \ No newline at end of file diff --git a/src/main/resources/templates/editCommentModal.html b/src/main/resources/templates/editCommentModal.html deleted file mode 100644 index 7b2bdba..0000000 --- a/src/main/resources/templates/editCommentModal.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - -
- - - - -
- - \ No newline at end of file diff --git a/src/main/resources/templates/editPostModal.html b/src/main/resources/templates/editPostModal.html deleted file mode 100644 index 07de419..0000000 --- a/src/main/resources/templates/editPostModal.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - -
- - - -
- - - - \ No newline at end of file diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html deleted file mode 100644 index 9d66499..0000000 --- a/src/main/resources/templates/error.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/feed.html b/src/main/resources/templates/feed.html deleted file mode 100644 index 3bb2e58..0000000 --- a/src/main/resources/templates/feed.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - -
-
- - - - - - - - - - - - - - -
- - -
-
- - - - \ No newline at end of file diff --git a/src/main/resources/templates/feedPosts.html b/src/main/resources/templates/feedPosts.html deleted file mode 100644 index c21453a..0000000 --- a/src/main/resources/templates/feedPosts.html +++ /dev/null @@ -1,106 +0,0 @@ - - - - - -
- -
-

-
-
- - Лента - -
- -
- - -
- - -
-
-

-
-
- Автор: - -
-
-
- -
-
- -
-
-
-
- -
-
-

Комментарии:

-
-

-
-

- -
-
- -
-
- -
-
- -
-
-
-
-
- -
- -
- - - - - -
- - -
- - - \ No newline at end of file diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html deleted file mode 100644 index 5c9f583..0000000 --- a/src/main/resources/templates/login.html +++ /dev/null @@ -1,30 +0,0 @@ - - - -
-
- Пользователь не найден или пароль указан не верно -
-
- Выход успешно произведен -
-
- Пользователь '' успешно создан -
-
-
- -
-
- -
- - Регистрация -
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/profilePage.html b/src/main/resources/templates/profilePage.html deleted file mode 100644 index 5715542..0000000 --- a/src/main/resources/templates/profilePage.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - -
- -
-
-

Профиль

-

-

Список постов пользователя:

- -
-
-

-
-
-

- Нет постов -

-
-
- -
- - \ No newline at end of file diff --git a/src/main/resources/templates/profiles.html b/src/main/resources/templates/profiles.html deleted file mode 100644 index 8dce0b9..0000000 --- a/src/main/resources/templates/profiles.html +++ /dev/null @@ -1,56 +0,0 @@ - - - - - -
- -
-
-
-

Профиль

-

-

Список постов пользователя:

- -
-
-

-
-
-

- Нет постов -

-
-
- -
-
-
-
-
- - - -
- - \ No newline at end of file diff --git a/src/main/resources/templates/signup.html b/src/main/resources/templates/signup.html deleted file mode 100644 index 8cd75f5..0000000 --- a/src/main/resources/templates/signup.html +++ /dev/null @@ -1,28 +0,0 @@ - - - -
-
-
-
- -
-
- -
-
- -
-
- - Назад -
-
-
- - \ No newline at end of file