-
Notifications
You must be signed in to change notification settings - Fork 1
Feat: 안드로이드 SDK 방식의 컨트롤러 구성 #89
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughAdds a POST /auth/kakao-login endpoint for Android SDK token-based Kakao login, a KakaoLoginRequest DTO, new OAuth2Service methods (getProfileFromKakao, loginAndSignUp), exposes corresponding OAuth2ServiceImpl methods with improved error handling, adds INVALID_OAUTH_TOKEN error code, and permits the new endpoint in security config. Changes
Sequence Diagram(s)sequenceDiagram
participant App as Android App
participant BE as Backend (/auth/kakao-login)
participant Svc as OAuth2Service
participant Kakao as Kakao API
App->>BE: POST /auth/kakao-login { accessToken }
BE->>Svc: getProfileFromKakao(accessToken)
Svc->>Kakao: Validate token & fetch profile
Kakao-->>Svc: KakaoProfile (email)
BE->>Svc: loginAndSignUp(KAKAO, email)
Svc-->>BE: UserTokenDTO
BE->>Refresh as RefreshTokenService: saveRefreshToken(userToken, expiry)
BE-->>App: CustomResponse<UserTokenDTO>
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Out-of-scope changesNo out-of-scope functional changes detected relative to the linked issue objectives. Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🔭 Outside diff range comments (1)
src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java (1)
86-110: Persist refresh token inside the service to ensure consistency across flows.The OAuth callback controller saves the refresh token, but the new Android SDK flow does not. Centralizing persistence here prevents drift and duplicated logic.
Apply this diff:
public UserResponseDTO.UserTokenDTO loginAndSignUp(SocialType socialType, String email) { @@ String refreshToken = jwtProvider.createRefreshToken(user); long refreshExpiration = jwtProvider.getRefreshExpiration(); @@ Instant refreshExpire = issuedAt.plusMillis(refreshExpiration); + // Persist refresh token for subsequent refresh flows + LocalDateTime refreshTokenExpireAt = LocalDateTime.ofInstant(refreshExpire, ZoneId.of("Asia/Seoul")); + refreshTokenService.saveRefreshToken(user.getId(), refreshToken, refreshTokenExpireAt); + return UserResponseDTO.UserTokenDTO.builder() .userId(user.getId()) .accessToken(accessToken) .refreshToken(refreshToken) .refreshTokenExpire(Date.from(refreshExpire)) .build(); }Also add these imports at the top of this class:
import java.time.LocalDateTime; import java.time.ZoneId;Follow-up: Once this is centralized, remove the duplicate save call in KakaoController (GET /auth/kakao-oauth) to avoid double-writes.
🧹 Nitpick comments (5)
src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoLoginRequest.java (1)
5-8: Strengthen request validation (use @notblank and document via @Schema).Access tokens can be non-null but blank. Tighten validation and improve API docs for Swagger.
Apply this diff:
-import jakarta.validation.constraints.NotNull; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; -public record KakaoLoginRequest( - @NotNull String accessToken -) { +public record KakaoLoginRequest( + @Schema(description = "Kakao access token obtained via Android SDK") + @NotBlank String accessToken +) {src/main/java/naughty/tuzamate/auth/service/OAuth2Service.java (2)
15-18: Avoid provider-specific DTOs in a generic service interface.Exposing KakaoOAuth2DTO from the generic OAuth2Service tightly couples the interface to Kakao. Consider one of:
- Extract Kakao-specific APIs to a KakaoAuthService.
- Or return a provider-agnostic profile abstraction (e.g., AuthProfile { id, email, nickname }) and map Kakao’s payload internally.
This keeps the interface stable and implementation-pluggable.
17-17: Redundant ‘public’ keyword in interface method.Interface methods are implicitly public. Drop the modifier for consistency.
- public UserResponseDTO.UserTokenDTO loginAndSignUp(SocialType socialType, String email); + UserResponseDTO.UserTokenDTO loginAndSignUp(SocialType socialType, String email);src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java (1)
112-137: Harden Kakao profile fetch: auth header helper, entity type, and error handling.
- Use setBearerAuth() over manual header concatenation.
- Content-Type is not needed for GET; prefer Accept if anything.
- Use HttpEntity since there’s no body.
- Consider catching 401 (invalid/expired token) to map to OAUTH_TOKEN_FAIL distinctly.
- Prefer a singleton, injected ObjectMapper instead of constructing per call.
Apply this minimal diff:
- httpHeaders.add("Authorization", "Bearer " + accessToken); - httpHeaders.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + httpHeaders.setBearerAuth(accessToken); - HttpEntity<MultiValueMap> request1 = new HttpEntity<>(httpHeaders); + HttpEntity<Void> request1 = new HttpEntity<>(httpHeaders); - ResponseEntity<String> response2 = restTemplate.exchange( + ResponseEntity<String> response2 = restTemplate.exchange( userInfoURI, HttpMethod.GET, request1, String.class ); - ObjectMapper om = new ObjectMapper(); - try { - return om.readValue(response2.getBody(), KakaoOAuth2DTO.KakaoProfile.class); + return objectMapper.readValue(response2.getBody(), KakaoOAuth2DTO.KakaoProfile.class); } catch (Exception e) { throw new UserCustomException(UserErrorCode.OAUTH_USER_INFO_FAIL); }To support the injected mapper, add this field (already using Lombok @requiredargsconstructor):
private final ObjectMapper objectMapper;Optional (recommended): wrap the exchange call to provide finer error semantics:
try { ResponseEntity<String> resp = restTemplate.exchange(userInfoURI, HttpMethod.GET, request1, String.class); return objectMapper.readValue(resp.getBody(), KakaoOAuth2DTO.KakaoProfile.class); } catch (org.springframework.web.client.HttpClientErrorException.Unauthorized e) { throw new UserCustomException(UserErrorCode.OAUTH_TOKEN_FAIL); } catch (org.springframework.web.client.RestClientException e) { throw new UserCustomException(UserErrorCode.OAUTH_USER_INFO_FAIL); }Would you like me to push a follow-up commit moving to a configured RestTemplate/WebClient with timeouts and logging?
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java (1)
52-64: Guard against missing email (Kakao consent).Kakao may not return email unless the user granted consent or the account has a valid email. Calling loginAndSignUp with null/blank email can break account linking.
Consider:
- Validating email and returning a specific error instructing the client to request email consent; or
- Falling back to Kakao id as the unique identifier (and store email as optional).
Example guard (adjust error type to your codebase):
String email = profileFromKakao.getKakao_account().getEmail(); if (email == null || email.isBlank()) { // Option A: reject with a clear error throw new UserCustomException(UserErrorCode.OAUTH_USER_INFO_FAIL); // Option B: use profileFromKakao.getId() as primary identifier and treat email as optional }Do you want me to refactor loginAndSignUp to accept a provider userId (e.g., Kakao id) and make email optional?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java(2 hunks)src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoLoginRequest.java(1 hunks)src/main/java/naughty/tuzamate/auth/service/OAuth2Service.java(1 hunks)src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java(4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoLoginRequest.java (1)
src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoOAuth2DTO.java (6)
KakaoOAuth2DTO(5-53)KakaoAccount(31-51)OAuth2TokenDTO(7-15)KakaoProfile(17-52)Profile(43-50)Properties(24-29)
src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java (1)
src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoOAuth2DTO.java (6)
KakaoProfile(17-52)KakaoOAuth2DTO(5-53)Profile(43-50)KakaoAccount(31-51)OAuth2TokenDTO(7-15)Properties(24-29)
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java (3)
src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoOAuth2DTO.java (2)
KakaoOAuth2DTO(5-53)KakaoProfile(17-52)src/main/java/naughty/tuzamate/domain/user/dto/UserResponseDTO.java (1)
UserResponseDTO(8-23)src/main/java/naughty/tuzamate/domain/user/controller/UserController.java (1)
UserController(25-61)
src/main/java/naughty/tuzamate/auth/service/OAuth2Service.java (2)
src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoOAuth2DTO.java (4)
KakaoOAuth2DTO(5-53)KakaoProfile(17-52)KakaoAccount(31-51)Profile(43-50)src/main/java/naughty/tuzamate/domain/user/dto/UserResponseDTO.java (1)
UserResponseDTO(8-23)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: deploy
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🔭 Outside diff range comments (1)
src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java (1)
88-112: Guard against missing Kakao email (common) to avoid downstream failures.Kakao email is not guaranteed (depends on user consent). A null/blank email will cause user lookup/creation issues. Add an early validation to fail fast with a meaningful error or handle a fallback strategy.
Minimal defensive fix:
public UserResponseDTO.UserTokenDTO loginAndSignUp(SocialType socialType, String email) { + if (email == null || email.isBlank()) { + // Consider introducing a dedicated error code (e.g., EMAIL_NOT_PROVIDED) if you want finer granularity. + throw new UserCustomException(UserErrorCode.OAUTH_USER_INFO_FAIL); + } User user; Optional<User> userEmail = userRepository.findByEmail(email); user = userEmail.orElseGet(() -> userRepository.save(User.builder() .email(email) .role("ROLE_USER") .socialType(socialType) .build()));Additionally, consider ensuring a unique index on the email column and/or using a providerId-based lookup to make first-login idempotent under concurrency.
🧹 Nitpick comments (1)
src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java (1)
114-144: Simplify and harden Kakao profile fetch: use Accept header and direct JSON mapping.
- For GET, don’t set Content-Type form-urlencoded; set Accept: application/json.
- Use a typed RestTemplate exchange to deserialize directly to KakaoProfile.
- Use a typed HttpEntity for a header-only request.
Apply this diff:
public KakaoOAuth2DTO.KakaoProfile getProfileFromKakao(String accessToken) { // 액세스 토큰으로 사용자 정보를 가져온다 RestTemplate restTemplate = new RestTemplate(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Authorization", "Bearer " + accessToken); - httpHeaders.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + // GET 요청: 콘텐츠 전송이 아니라 응답 포맷 지정이므로 Accept 사용 + httpHeaders.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); - HttpEntity<MultiValueMap> request1 = new HttpEntity<>(httpHeaders); + HttpEntity<Void> request1 = new HttpEntity<>(httpHeaders); - try { - ResponseEntity<String> response2 = restTemplate.exchange( - userInfoURI, - HttpMethod.GET, - request1, - String.class - ); - - ObjectMapper om = new ObjectMapper(); - - return om.readValue(response2.getBody(), KakaoOAuth2DTO.KakaoProfile.class); - - } + try { + ResponseEntity<KakaoOAuth2DTO.KakaoProfile> response2 = restTemplate.exchange( + userInfoURI, + HttpMethod.GET, + request1, + KakaoOAuth2DTO.KakaoProfile.class + ); + return response2.getBody(); + } catch (HttpClientErrorException e) { throw new UserCustomException(UserErrorCode.INVALID_OAUTH_TOKEN); } catch (Exception e) { throw new CustomException(UserErrorCode.OAUTH_USER_INFO_FAIL); } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java(4 hunks)src/main/java/naughty/tuzamate/domain/user/error/UserErrorCode.java(1 hunks)src/main/java/naughty/tuzamate/global/config/SecurityConfig.java(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/main/java/naughty/tuzamate/global/config/SecurityConfig.java (1)
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java (2)
KakaoController(19-48)KakaoLogin(36-47)
src/main/java/naughty/tuzamate/domain/user/error/UserErrorCode.java (7)
src/main/java/naughty/tuzamate/auth/hantu/error/HantuErrorCode.java (1)
HantuErrorCode(8-19)src/main/java/naughty/tuzamate/auth/jwt/error/JwtErrorCode.java (1)
JwtErrorCode(8-19)src/main/java/naughty/tuzamate/domain/user/error/exception/UserCustomException.java (1)
UserCustomException(6-11)src/main/java/naughty/tuzamate/domain/profile/error/ProfileErrorCode.java (1)
AllArgsConstructor(9-21)src/main/java/naughty/tuzamate/global/error/GeneralErrorCode.java (1)
GeneralErrorCode(8-24)src/main/java/naughty/tuzamate/domain/stock/error/StockErrorCode.java (1)
StockErrorCode(8-19)src/main/java/naughty/tuzamate/auth/success/AuthSuccessCode.java (1)
AuthSuccessCode(8-23)
src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java (3)
src/main/java/naughty/tuzamate/domain/comment/service/command/CommentCommandServiceImpl.java (1)
Service(22-126)src/main/java/naughty/tuzamate/domain/post/service/command/PostCommandServiceImpl.java (1)
Service(22-147)src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoOAuth2DTO.java (5)
KakaoOAuth2DTO(5-53)KakaoProfile(17-52)Profile(43-50)KakaoAccount(31-51)OAuth2TokenDTO(7-15)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: deploy
🔇 Additional comments (1)
src/main/java/naughty/tuzamate/global/config/SecurityConfig.java (1)
43-45: PermitAll for/auth/kakao-loginconfirmed
The controller defines a POST mapping for/auth/kakao-loginin
• src/main/java/naughty/tuzamate/auth/controller/KakaoController.java:52
so the security config entry is accurate. Exposing this token‐exchange endpoint publicly is correct.
| USER_NICKNAME_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER40902", "이미 존재하는 닉네임입니다."), | ||
| INVALID_OAUTH_TOKEN(HttpStatus.UNAUTHORIZED, "USER40103", "유효하지 않은 토큰입니다."),; | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Syntax error: trailing comma before semicolon breaks enum compilation.
The last enum constant ends with ",;" which won’t compile.
Apply this diff:
- USER_NICKNAME_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER40902", "이미 존재하는 닉네임입니다."),
- INVALID_OAUTH_TOKEN(HttpStatus.UNAUTHORIZED, "USER40103", "유효하지 않은 토큰입니다."),;
+ USER_NICKNAME_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER40902", "이미 존재하는 닉네임입니다."),
+ INVALID_OAUTH_TOKEN(HttpStatus.UNAUTHORIZED, "USER40103", "유효하지 않은 토큰입니다.");📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| USER_NICKNAME_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER40902", "이미 존재하는 닉네임입니다."), | |
| INVALID_OAUTH_TOKEN(HttpStatus.UNAUTHORIZED, "USER40103", "유효하지 않은 토큰입니다."),; | |
| USER_NICKNAME_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER40902", "이미 존재하는 닉네임입니다."), | |
| INVALID_OAUTH_TOKEN(HttpStatus.UNAUTHORIZED, "USER40103", "유효하지 않은 토큰입니다."); |
🤖 Prompt for AI Agents
In src/main/java/naughty/tuzamate/domain/user/error/UserErrorCode.java around
lines 22 to 24, the enum declaration ends with a trailing comma before the
semicolon (",;") which causes a compilation error; remove the extra comma so the
final enum constant is terminated by a single semicolon (i.e., replace ",;" with
";") and ensure no other enum constants have dangling commas before the
semicolon.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java (1)
63-66: Good: Refresh token is persisted (parity with OAuth callback restored).This addresses the earlier concern about missing refresh-token persistence in the Android SDK flow. Parity with the GET /auth/kakao-oauth path is now achieved.
🧹 Nitpick comments (4)
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java (4)
20-20: Remove unused import (cleanup).
java.util.Mapis not used in this class. Clean it up to avoid warnings and keep imports tidy.-import java.util.Map;
52-70: DRY: Extract refresh-token persistence and zone constant.The refresh-token persistence logic here mirrors the GET flow above. Consider extracting a small helper in this controller (or better: into the service layer) and centralizing the ZoneId to reduce repetition and potential drift.
Example helper method (outside the shown lines):
// Add inside KakaoController private static final ZoneId DEFAULT_ZONE = ZoneId.of("Asia/Seoul"); private void persistRefreshToken(UserResponseDTO.UserTokenDTO token) { refreshTokenService.saveRefreshToken( token.getUserId(), token.getRefreshToken(), LocalDateTime.ofInstant(Instant.ofEpochMilli(token.getRefreshTokenExpire().getTime()), DEFAULT_ZONE) ); }Then call
persistRefreshToken(userTokenDTO);here, and similarly update the GET flow for consistency. I can prepare a small refactor PR if helpful.
52-70: Add tests for Android SDK Kakao login flow.Recommended coverage:
- Valid token -> returns UserTokenDTO and persists refresh token.
- Invalid/expired token -> returns the expected domain error (e.g., INVALID_OAUTH_TOKEN).
- Missing email in Kakao profile -> returns a controlled error instead of NPE.
I can scaffold controller slice tests with MockMvc and mock
OAuth2Service/RefreshTokenServiceif you want a quick start.
52-54: Add explicit JSON consumes and tighten accessToken validationRestrict the endpoint to JSON payloads and use
@NotBlankon the DTO to reject empty strings.• src/main/java/naughty/tuzamate/auth/controller/KakaoController.java (around lines 52–54)
• src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoLoginRequest.java (accessToken declaration)Suggested diffs:
// Controller - @PostMapping("/auth/kakao-login") + @PostMapping(path = "/auth/kakao-login", consumes = MediaType.APPLICATION_JSON_VALUE)// DTO -public record KakaoLoginRequest( - @NotNull String accessToken -) { +public record KakaoLoginRequest( + @NotBlank String accessToken +) {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java(2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java (4)
src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoOAuth2DTO.java (2)
KakaoOAuth2DTO(5-53)KakaoProfile(17-52)src/main/java/naughty/tuzamate/domain/user/dto/UserResponseDTO.java (1)
UserResponseDTO(8-23)src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java (3)
OAuth2ServiceImpl(29-174)loginWithKakao(78-86)login(66-74)src/main/java/naughty/tuzamate/domain/user/controller/UserController.java (1)
UserController(25-61)
🔇 Additional comments (1)
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java (1)
57-58: Error mapping for invalid/expired Kakao tokens correctly implementedI confirm that
getProfileFromKakaoinOAuth2ServiceImplcatchesHttpClientErrorException(covering 401 responses) and throwsUserCustomException(UserErrorCode.INVALID_OAUTH_TOKEN). No further changes are needed.
| KakaoOAuth2DTO.KakaoProfile profileFromKakao = oAuth2Service.getProfileFromKakao(request.accessToken()); | ||
|
|
||
| // 사용자 이메일, 카카오 타입으로 로그인 및 회원가입 처리 | ||
| String email = profileFromKakao.getKakao_account().getEmail(); | ||
| UserResponseDTO.UserTokenDTO userTokenDTO = oAuth2Service.loginAndSignUp(SocialType.KAKAO, email); | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Guard against missing email from Kakao (avoid NPE and handle consent).
Kakao may not always return kakao_account.email (scope not granted or email unavailable). Current code can throw NPE. Fail fast with a clear error, or define a fallback strategy (e.g., use Kakao id as the principal or enforce the account_email scope on the client).
Minimal defensive check:
- // 사용자 이메일, 카카오 타입으로 로그인 및 회원가입 처리
- String email = profileFromKakao.getKakao_account().getEmail();
- UserResponseDTO.UserTokenDTO userTokenDTO = oAuth2Service.loginAndSignUp(SocialType.KAKAO, email);
+ // 사용자 이메일, 카카오 타입으로 로그인 및 회원가입 처리
+ var account = profileFromKakao.getKakao_account();
+ if (account == null || account.getEmail() == null || account.getEmail().isBlank()) {
+ // Consider mapping to a domain-specific exception/error code handled by your GlobalExceptionHandler
+ throw new IllegalStateException("Kakao account email not available. Ensure 'account_email' scope is granted.");
+ }
+ String email = account.getEmail();
+ UserResponseDTO.UserTokenDTO userTokenDTO = oAuth2Service.loginAndSignUp(SocialType.KAKAO, email);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| KakaoOAuth2DTO.KakaoProfile profileFromKakao = oAuth2Service.getProfileFromKakao(request.accessToken()); | |
| // 사용자 이메일, 카카오 타입으로 로그인 및 회원가입 처리 | |
| String email = profileFromKakao.getKakao_account().getEmail(); | |
| UserResponseDTO.UserTokenDTO userTokenDTO = oAuth2Service.loginAndSignUp(SocialType.KAKAO, email); | |
| KakaoOAuth2DTO.KakaoProfile profileFromKakao = oAuth2Service.getProfileFromKakao(request.accessToken()); | |
| // 사용자 이메일, 카카오 타입으로 로그인 및 회원가입 처리 | |
| var account = profileFromKakao.getKakao_account(); | |
| if (account == null || account.getEmail() == null || account.getEmail().isBlank()) { | |
| // Consider mapping to a domain-specific exception/error code handled by your GlobalExceptionHandler | |
| throw new IllegalStateException("Kakao account email not available. Ensure 'account_email' scope is granted."); | |
| } | |
| String email = account.getEmail(); | |
| UserResponseDTO.UserTokenDTO userTokenDTO = oAuth2Service.loginAndSignUp(SocialType.KAKAO, email); |
🤖 Prompt for AI Agents
In src/main/java/naughty/tuzamate/auth/controller/KakaoController.java around
lines 57 to 62, guard against a null kakao_account or missing email: check
profileFromKakao.getKakao_account() and
profileFromKakao.getKakao_account().getEmail() before using the email; if either
is null, fail fast with a clear error (e.g., throw a BadRequestException or
custom exception with message like "Kakao did not return email — ensure
account_email scope is granted") or alternatively fall back to using
profileFromKakao.getId() as the principal for login/sign-up and call
oAuth2Service.loginAndSignUp with that identifier; ensure you do not dereference
null and that the log/exception guides the caller to grant the account_email
scope.
📍 PR 타입 (하나 이상 선택)
🏷️ 관련 이슈
Close #88
📌 개요
🔁 변경 사항
📸 스크린샷
✅ 체크리스트
💡 추가 사항 (리뷰어가 참고해야 할 것)
Summary by CodeRabbit