Skip to content

Conversation

@RCNR
Copy link
Contributor

@RCNR RCNR commented Aug 17, 2025

📍 PR 타입 (하나 이상 선택)

  • 기능 추가
  • 버그 수정
  • 의존성, 환경 변수, 빌드 관련 코드 업데이트
  • 기타 사소한 수정

🏷️ 관련 이슈

Close #88

📌 개요

  • 안드로이드에서 주는 액세스 토큰을 받아 사용자 정보를 조회한다.

🔁 변경 사항

📸 스크린샷

✅ 체크리스트

  • 코드가 정상적으로 동작하는지 확인
  • PR에 적절한 라벨을 선택
  • 관련 테스트 코드 작성
  • 문서(README, Swagger 등) 업데이트

💡 추가 사항 (리뷰어가 참고해야 할 것)

Summary by CodeRabbit

  • New Features
    • Added Kakao Android SDK token-based login: users can sign in via their Kakao mobile token and receive an app session token.
    • First-time Kakao sign-ins automatically create accounts for seamless onboarding.
    • Retains existing Kakao web OAuth sign-in so both web and Android token-based flows are available.

@RCNR RCNR self-assigned this Aug 17, 2025
@RCNR RCNR linked an issue Aug 17, 2025 that may be closed by this pull request
2 tasks
@coderabbitai
Copy link

coderabbitai bot commented Aug 17, 2025

Walkthrough

Adds 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

Cohort / File(s) Summary
Controller: Kakao Android SDK login endpoint
src/main/java/naughty/tuzamate/auth/controller/KakaoController.java
Adds POST /auth/kakao-login accepting KakaoLoginRequest, validates token via OAuth2Service.getProfileFromKakao, extracts email, calls loginAndSignUp(SocialType.KAKAO, email), persists refresh token, returns CustomResponse<UserTokenDTO>.
DTO: Request model
src/main/java/naughty/tuzamate/auth/dto/kakao/KakaoLoginRequest.java
New record KakaoLoginRequest(@NotNull String accessToken).
Service API: Interface additions
src/main/java/naughty/tuzamate/auth/service/OAuth2Service.java
Adds KakaoOAuth2DTO.KakaoProfile getProfileFromKakao(String accessToken) and UserResponseDTO.UserTokenDTO loginAndSignUp(SocialType socialType, String email).
Service Impl: Visibility & error handling
src/main/java/naughty/tuzamate/auth/service/OAuth2ServiceImpl.java
Made getProfileFromKakao and loginAndSignUp public; added specific HttpClientErrorException handling to throw UserCustomException(INVALID_OAUTH_TOKEN) and general CustomException(OAUTH_USER_INFO_FAIL) on other failures; import adjustments.
Domain: Error codes
src/main/java/naughty/tuzamate/domain/user/error/UserErrorCode.java
Adds INVALID_OAUTH_TOKEN(HttpStatus.UNAUTHORIZED, "USER40103", "유효하지 않은 토큰입니다.").
Security: Permit new endpoint
src/main/java/naughty/tuzamate/global/config/SecurityConfig.java
Adds "/auth/kakao-login" to allowUrls so the endpoint is publicly permitted.

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>
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Implement Android SDK-based Kakao login flow (#88)
Access token validation via Kakao API (#88)
User handling: login or sign-up (#88)

Out-of-scope changes

No out-of-scope functional changes detected relative to the linked issue objectives.

Possibly related PRs

Suggested labels

feature

Suggested reviewers

  • weeast1521

Poem

I hop through code with twitching nose,
A Kakao token in my paws it goes—
From Android burrow to backend burrow,
Profile fetched, no fluster or furrow.
Sign or log, the warren knows; carrot-orange glow! 🥕🐇

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/#88-kakao-login-android-sdk-impl

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 4333c6d and 0091dab.

📒 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

Copy link

@coderabbitai coderabbitai bot left a 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 0091dab and 8f272b4.

📒 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-login confirmed
The controller defines a POST mapping for /auth/kakao-login in
• 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.

Comment on lines +22 to 24
USER_NICKNAME_ALREADY_EXISTS(HttpStatus.CONFLICT, "USER40902", "이미 존재하는 닉네임입니다."),
INVALID_OAUTH_TOKEN(HttpStatus.UNAUTHORIZED, "USER40103", "유효하지 않은 토큰입니다."),;

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

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.

Suggested change
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.

Copy link

@coderabbitai coderabbitai bot left a 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.Map is 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/RefreshTokenService if you want a quick start.


52-54: Add explicit JSON consumes and tighten accessToken validation

Restrict the endpoint to JSON payloads and use @NotBlank on 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 8f272b4 and 83d40eb.

📒 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 implemented

I confirm that getProfileFromKakao in OAuth2ServiceImpl catches HttpClientErrorException (covering 401 responses) and throws UserCustomException(UserErrorCode.INVALID_OAUTH_TOKEN). No further changes are needed.

Comment on lines +57 to +62
KakaoOAuth2DTO.KakaoProfile profileFromKakao = oAuth2Service.getProfileFromKakao(request.accessToken());

// 사용자 이메일, 카카오 타입으로 로그인 및 회원가입 처리
String email = profileFromKakao.getKakao_account().getEmail();
UserResponseDTO.UserTokenDTO userTokenDTO = oAuth2Service.loginAndSignUp(SocialType.KAKAO, email);

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

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.

Suggested change
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.

@RCNR RCNR merged commit 28422de into dev Aug 19, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

✨ [Feat] 카카오 로그인 안드로이드 sdk 방식으로 구현

2 participants