From 1cb7bb2e7974ff743a8a5ab9e58769a919f655c3 Mon Sep 17 00:00:00 2001 From: Nho Quy Dinh Date: Sun, 17 Mar 2024 11:21:31 +0100 Subject: [PATCH 1/6] Update to Spring Boot 3.2.3 --- pom.xml | 17 +- .../alovoa/config/SecurityConfig.java | 344 +++++++++--------- .../com/nonononoki/alovoa/entity/User.java | 6 +- .../entity/user/UserVerificationPicture.java | 6 +- .../alovoa/repo/UserRepository.java | 4 +- .../alovoa/rest/MessageController.java | 3 +- .../alovoa/rest/NotificationController.java | 26 -- .../alovoa/rest/UserController.java | 7 +- .../alovoa/service/AuthService.java | 2 +- .../alovoa/service/MessageService.java | 7 +- .../alovoa/service/NotificationService.java | 136 ------- .../alovoa/service/UserService.java | 8 +- src/main/resources/application.properties | 2 +- 13 files changed, 201 insertions(+), 367 deletions(-) delete mode 100644 src/main/java/com/nonononoki/alovoa/rest/NotificationController.java delete mode 100644 src/main/java/com/nonononoki/alovoa/service/NotificationService.java diff --git a/pom.xml b/pom.xml index 6a66732c..c2bbe268 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 3.0.9 + 3.2.3 com.alovoa @@ -16,7 +16,7 @@ Alovoa - 1.8 + 17 @@ -128,13 +128,8 @@ org.bouncycastle - bcprov-jdk15on - 1.70 - - - nl.martijndwars - web-push - 5.1.1 + bcprov-jdk18on + 1.77 com.giffing.bucket4j.spring.boot.starter @@ -250,8 +245,8 @@ org.apache.maven.plugins maven-compiler-plugin - 17 - 17 + 16 + 16 diff --git a/src/main/java/com/nonononoki/alovoa/config/SecurityConfig.java b/src/main/java/com/nonononoki/alovoa/config/SecurityConfig.java index dde4fe0a..95b783f1 100644 --- a/src/main/java/com/nonononoki/alovoa/config/SecurityConfig.java +++ b/src/main/java/com/nonononoki/alovoa/config/SecurityConfig.java @@ -1,9 +1,7 @@ package com.nonononoki.alovoa.config; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - +import com.nonononoki.alovoa.component.*; +import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; @@ -15,6 +13,8 @@ import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -32,170 +32,186 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; -import com.nonononoki.alovoa.component.AuthFilter; -import com.nonononoki.alovoa.component.AuthProvider; -import com.nonononoki.alovoa.component.CustomTokenBasedRememberMeServices; -import com.nonononoki.alovoa.component.CustomUserDetailsService; -import com.nonononoki.alovoa.component.AuthFailureHandler; -import com.nonononoki.alovoa.component.AuthSuccessHandler; - -import lombok.RequiredArgsConstructor; +import java.util.ArrayList; +import java.util.List; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig { - @Value("${app.text.key}") - private String key; - - @Value("${app.login.remember.key}") - private String rememberKey; - - @Autowired - private Environment env; - - @Autowired - private AuthFailureHandler failureHandler; - - @Autowired - private CustomUserDetailsService customUserDetailsService; - - private final AuthenticationConfiguration configuration; - - public static final String ROLE_USER = "ROLE_USER"; - public static final String ROLE_ADMIN = "ROLE_ADMIN"; - public static final String COOKIE_SESSION = "JSESSIONID"; - public static final String COOKIE_REMEMBER = "remember-me"; - - public static String getRoleUser() { - return ROLE_USER; - } - - public static String getRoleAdmin() { - return ROLE_ADMIN; - } - - @Bean - SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - - AuthenticationManagerBuilder authenticationManagerBuilder = http - .getSharedObject(AuthenticationManagerBuilder.class); - authenticationManagerBuilder.authenticationProvider(authProvider()); - - http.authorizeHttpRequests().requestMatchers("/admin").hasAnyAuthority(ROLE_ADMIN).requestMatchers("/admin/**") - .hasAnyAuthority(ROLE_ADMIN).requestMatchers("/css/**").permitAll().requestMatchers("/js/**").permitAll() - .requestMatchers("/img/**").permitAll().requestMatchers("/font/**").permitAll().requestMatchers("/json/**") - .permitAll().requestMatchers("/oauth2/**").permitAll().requestMatchers("/").permitAll().requestMatchers("/login/**") - .permitAll().requestMatchers("/terms-conditions").permitAll().requestMatchers("/imprint").permitAll() - .requestMatchers("/imprint/*").permitAll().requestMatchers("/privacy").permitAll().requestMatchers("/faq") - .permitAll().requestMatchers("/tos").permitAll().requestMatchers("/register").permitAll() - .requestMatchers("/register/**").permitAll().requestMatchers("/captcha/**").permitAll() - .requestMatchers("/donate-list").permitAll().requestMatchers("/donate/received/**").permitAll() - .requestMatchers("/password/**").permitAll().requestMatchers("/favicon.ico").permitAll().requestMatchers("/sw.js") - .permitAll().requestMatchers("/robots.txt").permitAll().requestMatchers("/.well-known/assetlinks.json") - .permitAll().requestMatchers("/text/*").permitAll().requestMatchers("/manifest/**").permitAll() - .requestMatchers("/fonts/**").permitAll().requestMatchers("/error").permitAll().requestMatchers("/info").permitAll() - .requestMatchers("/user/delete-account-confirm").permitAll().requestMatchers("/delete-account/*").permitAll() - - .anyRequest().authenticated().and().formLogin().loginPage("/login").and().logout() - .deleteCookies(COOKIE_SESSION, COOKIE_REMEMBER).logoutUrl("/logout").logoutSuccessUrl("/?logout").and() - .oauth2Login().loginPage("/login").defaultSuccessUrl("/login/oauth2/success").and() - .addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class).rememberMe() - .rememberMeServices(oAuthRememberMeServices()).key(rememberKey); - - http.sessionManagement().maximumSessions(10).expiredSessionStrategy(getSessionInformationExpiredStrategy()) - .sessionRegistry(sessionRegistry()); - http.securityContext((securityContext) -> securityContext.requireExplicitSave(false)); - - http.csrf().disable(); - - if (env.acceptsProfiles(Profiles.of("prod"))) { - http.requiresChannel().anyRequest().requiresSecure(); - } - - http.cors(); - return http.build(); - } - - @Bean - AuthenticationManager authenticationManager() throws Exception { - return configuration.getAuthenticationManager(); - } - - @Bean - AuthSuccessHandler successHandler() { - return new AuthSuccessHandler(this); - } - - @Bean - AuthFilter authenticationFilter() throws Exception { - AuthFilter filter = new AuthFilter(); - filter.setAuthenticationManager(authenticationManager()); - filter.setAuthenticationSuccessHandler(successHandler()); - filter.setAuthenticationFailureHandler(failureHandler); - filter.setRememberMeServices(rememberMeServices()); - filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy()); - return filter; - } - - // https://stackoverflow.com/questions/32463022/sessionregistry-is-empty-when-i-use-concurrentsessioncontrolauthenticationstrate - public SessionAuthenticationStrategy sessionAuthenticationStrategy() { - List stratList = new ArrayList<>(); - SessionFixationProtectionStrategy concStrat = new SessionFixationProtectionStrategy(); - stratList.add(concStrat); - RegisterSessionAuthenticationStrategy regStrat = new RegisterSessionAuthenticationStrategy(sessionRegistry()); - stratList.add(regStrat); - CompositeSessionAuthenticationStrategy compStrat = new CompositeSessionAuthenticationStrategy(stratList); - return compStrat; - } - - public SessionInformationExpiredStrategy getSessionInformationExpiredStrategy() { - SessionInformationExpiredStrategy strat = new SimpleRedirectSessionInformationExpiredStrategy("/logout"); - return strat; - } - - @Bean - SessionRegistry sessionRegistry() { - return new SessionRegistryImpl(); - } - - @Bean - TokenBasedRememberMeServices rememberMeServices() { - return new TokenBasedRememberMeServices(rememberKey, customUserDetailsService); - } - - @Bean - TokenBasedRememberMeServices oAuthRememberMeServices() { - CustomTokenBasedRememberMeServices rememberMeService = new CustomTokenBasedRememberMeServices(rememberKey, - customUserDetailsService); - rememberMeService.setAlwaysRemember(true); - return rememberMeService; - } - - @Bean - PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - AuthProvider authProvider() { - return new AuthProvider(); - } - - @Bean - CorsFilter corsFilter() { - final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - final CorsConfiguration config = new CorsConfiguration(); - config.setAllowCredentials(true); - config.setAllowedOriginPatterns(Arrays.asList("*")); - config.setAllowedHeaders(Arrays.asList("*")); - config.setAllowedMethods(Arrays.asList("*")); - source.registerCorsConfiguration("/**", config); - return new CorsFilter(source); - } - - public CustomTokenBasedRememberMeServices getOAuthRememberMeServices() { - return (CustomTokenBasedRememberMeServices) oAuthRememberMeServices(); - } + @Value("${app.text.key}") + private String key; + + @Value("${app.login.remember.key}") + private String rememberKey; + + @Autowired + private Environment env; + + @Autowired + private AuthFailureHandler failureHandler; + + @Autowired + private CustomUserDetailsService customUserDetailsService; + + private final AuthenticationConfiguration configuration; + + public static final String ROLE_USER = "ROLE_USER"; + public static final String ROLE_ADMIN = "ROLE_ADMIN"; + public static final String COOKIE_SESSION = "JSESSIONID"; + public static final String COOKIE_REMEMBER = "remember-me"; + + public static String getRoleUser() { + return ROLE_USER; + } + + public static String getRoleAdmin() { + return ROLE_ADMIN; + } + + @Bean + SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + AuthenticationManagerBuilder authenticationManagerBuilder = http + .getSharedObject(AuthenticationManagerBuilder.class); + authenticationManagerBuilder.authenticationProvider(authProvider()); + + http.authorizeHttpRequests(auth -> auth + .requestMatchers("/admin").hasAnyAuthority(ROLE_ADMIN) + .requestMatchers("/admin/**").hasAnyAuthority(ROLE_ADMIN) + .requestMatchers("/css/**").permitAll() + .requestMatchers("/js/**").permitAll() + .requestMatchers("/img/**").permitAll() + .requestMatchers("/font/**").permitAll() + .requestMatchers("/json/**").permitAll() + .requestMatchers("/oauth2/**").permitAll() + .requestMatchers("/").permitAll() + .requestMatchers("/login/**").permitAll() + .requestMatchers("/terms-conditions").permitAll() + .requestMatchers("/imprint").permitAll() + .requestMatchers("/imprint/*").permitAll() + .requestMatchers("/privacy").permitAll() + .requestMatchers("/faq").permitAll() + .requestMatchers("/tos").permitAll() + .requestMatchers("/register").permitAll() + .requestMatchers("/register/**").permitAll() + .requestMatchers("/captcha/**").permitAll() + .requestMatchers("/donate-list").permitAll() + .requestMatchers("/donate/received/**").permitAll() + .requestMatchers("/password/**").permitAll() + .requestMatchers("/favicon.ico").permitAll() + .requestMatchers("/sw.js").permitAll() + .requestMatchers("/robots.txt").permitAll() + .requestMatchers("/.well-known/assetlinks.json").permitAll() + .requestMatchers("/text/*").permitAll() + .requestMatchers("/manifest/**").permitAll() + .requestMatchers("/fonts/**").permitAll() + .requestMatchers("/error").permitAll() + .requestMatchers("/info").permitAll() + .requestMatchers("/user/delete-account-confirm").permitAll() + .requestMatchers("/delete-account/*").permitAll() + .anyRequest().authenticated() + ) + .csrf(AbstractHttpConfigurer::disable) + .formLogin(formLogin -> formLogin + .loginPage("/login") + .permitAll() + ).logout(logout -> + logout.deleteCookies("remove") + .invalidateHttpSession(true) + .deleteCookies(COOKIE_SESSION, COOKIE_REMEMBER) + .logoutUrl("/logout") + .logoutSuccessUrl("/?logout") + ).oauth2Login(login -> login.loginPage("/login").defaultSuccessUrl("/login/oauth2/success")) + .addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class) + .rememberMe(remember -> remember.rememberMeServices(oAuthRememberMeServices()).key(rememberKey)) + .sessionManagement(session -> session.maximumSessions(10).expiredSessionStrategy(getSessionInformationExpiredStrategy()) + .sessionRegistry(sessionRegistry())) + .securityContext((securityContext) -> securityContext.requireExplicitSave(false)); + + if (env.acceptsProfiles(Profiles.of("prod"))) { + http.requiresChannel(channel -> channel.anyRequest().requiresSecure()); + } + return http.build(); + } + + @Bean + AuthenticationManager authenticationManager() throws Exception { + return configuration.getAuthenticationManager(); + } + + @Bean + AuthSuccessHandler successHandler() { + return new AuthSuccessHandler(this); + } + + @Bean + AuthFilter authenticationFilter() throws Exception { + AuthFilter filter = new AuthFilter(); + filter.setAuthenticationManager(authenticationManager()); + filter.setAuthenticationSuccessHandler(successHandler()); + filter.setAuthenticationFailureHandler(failureHandler); + filter.setRememberMeServices(rememberMeServices()); + filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy()); + return filter; + } + + // https://stackoverflow.com/questions/32463022/sessionregistry-is-empty-when-i-use-concurrentsessioncontrolauthenticationstrate + public SessionAuthenticationStrategy sessionAuthenticationStrategy() { + List stratList = new ArrayList<>(); + SessionFixationProtectionStrategy concStrat = new SessionFixationProtectionStrategy(); + stratList.add(concStrat); + RegisterSessionAuthenticationStrategy regStrat = new RegisterSessionAuthenticationStrategy(sessionRegistry()); + stratList.add(regStrat); + return new CompositeSessionAuthenticationStrategy(stratList); + } + + public SessionInformationExpiredStrategy getSessionInformationExpiredStrategy() { + return new SimpleRedirectSessionInformationExpiredStrategy("/logout"); + } + + @Bean + SessionRegistry sessionRegistry() { + return new SessionRegistryImpl(); + } + + @Bean + TokenBasedRememberMeServices rememberMeServices() { + return new TokenBasedRememberMeServices(rememberKey, customUserDetailsService); + } + + @Bean + TokenBasedRememberMeServices oAuthRememberMeServices() { + CustomTokenBasedRememberMeServices rememberMeService = new CustomTokenBasedRememberMeServices(rememberKey, + customUserDetailsService); + rememberMeService.setAlwaysRemember(true); + return rememberMeService; + } + + @Bean + PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + AuthProvider authProvider() { + return new AuthProvider(); + } + + @Bean + CorsFilter corsFilter() { + final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + final CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + config.setAllowedOriginPatterns(List.of("*")); + config.setAllowedHeaders(List.of("*")); + config.setAllowedMethods(List.of("*")); + source.registerCorsConfiguration("/**", config); + return new CorsFilter(source); + } + + public CustomTokenBasedRememberMeServices getOAuthRememberMeServices() { + return (CustomTokenBasedRememberMeServices) oAuthRememberMeServices(); + } } \ No newline at end of file diff --git a/src/main/java/com/nonononoki/alovoa/entity/User.java b/src/main/java/com/nonononoki/alovoa/entity/User.java index 1516f34a..a0be7809 100644 --- a/src/main/java/com/nonononoki/alovoa/entity/User.java +++ b/src/main/java/com/nonononoki/alovoa/entity/User.java @@ -171,10 +171,12 @@ public class User implements UserDetails { @OneToMany(orphanRemoval = true, mappedBy = "userTo") @JsonIgnore private List reportedByUsers; - @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}, mappedBy = "userNo") + @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) + @JoinTable @JsonIgnore private List verificationNo; - @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}, mappedBy = "userYes") + @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) + @JoinTable @JsonIgnore private List verificationYes; @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) diff --git a/src/main/java/com/nonononoki/alovoa/entity/user/UserVerificationPicture.java b/src/main/java/com/nonononoki/alovoa/entity/user/UserVerificationPicture.java index f9588a2b..8ee6c1ca 100644 --- a/src/main/java/com/nonononoki/alovoa/entity/user/UserVerificationPicture.java +++ b/src/main/java/com/nonononoki/alovoa/entity/user/UserVerificationPicture.java @@ -30,12 +30,10 @@ public class UserVerificationPicture { @ManyToOne private User user; - @ManyToMany - @JoinColumn + @ManyToMany(mappedBy = "verificationYes") private List userYes; - @ManyToMany - @JoinColumn + @ManyToMany(mappedBy = "verificationNo") private List userNo; @Column(columnDefinition = "mediumtext") diff --git a/src/main/java/com/nonononoki/alovoa/repo/UserRepository.java b/src/main/java/com/nonononoki/alovoa/repo/UserRepository.java index 8b9eebc8..154defd8 100644 --- a/src/main/java/com/nonononoki/alovoa/repo/UserRepository.java +++ b/src/main/java/com/nonononoki/alovoa/repo/UserRepository.java @@ -30,7 +30,7 @@ default List usersSearch(UserSearchRequest request, Pageable page) { + "u.locationLatitude IS NOT NULL AND u.locationLongitude IS NOT NULL AND u.profilePicture IS NOT NULL " + "AND TIMESTAMPDIFF(YEAR, u.dates.dateOfBirth, CURDATE()) + u.preferedMaxAge >= :age AND TIMESTAMPDIFF(YEAR, u.dates.dateOfBirth, CURDATE()) + u.preferedMinAge <= :age AND u.dates.dateOfBirth >= :minDate AND u.dates.dateOfBirth <= :maxDate " + "AND u.locationLatitude BETWEEN :latitudeFrom AND :latitudeTo AND u.locationLongitude BETWEEN :longitudeFrom AND :longitudeTo " - + "AND u.intention.id = CASE WHEN :intentionId < 0 THEN 1=1 ELSE :intentionId END " + + "AND CASE WHEN :intentionId < 0 THEN 1=1 ELSE :intentionId = u.intention.id END " + "AND u.id NOT IN (:likeIds) AND u.id NOT IN (:likeIds) AND u.id NOT IN (:hideIds) " + "AND u.id NOT IN (:blockIds) AND u.gender.id IN (:genderIds)") List usersSearchQuery(@Param("age") int age, @Param("minDate") Date minDate, @Param("maxDate") Date maxDate, @@ -50,7 +50,7 @@ default List usersSearchAllIgnoreLocation(UserSearchRequest request, Pagea @Query(value = "SELECT u FROM User u WHERE u.disabled = FALSE AND u.admin = FALSE AND u.confirmed = TRUE AND u.intention IS NOT NULL AND " + "u.locationLatitude IS NOT NULL AND u.locationLongitude IS NOT NULL AND u.profilePicture IS NOT NULL " + "AND TIMESTAMPDIFF(YEAR, u.dates.dateOfBirth, CURDATE()) + u.preferedMaxAge >= :age AND TIMESTAMPDIFF(YEAR, u.dates.dateOfBirth, CURDATE()) + u.preferedMinAge <= :age AND u.dates.dateOfBirth >= :minDate AND u.dates.dateOfBirth <= :maxDate " - + "AND u.intention.id = CASE WHEN :intentionId < 0 THEN 1=1 ELSE :intentionId END " + + "AND CASE WHEN :intentionId < 0 THEN 1=1 ELSE :intentionId = u.intention.id END " + "AND u.id NOT IN (:likeIds) AND u.id NOT IN (:likeIds) AND u.id NOT IN (:hideIds) " + "AND u.id NOT IN (:blockIds) AND u.gender.id IN (:genderIds)") List usersSearchIgnoreLocation(@Param("age") int age, @Param("minDate") Date minDate, @Param("maxDate") Date maxDate, diff --git a/src/main/java/com/nonononoki/alovoa/rest/MessageController.java b/src/main/java/com/nonononoki/alovoa/rest/MessageController.java index 8d97ed6c..c8840a35 100644 --- a/src/main/java/com/nonononoki/alovoa/rest/MessageController.java +++ b/src/main/java/com/nonononoki/alovoa/rest/MessageController.java @@ -5,7 +5,6 @@ import java.util.Date; import java.util.List; -import org.jose4j.lang.JoseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ConcurrentModel; @@ -43,7 +42,7 @@ public class MessageController { @ResponseBody @PostMapping(value = "/send/{convoId}", consumes = "text/plain") public void send(@RequestBody String msg, @PathVariable long convoId) - throws AlovoaException, GeneralSecurityException, IOException, JoseException { + throws AlovoaException, GeneralSecurityException, IOException { messageService.send(convoId, msg); } diff --git a/src/main/java/com/nonononoki/alovoa/rest/NotificationController.java b/src/main/java/com/nonononoki/alovoa/rest/NotificationController.java deleted file mode 100644 index 8add5d14..00000000 --- a/src/main/java/com/nonononoki/alovoa/rest/NotificationController.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.nonononoki.alovoa.rest; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import com.nonononoki.alovoa.model.AlovoaException; -import com.nonononoki.alovoa.model.WebPushDto; -import com.nonononoki.alovoa.service.NotificationService; - -@RestController -@RequestMapping("/notification") -public class NotificationController { - - @Autowired - private NotificationService notificationService; - - @ResponseBody - @PostMapping(value = "/subscribe") - public void subscribe(@RequestBody WebPushDto webPush) throws AlovoaException { - notificationService.subscribe(WebPushDto.toEntity(webPush)); - } -} diff --git a/src/main/java/com/nonononoki/alovoa/rest/UserController.java b/src/main/java/com/nonononoki/alovoa/rest/UserController.java index 433b8ec9..1e72cfc2 100644 --- a/src/main/java/com/nonononoki/alovoa/rest/UserController.java +++ b/src/main/java/com/nonononoki/alovoa/rest/UserController.java @@ -4,11 +4,9 @@ import com.nonononoki.alovoa.Tools; import com.nonononoki.alovoa.entity.user.UserImage; import com.nonononoki.alovoa.entity.user.UserMiscInfo; -import com.nonononoki.alovoa.entity.user.UserPrompt; import com.nonononoki.alovoa.model.*; import com.nonononoki.alovoa.service.UserService; import jakarta.mail.MessagingException; -import org.jose4j.lang.JoseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; @@ -193,14 +191,13 @@ public void deleteImage(@PathVariable long imageId) throws AlovoaException { } @PostMapping(value = "/like/{idEnc}") - public void likeUser(@PathVariable String idEnc) throws AlovoaException, GeneralSecurityException, IOException, - JoseException { + public void likeUser(@PathVariable String idEnc) throws AlovoaException, GeneralSecurityException, IOException { userService.likeUser(idEnc, null); } @PostMapping(value = "/like/{idEnc}/{message}") public void likeUser(@PathVariable String idEnc, @PathVariable String message) throws AlovoaException, - GeneralSecurityException, IOException, JoseException { + GeneralSecurityException, IOException { userService.likeUser(idEnc, message); } diff --git a/src/main/java/com/nonononoki/alovoa/service/AuthService.java b/src/main/java/com/nonononoki/alovoa/service/AuthService.java index 9919166d..2cb071ba 100644 --- a/src/main/java/com/nonononoki/alovoa/service/AuthService.java +++ b/src/main/java/com/nonononoki/alovoa/service/AuthService.java @@ -45,7 +45,7 @@ public User getCurrentUser(boolean throwExceptionWhenNull) throws AlovoaExceptio throw new AlovoaException(ExceptionHandler.USER_NOT_FOUND); } else if (user == null && throwExceptionWhenNull) { //try again - user = userRepo.findByEmail(Tools.cleanEmail(email)); + user = userRepo.findByEmail(Tools.cleanEmail(email)); if (user == null) { throw new AlovoaException(ExceptionHandler.USER_NOT_FOUND); } diff --git a/src/main/java/com/nonononoki/alovoa/service/MessageService.java b/src/main/java/com/nonononoki/alovoa/service/MessageService.java index 1f96e8ac..aaedf37d 100644 --- a/src/main/java/com/nonononoki/alovoa/service/MessageService.java +++ b/src/main/java/com/nonononoki/alovoa/service/MessageService.java @@ -6,7 +6,6 @@ import java.util.Comparator; import java.util.Date; -import org.jose4j.lang.JoseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @@ -34,14 +33,11 @@ public class MessageService { @Autowired private ConversationRepository conversationRepo; - @Autowired - private NotificationService notificationService; - @Autowired private MailService mailService; public void send(Long convoId, String message) - throws AlovoaException, GeneralSecurityException, IOException, JoseException { + throws AlovoaException, GeneralSecurityException, IOException { User currUser = authService.getCurrentUser(true); @@ -91,7 +87,6 @@ public void send(Long convoId, String message) c.setLastUpdated(new Date()); conversationRepo.saveAndFlush(c); - notificationService.newMessage(user); if(user.getUserSettings().isEmailChat()){ mailService.sendChatNotificationMail(currUser, user, message); } diff --git a/src/main/java/com/nonononoki/alovoa/service/NotificationService.java b/src/main/java/com/nonononoki/alovoa/service/NotificationService.java deleted file mode 100644 index 73ab5eae..00000000 --- a/src/main/java/com/nonononoki/alovoa/service/NotificationService.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.nonononoki.alovoa.service; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.spec.InvalidKeySpecException; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -import org.jose4j.lang.JoseException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.MessageSource; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.nonononoki.alovoa.Tools; -import com.nonononoki.alovoa.entity.User; -import com.nonononoki.alovoa.entity.user.UserWebPush; -import com.nonononoki.alovoa.model.AlovoaException; -import com.nonononoki.alovoa.model.WebPushMessage; -import com.nonononoki.alovoa.repo.UserRepository; - -import nl.martijndwars.webpush.Notification; -import nl.martijndwars.webpush.PushAsyncService; - -@Service -public class NotificationService { - - @Value("${app.vapid.public}") - private String vapidPublicKey; - - @Value("${app.vapid.private}") - private String vapidPrivateKey; - - @Value("${app.vapid.max}") - private int vapidMax; - - @Value("${app.domain}") - private String appDomain; - - @Autowired - private AuthService authService; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private MessageSource messageSource; - - @Autowired - private UserRepository userRepo; - - private PushAsyncService pushService; - - public PushAsyncService pushService() - throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { - if (pushService == null) { - pushService = new PushAsyncService(); - pushService.setPrivateKey(vapidPrivateKey); - pushService.setPublicKey(vapidPublicKey); - } - return pushService; - } - - public void subscribe(UserWebPush webPush) throws AlovoaException { - User user = authService.getCurrentUser(true); - webPush.setUser(user); - if (webPush.getDate() == null) { - webPush.setDate(new Date()); - } - user.getWebPush().add(webPush); - user = userRepo.saveAndFlush(user); - - if (user.getWebPush().size() > vapidMax) { - UserWebPush wp = Collections.min(user.getWebPush(), Comparator.comparing(UserWebPush::getDate)); - user.getWebPush().remove(wp); - userRepo.saveAndFlush(user); - } - } - - public void newLike(User user) throws GeneralSecurityException, IOException, JoseException { - user.getDates().setNotificationDate(new Date()); - user = userRepo.saveAndFlush(user); - - Locale locale = Tools.getUserLocale(user); - String title = messageSource.getMessage("backend.webpush.like.message", null, locale); - String msg = messageSource.getMessage("backend.webpush.like.subject", null, locale); - - WebPushMessage message = new WebPushMessage(); - message.setTitle(title); - message.setMessage(msg); - send(user, message); - } - - public void newMatch(User user) throws GeneralSecurityException, IOException, JoseException { - user.getDates().setMessageDate(new Date()); - user = userRepo.saveAndFlush(user); - - Locale locale = Tools.getUserLocale(user); - String title = messageSource.getMessage("backend.webpush.match.message", null, locale); - String msg = messageSource.getMessage("backend.webpush.match.subject", null, locale); - - WebPushMessage message = new WebPushMessage(); - message.setTitle(title); - message.setMessage(msg); - send(user, message); - } - - public void newMessage(User user) throws GeneralSecurityException, IOException, JoseException { - user.getDates().setMessageDate(new Date()); - user = userRepo.saveAndFlush(user); - - Locale locale = Tools.getUserLocale(user); - String title = messageSource.getMessage("backend.webpush.message.message", null, locale); - String msg = messageSource.getMessage("backend.webpush.message.subject", null, locale); - - WebPushMessage message = new WebPushMessage(); - message.setTitle(title); - message.setMessage(msg); - send(user, message); - } - - private void send(User user, WebPushMessage message) throws GeneralSecurityException, IOException, JoseException { - List pushes = user.getWebPush(); - for (UserWebPush uwp : pushes) { - Notification notification = new Notification(uwp.getEndPoint(), uwp.getPublicKey(), uwp.getAuth(), - objectMapper.writeValueAsBytes(message)); - pushService().send(notification); - } - } -} diff --git a/src/main/java/com/nonononoki/alovoa/service/UserService.java b/src/main/java/com/nonononoki/alovoa/service/UserService.java index 1ae68e62..c4759abb 100644 --- a/src/main/java/com/nonononoki/alovoa/service/UserService.java +++ b/src/main/java/com/nonononoki/alovoa/service/UserService.java @@ -16,7 +16,6 @@ import com.sipgate.mp3wav.Converter; import jakarta.mail.MessagingException; import org.apache.commons.lang3.RandomStringUtils; -import org.jose4j.lang.JoseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -88,8 +87,6 @@ public class UserService { @Autowired private MailService mailService; @Autowired - private NotificationService notificationService; - @Autowired private TextEncryptorConverter textEncryptor; @Autowired private ObjectMapper objectMapper; @@ -648,7 +645,7 @@ private String adjustPicture(String imgB64) throws IOException { return Tools.B64IMAGEPREFIX + fileType + Tools.B64PREFIX + base64bytes; } - public void likeUser(String idEnc, String message) throws AlovoaException, GeneralSecurityException, IOException, JoseException { + public void likeUser(String idEnc, String message) throws AlovoaException, GeneralSecurityException, IOException { User user = encodedIdToUser(idEnc); User currUser = authService.getCurrentUser(true); @@ -686,7 +683,6 @@ public void likeUser(String idEnc, String message) throws AlovoaException, Gener not.setUserTo(user); not.setMessage(message); currUser.getNotifications().add(not); - notificationService.newLike(user); user.getDates().setNotificationDate(new Date()); @@ -707,8 +703,6 @@ public void likeUser(String idEnc, String message) throws AlovoaException, Gener convo.setMessages(new ArrayList<>()); conversationRepo.saveAndFlush(convo); - notificationService.newMatch(user); - user.getConversations().add(convo); currUser.getConversations().add(convo); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e24249d0..6a6fa2fa 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -42,7 +42,7 @@ server.compression.enabled=true server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json,application/xml server.compression.min-response-size=10240 -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDB103Dialect +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect spring.jpa.database-platform=org.hibernate.dialect.MariaDB103Dialect spring.jpa.show-sql=false spring.jpa.generate-ddl=true From 7225896808267ff0513637895f312e691239a61f Mon Sep 17 00:00:00 2001 From: Nho Quy Dinh Date: Sun, 17 Mar 2024 11:26:32 +0100 Subject: [PATCH 2/6] Fix tests --- .../alovoa/service/MailServiceTest.java | 3 +- .../service/NotificationServiceTest.java | 116 ------------------ 2 files changed, 1 insertion(+), 118 deletions(-) delete mode 100644 src/test/java/com/nonononoki/alovoa/service/NotificationServiceTest.java diff --git a/src/test/java/com/nonononoki/alovoa/service/MailServiceTest.java b/src/test/java/com/nonononoki/alovoa/service/MailServiceTest.java index 31ea3d4d..8bdd51cf 100644 --- a/src/test/java/com/nonononoki/alovoa/service/MailServiceTest.java +++ b/src/test/java/com/nonononoki/alovoa/service/MailServiceTest.java @@ -9,7 +9,6 @@ import com.nonononoki.alovoa.model.UserDto; import com.nonononoki.alovoa.repo.ConversationRepository; import com.nonononoki.alovoa.repo.UserRepository; -import org.jose4j.lang.JoseException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -105,7 +104,7 @@ void test() throws Exception { @Test - void testLikeMatchAndChatEmails() throws AlovoaException, GeneralSecurityException, JoseException, IOException { + void testLikeMatchAndChatEmails() throws AlovoaException, GeneralSecurityException, IOException { User user1 = testUsers.get(0); User user2 = testUsers.get(1); diff --git a/src/test/java/com/nonononoki/alovoa/service/NotificationServiceTest.java b/src/test/java/com/nonononoki/alovoa/service/NotificationServiceTest.java deleted file mode 100644 index 01712609..00000000 --- a/src/test/java/com/nonononoki/alovoa/service/NotificationServiceTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.nonononoki.alovoa.service; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; - -import java.util.Date; -import java.util.List; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.transaction.annotation.Transactional; - -import com.nonononoki.alovoa.entity.User; -import com.nonononoki.alovoa.entity.user.UserWebPush; -import com.nonononoki.alovoa.repo.ConversationRepository; -import com.nonononoki.alovoa.repo.UserRepository; -import com.nonononoki.alovoa.repo.UserWebPushRepository; - -@SpringBootTest -@ActiveProfiles("test") -@Transactional -class NotificationServiceTest { - - @Autowired - private RegisterService registerService; - - @Autowired - private CaptchaService captchaService; - - @Value("${app.vapid.max}") - private int vapidMax; - - @Value("${app.age.min}") - private int minAge; - - @Value("${app.message.size}") - private int maxMessageSize; - - @Value("${app.first-name.length-max}") - private int firstNameLengthMax; - - @Value("${app.first-name.length-min}") - private int firstNameLengthMin; - - @MockBean - private AuthService authService; - - @MockBean - private MailService mailService; - - @Autowired - private NotificationService notificationService; - - @Autowired - private UserService userService; - - @Autowired - private UserRepository userRepo; - - @Autowired - private ConversationRepository conversationRepo; - - @Autowired - private UserWebPushRepository userWebPushRepository; - - private List testUsers; - - @BeforeEach - void before() throws Exception { - Mockito.when(mailService.sendMail(Mockito.any(String.class), any(String.class), any(String.class), - any(String.class))).thenReturn(true); - testUsers = RegisterServiceTest.getTestUsers(captchaService, registerService, firstNameLengthMax, - firstNameLengthMin); - } - - @AfterEach - void after() throws Exception { - RegisterServiceTest.deleteAllUsers(userService, authService, captchaService, conversationRepo, userRepo); - } - - @Test - void test() throws Exception { - - User user1 = testUsers.get(1); - - Mockito.when(authService.getCurrentUser()).thenReturn(user1); - Mockito.when(authService.getCurrentUser(true)).thenReturn(user1); - - Date oldDate = new Date(); - - UserWebPush wp = new UserWebPush(); - wp.setDate(oldDate); - for (int i = 0; i < vapidMax; i++) { - notificationService.subscribe(wp); - } - assertEquals(vapidMax, userWebPushRepository.count()); - - Date newDate = new Date(); - wp.setDate(newDate); - notificationService.subscribe(wp); - assertEquals(vapidMax, userWebPushRepository.count()); - - user1 = userRepo.findByEmail(user1.getEmail()); - UserWebPush newWebPush = user1.getWebPush().get(vapidMax - 1); - assertEquals(newDate, newWebPush.getDate()); - - } - -} From c5509f7ee54ae2c8cfead0269c4a50d655c846d9 Mon Sep 17 00:00:00 2001 From: Nho Quy Dinh Date: Sun, 17 Mar 2024 11:27:56 +0100 Subject: [PATCH 3/6] Update UserServiceTest.java --- .../java/com/nonononoki/alovoa/service/UserServiceTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/test/java/com/nonononoki/alovoa/service/UserServiceTest.java b/src/test/java/com/nonononoki/alovoa/service/UserServiceTest.java index f657afde..8fa922bd 100644 --- a/src/test/java/com/nonononoki/alovoa/service/UserServiceTest.java +++ b/src/test/java/com/nonononoki/alovoa/service/UserServiceTest.java @@ -10,7 +10,6 @@ import com.nonononoki.alovoa.model.*; import com.nonononoki.alovoa.repo.ConversationRepository; import com.nonononoki.alovoa.repo.UserRepository; -import org.jose4j.lang.JoseException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -84,8 +83,6 @@ class UserServiceTest { private MailService mailService; private List testUsers; @Autowired - private NotificationService notificationService; - @Autowired private MessageService messageService; @BeforeEach From 8a3f50804c6b9aff8fb10d48cd9cc55fbdf7041b Mon Sep 17 00:00:00 2001 From: Nho Quy Dinh Date: Sun, 17 Mar 2024 13:05:44 +0100 Subject: [PATCH 4/6] Update application.properties --- src/main/resources/application.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 6a6fa2fa..5f0cc8c4 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -69,6 +69,7 @@ spring.mail.username=nonononoki@gmx.de spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.test-connection=true +spring.mail.properties.mail.smtp.ssl.checkserveridentity=false # logging logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n From 8aacfd9a57e5944ce84566e24619feaa0e6d64b1 Mon Sep 17 00:00:00 2001 From: Nho Quy Dinh Date: Tue, 19 Mar 2024 17:15:45 +0100 Subject: [PATCH 5/6] Remove Web Push --- .../com/nonononoki/alovoa/entity/User.java | 3 - .../alovoa/entity/user/UserWebPush.java | 38 ---- .../com/nonononoki/alovoa/model/UserGdpr.java | 3 - .../nonononoki/alovoa/model/WebPushDto.java | 36 ---- .../alovoa/model/WebPushMessage.java | 14 -- .../alovoa/repo/UserWebPushRepository.java | 8 - .../alovoa/service/AdminService.java | 1 - .../alovoa/service/RegisterService.java | 1 - .../resources/static/js/lib/notification.js | 169 ------------------ src/main/resources/static/sw.js | 1 - 10 files changed, 274 deletions(-) delete mode 100644 src/main/java/com/nonononoki/alovoa/entity/user/UserWebPush.java delete mode 100644 src/main/java/com/nonononoki/alovoa/model/WebPushDto.java delete mode 100644 src/main/java/com/nonononoki/alovoa/model/WebPushMessage.java delete mode 100644 src/main/java/com/nonononoki/alovoa/repo/UserWebPushRepository.java delete mode 100644 src/main/resources/static/js/lib/notification.js diff --git a/src/main/java/com/nonononoki/alovoa/entity/User.java b/src/main/java/com/nonononoki/alovoa/entity/User.java index a0be7809..83a5c46f 100644 --- a/src/main/java/com/nonononoki/alovoa/entity/User.java +++ b/src/main/java/com/nonononoki/alovoa/entity/User.java @@ -130,9 +130,6 @@ public class User implements UserDetails { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user") @JsonIgnore private List donations; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user") - @JsonIgnore - private List webPush; @OneToMany(cascade = CascadeType.PERSIST, orphanRemoval = true, mappedBy = "userFrom") @JsonIgnore private List messageSent; diff --git a/src/main/java/com/nonononoki/alovoa/entity/user/UserWebPush.java b/src/main/java/com/nonononoki/alovoa/entity/user/UserWebPush.java deleted file mode 100644 index d064dea0..00000000 --- a/src/main/java/com/nonononoki/alovoa/entity/user/UserWebPush.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.nonononoki.alovoa.entity.user; - -import java.util.Date; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.ManyToOne; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.nonononoki.alovoa.entity.User; - -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -@Entity -public class UserWebPush { - - @JsonIgnore - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @JsonIgnore - @ManyToOne - private User user; - - private Date date; - - private String publicKey; - - private String endPoint; - - private String auth; -} diff --git a/src/main/java/com/nonononoki/alovoa/model/UserGdpr.java b/src/main/java/com/nonononoki/alovoa/model/UserGdpr.java index bacdc871..f6fc30b5 100644 --- a/src/main/java/com/nonononoki/alovoa/model/UserGdpr.java +++ b/src/main/java/com/nonononoki/alovoa/model/UserGdpr.java @@ -36,8 +36,6 @@ public class UserGdpr { private Set preferedGenders; private List images; private List prompts; - - // private List webPush; private List donations; private List messageSent; private UserDates dates; @@ -79,7 +77,6 @@ public static UserGdpr userToUserGdpr(User user) { u.setDonations(user.getDonations()); u.setMessageSent(user.getMessageSent()); - // u.setWebPush(user.getWebPush()); u.setDates(user.getDates()); u.setNumberProfileViews(user.getNumberProfileViews()); diff --git a/src/main/java/com/nonononoki/alovoa/model/WebPushDto.java b/src/main/java/com/nonononoki/alovoa/model/WebPushDto.java deleted file mode 100644 index f8a67970..00000000 --- a/src/main/java/com/nonononoki/alovoa/model/WebPushDto.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.nonononoki.alovoa.model; - -import java.util.Date; - -import com.nonononoki.alovoa.entity.User; -import com.nonononoki.alovoa.entity.user.UserWebPush; - -import lombok.Data; - -@Data -public class WebPushDto { - - private Long id; - - private User user; - - private Date date; - - private String publicKey; - - private String endPoint; - - private String auth; - - public static UserWebPush toEntity(WebPushDto dto) { - UserWebPush wp = new UserWebPush(); - wp.setAuth(dto.getAuth()); - wp.setDate(dto.getDate()); - wp.setEndPoint(dto.getEndPoint()); - wp.setId(dto.getId()); - wp.setPublicKey(dto.getPublicKey()); - wp.setUser(dto.getUser()); - return wp; - } - -} diff --git a/src/main/java/com/nonononoki/alovoa/model/WebPushMessage.java b/src/main/java/com/nonononoki/alovoa/model/WebPushMessage.java deleted file mode 100644 index 2a8f50b0..00000000 --- a/src/main/java/com/nonononoki/alovoa/model/WebPushMessage.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.nonononoki.alovoa.model; - -import lombok.Data; - -@Data -public class WebPushMessage { - - private String title; - - private String clickTarget; - - private String message; - -} diff --git a/src/main/java/com/nonononoki/alovoa/repo/UserWebPushRepository.java b/src/main/java/com/nonononoki/alovoa/repo/UserWebPushRepository.java deleted file mode 100644 index eb8100a4..00000000 --- a/src/main/java/com/nonononoki/alovoa/repo/UserWebPushRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.nonononoki.alovoa.repo; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.nonononoki.alovoa.entity.user.UserWebPush; - -public interface UserWebPushRepository extends JpaRepository { -} \ No newline at end of file diff --git a/src/main/java/com/nonononoki/alovoa/service/AdminService.java b/src/main/java/com/nonononoki/alovoa/service/AdminService.java index 9061df2d..004aa812 100644 --- a/src/main/java/com/nonononoki/alovoa/service/AdminService.java +++ b/src/main/java/com/nonononoki/alovoa/service/AdminService.java @@ -189,7 +189,6 @@ public void banUser(String id) throws AlovoaException, NumberFormatException, In user.setProfilePicture(null); user.setVerificationCode(null); user.setVerificationPicture(null); - user.getWebPush().clear(); user.setShowZodiac(false); user.getPrompts().clear(); userRepo.saveAndFlush(user); diff --git a/src/main/java/com/nonononoki/alovoa/service/RegisterService.java b/src/main/java/com/nonononoki/alovoa/service/RegisterService.java index 633e6b09..5d16c0fa 100644 --- a/src/main/java/com/nonononoki/alovoa/service/RegisterService.java +++ b/src/main/java/com/nonononoki/alovoa/service/RegisterService.java @@ -343,7 +343,6 @@ private BaseRegisterDto registerBase(RegisterDto dto, boolean isOauth) throws Al user.setBlockedUsers(new ArrayList<>()); user.setReported(new ArrayList<>()); user.setReportedByUsers(new ArrayList<>()); - user.setWebPush(new ArrayList<>()); user.setPrompts(new ArrayList<>()); user.setNumberProfileViews(0); diff --git a/src/main/resources/static/js/lib/notification.js b/src/main/resources/static/js/lib/notification.js deleted file mode 100644 index 466f0fcf..00000000 --- a/src/main/resources/static/js/lib/notification.js +++ /dev/null @@ -1,169 +0,0 @@ -// https://github.com/naturalprogrammer/webpush-java-demo/blob/master/src/main/resources/static/js/main.js -// Apache 2.0 - -var notificationSubscriptionUrl = '/notification/subscribe'; - -var serviceWorkerName = '/sw.js'; - -var isSubscribed = (Notification.permission == "granted"); -var swRegistration = null; - -$(document).ready(function() { - - if (isSubscribed || !isPushApiSupported()) { - // $('#webpush-button').toggle(); - } else { - $('#webpush-button').toggle(); - $('#webpush-button').click(function(event) { - subscribe(); - }); - } -}); - -function initialiseServiceWorker(callback) { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.register(serviceWorkerName).then(handleSWRegistration); - if(callback) callback(); - } else { - console.log('Service workers aren\'t supported in this browser.'); - disableAndSetBtnMessage('Service workers unsupported'); - if(callback) callback(); - } -}; - -function handleSWRegistration(reg) { - if (reg.installing) { - console.log('Service worker installing'); - } else if (reg.waiting) { - console.log('Service worker installed'); - } else if (reg.active) { - console.log('Service worker active'); - } - - swRegistration = reg; - initialiseState(reg); -} - -// Once the service worker is registered set the initial state -function initialiseState(reg) { - // Are Notifications supported in the service worker? - if (!(reg.showNotification)) { - console.log('Notifications aren\'t supported on service workers.'); - disableAndSetBtnMessage('Notifications unsupported'); - return; - } - - // Check if push messaging is supported - if (!('PushManager' in window)) { - console.log('Push messaging isn\'t supported.'); - disableAndSetBtnMessage('Push messaging unsupported'); - return; - } - - // We need the service worker registration to check for a subscription - navigator.serviceWorker.ready.then(function(reg) { - // Do we already have a push message subscription? - reg.pushManager.getSubscription() - .then(function(subscription) { - - if (!subscription) { - console.log('Not yet subscribed to Push'); - - isSubscribed = false; - makeButtonSubscribable(reg); - } else { - // initialize status, which includes setting UI elements for - // subscribed status - // and updating Subscribers list via push - isSubscribed = true; - makeButtonUnsubscribable(); - } - }) - .catch(function(err) { - console.log('Error during getSubscription()', err); - }); - }); -} - -function subscribe(callback) { - if(!isPushApiSupported() || isSubscribed) { - if(callback) callback(); - } else { - Notification.requestPermission().then(function(status) { - if (status == 'granted') { - initialiseServiceWorker(callback); - } else { - if(callback) callback(); - } - }); - } -} - -function sendSubscriptionToServer(endpoint, key, auth) { - var encodedKey = btoa(String.fromCharCode.apply(null, new Uint8Array(key))); - var encodedAuth = btoa(String.fromCharCode.apply(null, new Uint8Array(auth))); - $.ajax({ - type: 'POST', - url: notificationSubscriptionUrl, - data: JSON.stringify({ publicKey: encodedKey, auth: encodedAuth, endPoint: endpoint }), - contentType: "application/json", - success: function(response) { - console.log('Subscribed successfully! ' + JSON.stringify(response)); - } - }); -} - -function disableAndSetBtnMessage(message) { - $('#webpush-button').toggle(); -} - -function makeButtonSubscribable(reg) { - var subscribeParams = { userVisibleOnly: true }; - - // Setting the public key of our VAPID key pair. - let applicationServerPublicKey = $("#vapidPublicKey").val(); - // console.log(applicationServerPublicKey) - var applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey); - subscribeParams.applicationServerKey = applicationServerKey; - - reg.pushManager.subscribe(subscribeParams) - .then(function(subscription) { - - // Update status to subscribe current user on server, and to - // let - // other users know this user has subscribed - var endpoint = subscription.endpoint; - var key = subscription.getKey('p256dh'); - var auth = subscription.getKey('auth'); - sendSubscriptionToServer(endpoint, key, auth); - isSubscribed = true; - makeButtonUnsubscribable(); - }) - .catch(function(e) { - // A problem occurred with the subscription. - console.log('Unable to subscribe to push.', e); - }); -} - -function makeButtonUnsubscribable() { - $('#webpush-button').toggle(); -} - -function urlB64ToUint8Array(base64String) { - const padding = '='.repeat((4 - base64String.length % 4) % 4); - const base64 = (base64String + padding) - .replace(/\-/g, '+') - .replace(/_/g, '/'); - - const rawData = window.atob(base64); - const outputArray = new Uint8Array(rawData.length); - - for (var i = 0; i < rawData.length; ++i) { - outputArray[i] = rawData.charCodeAt(i); - } - return outputArray; -} - -function isPushApiSupported() { - return 'PushManager' in window; -} \ No newline at end of file diff --git a/src/main/resources/static/sw.js b/src/main/resources/static/sw.js index fcc5944c..d1987c93 100644 --- a/src/main/resources/static/sw.js +++ b/src/main/resources/static/sw.js @@ -21,7 +21,6 @@ const staticAssets = [ '/js/lib/jquery.min.js', '/js/lib/jquery-ui.min.js', '/js/lib/matter.min.js', - '/js/lib/notification.js', '/js/lib/modal-fx.min.js', '/js/tools/check-password.js', From 52661c84b97c6ae070b6cb568470713d4c4a4f58 Mon Sep 17 00:00:00 2001 From: Nho Quy Dinh Date: Tue, 19 Mar 2024 17:24:47 +0100 Subject: [PATCH 6/6] Update UserService.java --- src/main/java/com/nonononoki/alovoa/service/UserService.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/nonononoki/alovoa/service/UserService.java b/src/main/java/com/nonononoki/alovoa/service/UserService.java index c4759abb..2a1fa6d6 100644 --- a/src/main/java/com/nonononoki/alovoa/service/UserService.java +++ b/src/main/java/com/nonononoki/alovoa/service/UserService.java @@ -295,6 +295,9 @@ public UserDeleteToken deleteAccountRequest() throws MessagingException, IOExcep token.setContent(RandomStringUtils.random(tokenLength, 0, 0, true, true, null, new SecureRandom())); token.setDate(currentDate); token.setUser(user); + if(user.getDeleteToken() != null) { + token.setId(user.getDeleteToken().getId()); + } user.setDeleteToken(token); user = userRepo.saveAndFlush(user);