Skip to content

Commit

Permalink
Merge pull request #95 from Central-MakeUs/dev
Browse files Browse the repository at this point in the history
[Refactor] 소셜로그인 성공 시 회원가입인지 구분 및 실패 시 에러 메시지 포함되도록 수정
  • Loading branch information
dainnida authored Feb 11, 2025
2 parents 919ff5a + a02e048 commit 895681f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
Expand All @@ -19,8 +21,11 @@ public void onAuthenticationFailure(HttpServletRequest request, HttpServletRespo
AuthenticationException exception) throws IOException {

log.error("Social Login Failed: {}", exception.getMessage());
// 예외 메시지를 URI로 인코딩하여 전달
String errorMessage = URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8);

String targetUrl = UriComponentsBuilder.fromUriString("https://www.mercuryplanet.co.kr/login/fail")
.queryParam("error", errorMessage)
.build(true).toUriString();

getRedirectStrategy().sendRedirect(request, response, targetUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
Authentication authentication) throws IOException {
log.info("OAuth2 Login 성공!");
OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal();
// 인증이 완료된 후 새로운 요청이 발생하면 request에 저장된 데이터(isNewUser). 는 사라짐
boolean isNewUser = (boolean) oAuth2User.getAttributes().getOrDefault("isNewUser", false);

// oauthId로 사용자 조회
User user = userRepository.findByOauthId(oAuth2User.getName())
Expand All @@ -62,6 +64,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
// 리다이렉트 URL에 토큰 포함하여 이동
String targetUrl = UriComponentsBuilder.fromUriString("https://www.mercuryplanet.co.kr/login/success")
.queryParam("access_token", accessToken)
.queryParam("isNewUser", isNewUser)
.build(true).toUriString();

getRedirectStrategy().sendRedirect(request, response, targetUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -94,13 +95,19 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
String oauthId = oAuth2UserInfo.getOAuthId();
OAuthType oAuthType = oAuth2UserInfo.getOAuthType();

User user = userRepository.findByOauthTypeAndOauthId(oAuthType, oauthId)
.orElseGet(() -> {
log.info("새로운 사용자 생성 시도");
return createUser(oAuth2UserInfo);
});
Optional<User> existingUser = userRepository.findByOauthTypeAndOauthId(oAuthType, oauthId);
boolean isNewUser = existingUser.isEmpty(); // 존재하지 않으면 회원가입

User user = existingUser.orElseGet(() -> {
log.info("새로운 사용자 생성 시도");
return createUser(oAuth2UserInfo);
});
log.info("사용자 조회/생성 완료: userId={}", user.getId());

// 회원가입 여부를 Security Context에 저장 (OAuth2User에 포함)
Map<String, Object> userAttributes = new HashMap<>(oAuth2User.getAttributes());
userAttributes.put("isNewUser", isNewUser);

// 인증 객체 생성 (Security Context에 저장될 인증 정보)
// 반환된 DefaultOAuth2User는 나중에 @AuthenticationPrincipal로 받아서 필요한 정보를 꺼내 쓸 수 있음
return new DefaultOAuth2User(
Expand Down

0 comments on commit 895681f

Please sign in to comment.