diff --git a/src/main/java/com/example/moyeothon/Config/GlobalExceptionHandler.java b/src/main/java/com/example/moyeothon/Config/GlobalExceptionHandler.java new file mode 100644 index 0000000..be86455 --- /dev/null +++ b/src/main/java/com/example/moyeothon/Config/GlobalExceptionHandler.java @@ -0,0 +1,35 @@ +package com.example.moyeothon.Config; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.HashMap; +import java.util.Map; + +@ControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(HttpClientErrorException.class) + public ResponseEntity> handleHttpClientError(HttpClientErrorException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("status", e.getStatusCode().value()); + errorResponse.put("error", e.getStatusText()); + errorResponse.put("message", e.getResponseBodyAsString()); + + return ResponseEntity.status(e.getStatusCode()).body(errorResponse); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> handleGeneralException(Exception e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value()); + errorResponse.put("error", "Internal Server Error"); + errorResponse.put("message", e.getMessage()); + + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse); + } +} + diff --git a/src/main/java/com/example/moyeothon/Controller/UserController.java b/src/main/java/com/example/moyeothon/Controller/UserController.java index f871e38..d13ae34 100644 --- a/src/main/java/com/example/moyeothon/Controller/UserController.java +++ b/src/main/java/com/example/moyeothon/Controller/UserController.java @@ -63,15 +63,8 @@ public ResponseEntity updateNickname(@PathVariable String uid, @Request // 카카오 로그인 성공 시 호출되는 엔드포인트 (GET) @Operation(summary = "카카오 로그인 성공 시 호출되는 엔드포인트 (GET)") @GetMapping("/oauth2/code/kakao") - public ResponseEntity kakaoCallback(@RequestParam String code) { - return ResponseEntity.ok(userService.loginWithOAuth2(code)); - } - - // 카카오 로그인 성공 시 호출되는 엔드포인트 (POST) - @Operation(summary = "카카오 로그인 성공 시 호출되는 엔드포인트 (POST)") - @PostMapping("/oauth2/code/kakao") - public ResponseEntity kakaoLoginPost(@RequestBody OAuth2CodeDTO codeDTO) { - return ResponseEntity.ok(userService.loginWithOAuth2(codeDTO.getCode())); + public ResponseEntity kakaoCallback(@RequestParam String code, @RequestParam String state) { + return ResponseEntity.ok(userService.loginWithOAuth2(code, state)); } // 구글 로그인 성공 시 호출되는 엔드포인트 (GET) @@ -80,11 +73,4 @@ public ResponseEntity kakaoLoginPost(@RequestBody OAuth2CodeDTO codeDTO) public ResponseEntity googleCallback(@RequestParam String code) { return ResponseEntity.ok(userService.loginWithGoogleOAuth2(code)); } - - // 구글 로그인 성공 시 호출되는 엔드포인트 (POST) - @Operation(summary = "구글 로그인 성공 시 호출되는 엔드포인트 (POST)") - @PostMapping("/oauth2/code/google") - public ResponseEntity googleLoginPost(@RequestBody OAuth2CodeDTO codeDTO) { - return ResponseEntity.ok(userService.loginWithGoogleOAuth2(codeDTO.getCode())); - } } diff --git a/src/main/java/com/example/moyeothon/Service/UserService.java b/src/main/java/com/example/moyeothon/Service/UserService.java index 1505fbe..30774a8 100644 --- a/src/main/java/com/example/moyeothon/Service/UserService.java +++ b/src/main/java/com/example/moyeothon/Service/UserService.java @@ -9,6 +9,8 @@ import com.example.moyeothon.Repository.BucketRepository; import com.example.moyeothon.Repository.MessageRepository; import com.example.moyeothon.Repository.UserRepository; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.PostConstruct; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; @@ -31,6 +33,7 @@ public class UserService { private static final Logger logger = LoggerFactory.getLogger(UserService.class); + private final ObjectMapper objectMapper = new ObjectMapper(); private final PasswordEncoder passwordEncoder; private final UserRepository userRepository; private final JwtTokenProvider jwtTokenProvider; @@ -148,6 +151,22 @@ private String randomNickname() { return adjective + noun; } + @PostConstruct + public void logKakaoOAuthSettings() { + logger.info("카카오 로그인 설정 값 - clientId : {}, clientSecret : {}, redirectUri : {}", + kakaoOAuthProperties.getClientId(), + kakaoOAuthProperties.getClientSecret(), + kakaoOAuthProperties.getRedirectUri()); + + // 카카오 로그인 URL 로깅 + String authorizationUrl = String.format( + "https://kauth.kakao.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code", + kakaoOAuthProperties.getClientId(), + kakaoOAuthProperties.getRedirectUri() + ); + logger.info("카카오 로그인 URL : {}", authorizationUrl); + } + // 카카오 인가 코드로 액세스 토큰을 요청하는 메서드 public String getAccessToken(String code) { String url = "https://kauth.kakao.com/oauth/token"; @@ -193,6 +212,8 @@ public Map getUserInfo(String accessToken) { ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class); Map responseBody = response.getBody(); if (responseBody != null) { + String userInfoJson = objectMapper.writeValueAsString(responseBody); + logger.info("사용자 정보 출력 : {}", userInfoJson); logger.info("사용자 정보를 성공적으로 가져왔습니다 : {}", responseBody); return responseBody; } else { @@ -203,12 +224,18 @@ public Map getUserInfo(String accessToken) { logger.error("사용자 정보를 가져오는 중 오류가 발생했습니다. (위치: getUserInfo): {}", e.getMessage()); logger.error("응답 본문 (위치: getUserInfo): {}", e.getResponseBodyAsString()); throw e; + } catch (Exception e) { + logger.error("JSON 변환 중 오류가 발생했습니다: {}", e.getMessage()); + throw new RuntimeException("JSON 변환 중 오류가 발생했습니다.", e); } } // 최종적으로 카카오 로그인을 처리하는 메서드 - public JWTDTO loginWithOAuth2(String code) { + public JWTDTO loginWithOAuth2(String code, String state) { try { + String redirectUri = kakaoOAuthProperties.getRedirectUri(); + String redirectUrlWithParams = String.format("%s?code=%s&state=%s", redirectUri, code, state); + logger.info("카카오 로그인 성공 후 최종 리다이렉트 URL : {}", redirectUrlWithParams); String accessToken = getAccessToken(code); Map userInfo = getUserInfo(accessToken);