From c5ab024c5040a58dff2e4c76f32ab0608a172eaf Mon Sep 17 00:00:00 2001 From: Minseo Kang Date: Fri, 1 Nov 2024 03:06:15 +0900 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20User=20=EA=B4=80=EB=A0=A8?= =?UTF-8?q?=20=EB=A6=AC=ED=8C=A9=ED=86=A0=EB=A7=81=20(#23)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * :truck: User 엔티티 패키지 이동 * :truck: UserRepository 패키지 이동 * :recycle: 코드 스타일 변경 * :lipstick: 서비스 인터페이스 생성 --- .../gather_back_end/domain/Portfolio.java | 1 - .../domain/PromotionRequest.java | 1 - .../{util/jwt/entity => domain}/User.java | 5 +- .../example/gather_back_end/domain/Work.java | 1 - .../jwt => }/repository/UserRepository.java | 9 +- .../util/config/SecurityConfig.java | 6 +- .../util/jwt/dto/GoogleResponse.java | 8 +- .../gather_back_end/util/jwt/dto/UserDto.java | 2 + .../jwt/handler/CustomSuccessHandler.java | 4 +- .../jwt/service/CustomOAuth2UserService.java | 90 +--------------- .../service/CustomOAuth2UserServiceImpl.java | 101 ++++++++++++++++++ .../util/jwt/util/JwtFilter.java | 9 +- 12 files changed, 125 insertions(+), 112 deletions(-) rename src/main/java/org/example/gather_back_end/{util/jwt/entity => domain}/User.java (92%) rename src/main/java/org/example/gather_back_end/{util/jwt => }/repository/UserRepository.java (58%) create mode 100644 src/main/java/org/example/gather_back_end/util/jwt/service/CustomOAuth2UserServiceImpl.java diff --git a/src/main/java/org/example/gather_back_end/domain/Portfolio.java b/src/main/java/org/example/gather_back_end/domain/Portfolio.java index 8b170ee..9156632 100644 --- a/src/main/java/org/example/gather_back_end/domain/Portfolio.java +++ b/src/main/java/org/example/gather_back_end/domain/Portfolio.java @@ -13,7 +13,6 @@ import lombok.Getter; import lombok.NoArgsConstructor; import org.example.gather_back_end.util.entity.BaseEntity; -import org.example.gather_back_end.util.jwt.entity.User; @Entity @Table(name = "Portfolio") diff --git a/src/main/java/org/example/gather_back_end/domain/PromotionRequest.java b/src/main/java/org/example/gather_back_end/domain/PromotionRequest.java index 9b28ef5..b43deb2 100644 --- a/src/main/java/org/example/gather_back_end/domain/PromotionRequest.java +++ b/src/main/java/org/example/gather_back_end/domain/PromotionRequest.java @@ -17,7 +17,6 @@ import lombok.Getter; import lombok.NoArgsConstructor; import org.example.gather_back_end.util.entity.BaseEntity; -import org.example.gather_back_end.util.jwt.entity.User; // 홍보 요청 내역 @Entity diff --git a/src/main/java/org/example/gather_back_end/util/jwt/entity/User.java b/src/main/java/org/example/gather_back_end/domain/User.java similarity index 92% rename from src/main/java/org/example/gather_back_end/util/jwt/entity/User.java rename to src/main/java/org/example/gather_back_end/domain/User.java index 03512ee..78f3000 100644 --- a/src/main/java/org/example/gather_back_end/util/jwt/entity/User.java +++ b/src/main/java/org/example/gather_back_end/domain/User.java @@ -1,4 +1,4 @@ -package org.example.gather_back_end.util.jwt.entity; +package org.example.gather_back_end.domain; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; @@ -14,9 +14,6 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; -import org.example.gather_back_end.domain.Portfolio; -import org.example.gather_back_end.domain.PromotionRequest; -import org.example.gather_back_end.domain.Work; import org.example.gather_back_end.util.entity.BaseEntity; @Entity diff --git a/src/main/java/org/example/gather_back_end/domain/Work.java b/src/main/java/org/example/gather_back_end/domain/Work.java index 91524c0..15945be 100644 --- a/src/main/java/org/example/gather_back_end/domain/Work.java +++ b/src/main/java/org/example/gather_back_end/domain/Work.java @@ -15,7 +15,6 @@ import lombok.Getter; import lombok.NoArgsConstructor; import org.example.gather_back_end.util.entity.BaseEntity; -import org.example.gather_back_end.util.jwt.entity.User; @Entity @Table(name = "Works") diff --git a/src/main/java/org/example/gather_back_end/util/jwt/repository/UserRepository.java b/src/main/java/org/example/gather_back_end/repository/UserRepository.java similarity index 58% rename from src/main/java/org/example/gather_back_end/util/jwt/repository/UserRepository.java rename to src/main/java/org/example/gather_back_end/repository/UserRepository.java index 19e2bda..0eece1d 100644 --- a/src/main/java/org/example/gather_back_end/util/jwt/repository/UserRepository.java +++ b/src/main/java/org/example/gather_back_end/repository/UserRepository.java @@ -1,11 +1,14 @@ -package org.example.gather_back_end.util.jwt.repository; +package org.example.gather_back_end.repository; -import org.example.gather_back_end.util.jwt.entity.User; +import org.example.gather_back_end.domain.User; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +@Repository public interface UserRepository extends JpaRepository { User findByNickname(String nickname); - User findByUsername(String username); + + } diff --git a/src/main/java/org/example/gather_back_end/util/config/SecurityConfig.java b/src/main/java/org/example/gather_back_end/util/config/SecurityConfig.java index c090c20..ee29aae 100644 --- a/src/main/java/org/example/gather_back_end/util/config/SecurityConfig.java +++ b/src/main/java/org/example/gather_back_end/util/config/SecurityConfig.java @@ -7,7 +7,7 @@ import org.example.gather_back_end.util.exception.AccessDeniedHandler; import org.example.gather_back_end.util.jwt.handler.CustomFailureHandler; import org.example.gather_back_end.util.jwt.handler.CustomSuccessHandler; -import org.example.gather_back_end.util.jwt.service.CustomOAuth2UserService; +import org.example.gather_back_end.util.jwt.service.CustomOAuth2UserServiceImpl; import org.example.gather_back_end.util.jwt.util.JwtFilter; import org.example.gather_back_end.util.jwt.util.JwtUtil; import org.springframework.context.annotation.Bean; @@ -32,7 +32,7 @@ public class SecurityConfig { private final AccessDeniedHandler accessDeniedHandler; - private final CustomOAuth2UserService customOAuth2UserService; + private final CustomOAuth2UserServiceImpl customOAuth2UserServiceImpl; private final CustomSuccessHandler customSuccessHandler; private final JwtUtil jwtUtil; private final CustomFailureHandler customFailureHandler; @@ -72,7 +72,7 @@ public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { .httpBasic(AbstractHttpConfigurer::disable) .addFilterBefore(new JwtFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class) .oauth2Login((oauth2)->oauth2.userInfoEndpoint((userInfoEndpointConfig -> userInfoEndpointConfig - .userService(customOAuth2UserService))) + .userService(customOAuth2UserServiceImpl))) .successHandler(customSuccessHandler) .failureHandler(customFailureHandler) ) diff --git a/src/main/java/org/example/gather_back_end/util/jwt/dto/GoogleResponse.java b/src/main/java/org/example/gather_back_end/util/jwt/dto/GoogleResponse.java index 1d9de38..3504c7d 100644 --- a/src/main/java/org/example/gather_back_end/util/jwt/dto/GoogleResponse.java +++ b/src/main/java/org/example/gather_back_end/util/jwt/dto/GoogleResponse.java @@ -1,15 +1,13 @@ package org.example.gather_back_end.util.jwt.dto; import java.util.Map; +import lombok.RequiredArgsConstructor; -public class GoogleResponse implements OAuth2Response{ +@RequiredArgsConstructor +public class GoogleResponse implements OAuth2Response { private final Map attribute; - public GoogleResponse(Map attribute) { - this.attribute = attribute; - } - @Override public String getProvider() { return "google"; diff --git a/src/main/java/org/example/gather_back_end/util/jwt/dto/UserDto.java b/src/main/java/org/example/gather_back_end/util/jwt/dto/UserDto.java index 3a8dcd4..58e747e 100644 --- a/src/main/java/org/example/gather_back_end/util/jwt/dto/UserDto.java +++ b/src/main/java/org/example/gather_back_end/util/jwt/dto/UserDto.java @@ -1,10 +1,12 @@ package org.example.gather_back_end.util.jwt.dto; +import lombok.Builder; import lombok.Getter; import lombok.Setter; @Getter @Setter +@Builder public class UserDto { private String role; private String name; diff --git a/src/main/java/org/example/gather_back_end/util/jwt/handler/CustomSuccessHandler.java b/src/main/java/org/example/gather_back_end/util/jwt/handler/CustomSuccessHandler.java index 8397866..0a0e554 100644 --- a/src/main/java/org/example/gather_back_end/util/jwt/handler/CustomSuccessHandler.java +++ b/src/main/java/org/example/gather_back_end/util/jwt/handler/CustomSuccessHandler.java @@ -35,9 +35,9 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo GrantedAuthority auth = iterator.next(); String role = auth.getAuthority(); - String token = jwtUtil.createJwt(nickname, role, 60*60*1000L); + String token = jwtUtil.createJwt(nickname, role, 60 * 60 * 1000L); - response.sendRedirect("https://www.to-gather.info?code="+"Bearer "+token); + response.sendRedirect("https://www.to-gather.info?code=" + "Bearer " + token); } } diff --git a/src/main/java/org/example/gather_back_end/util/jwt/service/CustomOAuth2UserService.java b/src/main/java/org/example/gather_back_end/util/jwt/service/CustomOAuth2UserService.java index beffaf3..737528a 100644 --- a/src/main/java/org/example/gather_back_end/util/jwt/service/CustomOAuth2UserService.java +++ b/src/main/java/org/example/gather_back_end/util/jwt/service/CustomOAuth2UserService.java @@ -1,94 +1,8 @@ package org.example.gather_back_end.util.jwt.service; -import java.security.NoSuchAlgorithmException; -import java.time.LocalDateTime; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.example.gather_back_end.util.jwt.dto.CustomOAuth2User; -import org.example.gather_back_end.util.jwt.dto.GoogleResponse; -import org.example.gather_back_end.util.jwt.dto.OAuth2Response; -import org.example.gather_back_end.util.jwt.dto.UserDto; -import org.example.gather_back_end.util.jwt.entity.User; -import org.example.gather_back_end.util.jwt.repository.UserRepository; -import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; -import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.user.OAuth2User; -import org.springframework.stereotype.Service; -@Slf4j -@Service -@RequiredArgsConstructor -public class CustomOAuth2UserService extends DefaultOAuth2UserService { - - private final UserRepository userRepository; - private final LocalDateTimeNumericEncryption localDateTimeNumericEncryption; - - @Override - public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { - - OAuth2User oAuth2User = super.loadUser(userRequest); - log.info("[CustomOAuth2UserService 클래스][loadUser 메소드] : " + oAuth2User); - - String registrationId = userRequest.getClientRegistration().getRegistrationId(); - OAuth2Response oAuth2Response; - if (registrationId.equals("google")) { - oAuth2Response = new GoogleResponse(oAuth2User.getAttributes()); - } else { - return null; - } - - String username = oAuth2Response.getProvider() + " " + oAuth2Response.getProviderId(); - - StringBuilder numericEncryptedDateTime; - - while(true) { - SecretKey secretKey; - try { - secretKey = KeyGenerator.getInstance(localDateTimeNumericEncryption.getALGORITHM()).generateKey(); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - LocalDateTime code = LocalDateTime.now(); - try { - numericEncryptedDateTime = new StringBuilder(localDateTimeNumericEncryption.encryptToSixDigits(code, secretKey)); - } catch (Exception e) { - throw new RuntimeException(e); - } - - if(userRepository.findByNickname("USER" + numericEncryptedDateTime)==null) { - break; - } - } - - String nickname = "USER"+numericEncryptedDateTime; - - User existData = userRepository.findByUsername(username); - - if (existData == null) { - - userRepository.save(User.createAllUserInfo(username,oAuth2Response.getName(),oAuth2Response.getEmail(),"ROLE_USER",nickname)); - - UserDto userDto = new UserDto(); - userDto.setNickname(nickname); - userDto.setName(oAuth2Response.getName()); - userDto.setRole("ROLE_USER"); - - return new CustomOAuth2User(userDto); - } else { - - existData.updateUserInfo(oAuth2Response.getName(), oAuth2Response.getEmail()); - - userRepository.save(existData); - - UserDto userDto = new UserDto(); - userDto.setNickname(existData.getNickname()); - userDto.setName(oAuth2Response.getName()); - userDto.setRole(existData.getRole()); - - return new CustomOAuth2User(userDto); - } - } +public interface CustomOAuth2UserService { + OAuth2User loadUser(OAuth2UserRequest userRequest); } diff --git a/src/main/java/org/example/gather_back_end/util/jwt/service/CustomOAuth2UserServiceImpl.java b/src/main/java/org/example/gather_back_end/util/jwt/service/CustomOAuth2UserServiceImpl.java new file mode 100644 index 0000000..16e7fd1 --- /dev/null +++ b/src/main/java/org/example/gather_back_end/util/jwt/service/CustomOAuth2UserServiceImpl.java @@ -0,0 +1,101 @@ +package org.example.gather_back_end.util.jwt.service; + +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.example.gather_back_end.domain.User; +import org.example.gather_back_end.repository.UserRepository; +import org.example.gather_back_end.util.jwt.dto.CustomOAuth2User; +import org.example.gather_back_end.util.jwt.dto.GoogleResponse; +import org.example.gather_back_end.util.jwt.dto.OAuth2Response; +import org.example.gather_back_end.util.jwt.dto.UserDto; +import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CustomOAuth2UserServiceImpl extends DefaultOAuth2UserService implements CustomOAuth2UserService { + + private final UserRepository userRepository; + private final LocalDateTimeNumericEncryption localDateTimeNumericEncryption; + + @Override + public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { + + OAuth2User oAuth2User = super.loadUser(userRequest); + log.info("[CustomOAuth2UserService 클래스][loadUser 메소드] : " + oAuth2User); + + String registrationId = userRequest.getClientRegistration().getRegistrationId(); + OAuth2Response oAuth2Response; + + if (registrationId.equals("google")) { oAuth2Response = new GoogleResponse(oAuth2User.getAttributes()); } + else { return null; } + + String username = oAuth2Response.getProvider() + " " + oAuth2Response.getProviderId(); + + StringBuilder numericEncryptedDateTime; + + while(true) { + SecretKey secretKey; + try { + secretKey = KeyGenerator.getInstance(localDateTimeNumericEncryption.getALGORITHM()).generateKey(); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + LocalDateTime code = LocalDateTime.now(); + try { + numericEncryptedDateTime = new StringBuilder(localDateTimeNumericEncryption.encryptToSixDigits(code, secretKey)); + } catch (Exception e) { + throw new RuntimeException(e); + } + + if (userRepository.findByNickname("USER" + numericEncryptedDateTime) == null) { + break; + } + } + + String nickname = "USER" + numericEncryptedDateTime; + + User existData = userRepository.findByUsername(username); + + if (existData == null) { + + userRepository.save(User.createAllUserInfo( + username, + oAuth2Response.getName(), + oAuth2Response.getEmail(), + "ROLE_USER", + nickname) + ); + + UserDto userDto = UserDto.builder() + .nickname(nickname) + .name(oAuth2Response.getName()) + .role("ROLE_USER") + .build(); + + return new CustomOAuth2User(userDto); + + } else { + + existData.updateUserInfo(oAuth2Response.getName(), oAuth2Response.getEmail()); + + userRepository.save(existData); + + UserDto userDto = UserDto.builder() + .nickname(existData.getNickname()) + .name(existData.getName()) + .role(existData.getRole()) + .build(); + + return new CustomOAuth2User(userDto); + } + } +} diff --git a/src/main/java/org/example/gather_back_end/util/jwt/util/JwtFilter.java b/src/main/java/org/example/gather_back_end/util/jwt/util/JwtFilter.java index 8dc424f..a49a7e2 100644 --- a/src/main/java/org/example/gather_back_end/util/jwt/util/JwtFilter.java +++ b/src/main/java/org/example/gather_back_end/util/jwt/util/JwtFilter.java @@ -52,10 +52,11 @@ protected void doFilterInternal(HttpServletRequest request,HttpServletResponse r String nickname = jwtUtil.getNickname(token); String role = jwtUtil.getRole(token); - // userDtO 생성하여 값 set - UserDto userDto = new UserDto(); - userDto.setNickname(nickname); - userDto.setRole(role); + // userDto 생성하여 값 set + UserDto userDto = UserDto.builder() + .nickname(nickname) + .role(role) + .build(); // UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDto);