Skip to content

Commit

Permalink
♻️ User 관련 리팩토링 (#23)
Browse files Browse the repository at this point in the history
* 🚚 User 엔티티 패키지 이동

* 🚚 UserRepository 패키지 이동

* ♻️ 코드 스타일 변경

* 💄 서비스 인터페이스 생성
  • Loading branch information
MinseoKangQ authored Oct 31, 2024
1 parent 2380acd commit c5ab024
Show file tree
Hide file tree
Showing 12 changed files with 125 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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
Expand Down
1 change: 0 additions & 1 deletion src/main/java/org/example/gather_back_end/domain/Work.java
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
@@ -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, Long> {

User findByNickname(String nickname);

User findByUsername(String username);


}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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)
)
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, Object> attribute;

public GoogleResponse(Map<String, Object> attribute) {
this.attribute = attribute;
}

@Override
public String getProvider() {
return "google";
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Original file line number Diff line number Diff line change
@@ -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);
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit c5ab024

Please sign in to comment.