Skip to content

Conversation

@KiSeungMin
Copy link
Member

@KiSeungMin KiSeungMin commented Jul 29, 2025

✔️ 연관 이슈

📝 작업 내용

유저 인증 관련 로직을 Auth 폴더로 분리

스크린샷 (선택)

Summary by CodeRabbit

  • 신규 기능

    • 인증 및 토큰 관리를 위한 전용 인증 API 엔드포인트(/api/v1/auth) 추가: 일반 로그인, 카카오 로그인, 토큰 재발급, 로그아웃 지원
  • 버그 수정

    • 인증 관련 엔드포인트가 기존 사용자 API에서 분리되어 인증 전용 컨트롤러로 이동
  • 리팩터링

    • 인증 및 토큰 관련 클래스와 저장소, 서비스, 엔티티의 패키지 구조를 auth로 통합 및 정리
  • 보안

    • 인증 API 경로(/api/v1/auth/**)에 대한 접근 허용 정책 추가

@KiSeungMin KiSeungMin self-assigned this Jul 29, 2025
@KiSeungMin KiSeungMin added the ⚙️ chore 패키지 매니저 및 기타 수정 label Jul 29, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jul 29, 2025

Walkthrough

인증 관련 엔드포인트가 기존 UserController에서 분리되어 새로운 AuthController로 이동되었습니다. 카카오 로그인, 기본 로그인, 토큰 재발급, 로그아웃 등 인증 기능이 통합되어 /api/v1/auth 경로로 제공됩니다. 관련 DTO, 엔티티, 리포지토리, 서비스 클래스들도 auth 패키지로 이동되었습니다. 시큐리티 설정도 /api/v1/auth/** 경로를 허용하도록 변경되었습니다.

Changes

Cohort / File(s) Change Summary
AuthController 신설 및 인증 엔드포인트 통합
src/main/java/com/wayble/server/auth/controller/AuthController.java
인증 관련 엔드포인트(로그인, 카카오 로그인, 토큰 재발급, 로그아웃) 신설 및 통합, Swagger 문서화, 공통 응답 포맷 적용
UserController 인증 관련 코드 삭제
src/main/java/com/wayble/server/user/controller/UserController.java
로그인, 토큰 재발급, 로그아웃 엔드포인트 및 관련 필드/로직/Swagger 문서 삭제, 인증 서비스 의존성 제거
카카오 로그인 컨트롤러 삭제
src/main/java/com/wayble/server/user/controller/KakaoLoginController.java
카카오 로그인 전용 컨트롤러 및 엔드포인트 완전 삭제
패키지 이동: 인증 DTO/엔티티/리포지토리/서비스
src/main/java/com/wayble/server/auth/dto/TokenResponseDto.java,
src/main/java/com/wayble/server/auth/entity/RefreshToken.java,
src/main/java/com/wayble/server/auth/repository/RefreshTokenRepository.java,
src/main/java/com/wayble/server/auth/service/AuthService.java,
src/main/java/com/wayble/server/auth/service/KakaoLoginService.java
인증 관련 클래스들의 패키지명을 user에서 auth로 일괄 이동, import 경로 수정, 코드 로직 변경 없음
시큐리티 설정 변경
src/main/java/com/wayble/server/common/config/SecurityConfig.java
/api/v1/auth/** 경로를 인증 없이 접근 가능하도록 허용 패턴에 추가

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AuthController
    participant AuthService
    participant KakaoLoginService
    participant SecurityContext

    Client->>AuthController: POST /api/v1/auth/login/basic (email, pw)
    AuthController->>AuthService: login(request)
    AuthService-->>AuthController: TokenResponseDto
    AuthController-->>Client: CommonResponse<TokenResponseDto>

    Client->>AuthController: POST /api/v1/auth/login/kakao (kakaoToken)
    AuthController->>KakaoLoginService: kakaoLogin(request)
    KakaoLoginService-->>AuthController: KakaoLoginResponseDto
    AuthController-->>Client: CommonResponse<KakaoLoginResponseDto>

    Client->>AuthController: POST /api/v1/auth/reissue (refreshToken)
    AuthController->>AuthService: reissue(refreshToken)
    AuthService-->>AuthController: TokenResponseDto
    AuthController-->>Client: CommonResponse<TokenResponseDto>

    Client->>AuthController: POST /api/v1/auth/logout (Authorization: Bearer)
    AuthController->>SecurityContext: getUserIdFromContext()
    AuthController->>AuthService: logout(userId)
    AuthService-->>AuthController: Success message
    AuthController-->>Client: CommonResponse<String>
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Wayble-Project/wayble-spring#60: 카카오 로그인 컨트롤러 및 엔드포인트를 신설했던 PR로, 이번 PR에서 해당 기능이 통합 및 구조 변경됨
  • Wayble-Project/wayble-spring#44: JWT 기반 로그인 및 인증 서비스 초기 도입 PR로, 이번 PR은 이 구조를 리팩토링 및 분리
  • Wayble-Project/wayble-spring#53: JWT 리프레시 토큰, 로그아웃, 재발급 API를 UserController에 도입했던 PR로, 이번 PR에서 해당 기능이 AuthController로 이동됨

Poem

🐰
새로운 문이 열렸어요,
인증의 길이 분리되어
깔끔한 AuthController로 hop hop!
카카오도, 토큰도, 로그아웃도
이제는 한 곳에서 토실토실
토끼처럼 깡총깡총
코드가 더 예뻐졌어요!

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c0a53c and 072182b.

📒 Files selected for processing (3)
  • src/main/java/com/wayble/server/auth/entity/RefreshToken.java (1 hunks)
  • src/main/java/com/wayble/server/auth/repository/RefreshTokenRepository.java (1 hunks)
  • src/main/java/com/wayble/server/auth/service/AuthService.java (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/main/java/com/wayble/server/auth/entity/RefreshToken.java
  • src/main/java/com/wayble/server/auth/service/AuthService.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/wayble/server/auth/repository/RefreshTokenRepository.java
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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: 3

🔭 Outside diff range comments (3)
src/main/java/com/wayble/server/auth/service/KakaoLoginService.java (2)

32-42: 카카오에서 이메일을 반환하지 않는 경우 NPE 위험

카카오 계정에서 이메일 제공에 동의하지 않은 사용자는 kakaoUserInfo.getKakaoAccount().getEmail()null 이 될 수 있습니다.
null 체크 없이는 이후 findByEmailAndLoginType 호출에서 NullPointerException 이 발생합니다.
방어 코드를 추가하거나, 이메일이 없을 때 다른 식별자를 사용하도록 로직을 보완해야 합니다.


62-70: 리프레시 토큰을 DB에 저장하지 않아 재발급 API가 동작하지 않음

AuthService.reissue()RefreshTokenRepository 를 통해 DB 에 저장된 토큰을 조회합니다.
그러나 카카오 로그인 흐름에서는 발급된 refreshToken 을 저장하지 않아 재발급 및 로그아웃 로직이 실패합니다.
refreshTokenRepository.save(...) 로 저장하는 처리를 추가해 주세요.

 String refreshToken = jwtProvider.generateRefreshToken(user.getId());
 Long expiry = jwtProvider.getTokenExpiry(refreshToken);

+refreshTokenRepository.deleteByUserId(user.getId());
+refreshTokenRepository.save(
+        RefreshToken.builder()
+                .userId(user.getId())
+                .token(refreshToken)
+                .expiry(expiry)
+                .build());
src/main/java/com/wayble/server/common/config/SecurityConfig.java (1)

37-41: 이전 인증 엔드포인트 경로를 제거해주세요.

인증 관련 엔드포인트가 /api/v1/auth/**로 이동했으므로, 더 이상 사용하지 않는 경로들을 제거해야 합니다. /api/v1/users/signup은 여전히 UserController에서 처리하므로 유지해야 합니다.

다음과 같이 수정해주세요:

 .requestMatchers(
     "/api/v1/users/signup",
-    "/api/v1/users/login",
-    "/api/v1/users/reissue",
-    "/api/v1/users/logout",
     "/api/v1/auth/**",
♻️ Duplicate comments (2)
src/main/java/com/wayble/server/auth/repository/RefreshTokenRepository.java (1)

3-3: enttiy 패키지명 오타 재사용

앞서 지적한 패키지 오타가 여기서도 반복됩니다. 동일하게 entity 로 수정해야 합니다.
이전 코멘트와 중복되어 추가 설명은 생략합니다.

src/main/java/com/wayble/server/auth/service/AuthService.java (1)

7-8: 패키지 오타로 인한 임포트 오류

com.wayble.server.auth.enttiy.RefreshTokencom.wayble.server.auth.entity.RefreshToken 로 수정 필요.
앞서 동일 사안에 대해 코멘트가 있으므로 중복 표기로 처리합니다.

🧹 Nitpick comments (1)
src/main/java/com/wayble/server/user/controller/UserController.java (1)

12-12: 사용하지 않는 import를 제거하세요.

AuthService는 이 컨트롤러에서 사용되지 않으므로 import를 제거해야 합니다.

-import com.wayble.server.auth.service.AuthService;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7c8e3a and 2c0a53c.

📒 Files selected for processing (9)
  • src/main/java/com/wayble/server/auth/controller/AuthController.java (1 hunks)
  • src/main/java/com/wayble/server/auth/dto/TokenResponseDto.java (1 hunks)
  • src/main/java/com/wayble/server/auth/enttiy/RefreshToken.java (1 hunks)
  • src/main/java/com/wayble/server/auth/repository/RefreshTokenRepository.java (1 hunks)
  • src/main/java/com/wayble/server/auth/service/AuthService.java (1 hunks)
  • src/main/java/com/wayble/server/auth/service/KakaoLoginService.java (1 hunks)
  • src/main/java/com/wayble/server/common/config/SecurityConfig.java (1 hunks)
  • src/main/java/com/wayble/server/user/controller/KakaoLoginController.java (0 hunks)
  • src/main/java/com/wayble/server/user/controller/UserController.java (2 hunks)
💤 Files with no reviewable changes (1)
  • src/main/java/com/wayble/server/user/controller/KakaoLoginController.java
🧰 Additional context used
🧠 Learnings (4)
src/main/java/com/wayble/server/auth/enttiy/RefreshToken.java (1)

Learnt from: seung-in-Yoo
PR: #37
File: src/main/java/com/wayble/server/user/entity/User.java:61-62
Timestamp: 2025-07-13T15:08:59.318Z
Learning: Java에서 같은 패키지 내의 클래스들은 import 구문 없이 서로를 참조할 수 있다. com.wayble.server.user.entity 패키지 내의 클래스들은 명시적인 import 없이 사용 가능하다.

src/main/java/com/wayble/server/auth/service/AuthService.java (1)

Learnt from: seung-in-Yoo
PR: #37
File: src/main/java/com/wayble/server/user/entity/User.java:61-62
Timestamp: 2025-07-13T15:08:59.318Z
Learning: Java에서 같은 패키지 내의 클래스들은 import 구문 없이 서로를 참조할 수 있다. com.wayble.server.user.entity 패키지 내의 클래스들은 명시적인 import 없이 사용 가능하다.

src/main/java/com/wayble/server/auth/repository/RefreshTokenRepository.java (1)

Learnt from: seung-in-Yoo
PR: #37
File: src/main/java/com/wayble/server/user/entity/User.java:61-62
Timestamp: 2025-07-13T15:08:59.318Z
Learning: Java에서 같은 패키지 내의 클래스들은 import 구문 없이 서로를 참조할 수 있다. com.wayble.server.user.entity 패키지 내의 클래스들은 명시적인 import 없이 사용 가능하다.

src/main/java/com/wayble/server/auth/service/KakaoLoginService.java (1)

Learnt from: seung-in-Yoo
PR: #37
File: src/main/java/com/wayble/server/user/entity/User.java:61-62
Timestamp: 2025-07-13T15:08:59.318Z
Learning: Java에서 같은 패키지 내의 클래스들은 import 구문 없이 서로를 참조할 수 있다. com.wayble.server.user.entity 패키지 내의 클래스들은 명시적인 import 없이 사용 가능하다.

🧬 Code Graph Analysis (1)
src/main/java/com/wayble/server/auth/controller/AuthController.java (2)
src/main/java/com/wayble/server/common/config/security/jwt/JwtAuthenticationFilter.java (1)
  • RequiredArgsConstructor (13-43)
src/main/java/com/wayble/server/user/controller/UserController.java (1)
  • RestController (25-94)
🔇 Additional comments (1)
src/main/java/com/wayble/server/auth/dto/TokenResponseDto.java (1)

1-3: 변경 사항 이상 없음

패키지 이동만 이루어졌으며 레코드 정의는 간결하고 문제 없습니다.

Comment on lines +7 to +11
import com.wayble.server.user.dto.KakaoLoginRequestDto;
import com.wayble.server.user.dto.KakaoLoginResponseDto;
import com.wayble.server.user.dto.UserLoginRequestDto;
import com.wayble.server.auth.dto.TokenResponseDto;
import com.wayble.server.user.exception.UserErrorCase;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

인증 관련 DTO와 에러 케이스를 auth 패키지로 이동하세요.

인증 로직을 Auth 폴더로 분리하는 PR 목적에 맞게, 인증 관련 DTO들(KakaoLoginRequestDto, KakaoLoginResponseDto, UserLoginRequestDto)과 UserErrorCase도 auth 패키지로 이동해야 합니다. 현재 user 패키지에서 import하고 있어 패키지 간 의존성이 깔끔하게 분리되지 않았습니다.

다음 클래스들을 auth 패키지로 이동하시겠습니까?

  • com.wayble.server.user.dto.KakaoLoginRequestDtocom.wayble.server.auth.dto.KakaoLoginRequestDto
  • com.wayble.server.user.dto.KakaoLoginResponseDtocom.wayble.server.auth.dto.KakaoLoginResponseDto
  • com.wayble.server.user.dto.UserLoginRequestDtocom.wayble.server.auth.dto.UserLoginRequestDto
  • com.wayble.server.user.exception.UserErrorCasecom.wayble.server.auth.exception.AuthErrorCase

이 작업을 위한 이슈를 생성해드릴까요?

🤖 Prompt for AI Agents
In src/main/java/com/wayble/server/auth/controller/AuthController.java around
lines 7 to 11, the imports for authentication-related DTOs and error cases are
still from the user package, causing unclear package dependencies. Move the
classes KakaoLoginRequestDto, KakaoLoginResponseDto, UserLoginRequestDto from
com.wayble.server.user.dto to com.wayble.server.auth.dto, and move UserErrorCase
from com.wayble.server.user.exception to
com.wayble.server.auth.exception.AuthErrorCase. Then update the import
statements in AuthController.java to reflect these new package locations.

Comment on lines +100 to +108
if (accessToken == null || !accessToken.startsWith("Bearer ")) {
throw new ApplicationException(UserErrorCase.INVALID_CREDENTIALS);
}
String token = accessToken.replace("Bearer ", "");
if (token.isEmpty()) {
throw new ApplicationException(UserErrorCase.INVALID_CREDENTIALS);
}
Long userId = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
authService.logout(userId);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

불필요한 토큰 검증 로직을 제거하고 NPE 방지 로직을 추가하세요.

현재 구현에는 두 가지 문제가 있습니다:

  1. JwtAuthenticationFilter에서 이미 토큰 검증을 수행하므로 중복 검증입니다.
  2. 인증이 실패한 경우 SecurityContextHolder.getContext().getAuthentication()이 null일 수 있어 NPE가 발생할 수 있습니다.

다음과 같이 수정하세요:

-    public CommonResponse<String> logout(
-            @Parameter(
-                    description = "사용자 인증용 accessToken (Bearer {token} 형태)",
-                    required = true,
-                    example = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
-            )
-            @RequestHeader("Authorization") String accessToken
-    ) {
-        if (accessToken == null || !accessToken.startsWith("Bearer ")) {
-            throw new ApplicationException(UserErrorCase.INVALID_CREDENTIALS);
-        }
-        String token = accessToken.replace("Bearer ", "");
-        if (token.isEmpty()) {
-            throw new ApplicationException(UserErrorCase.INVALID_CREDENTIALS);
-        }
-        Long userId = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+    public CommonResponse<String> logout() {
+        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+        if (authentication == null || !(authentication.getPrincipal() instanceof Long userId)) {
+            throw new ApplicationException(UserErrorCase.UNAUTHORIZED);
+        }
         authService.logout(userId);
         return CommonResponse.success("로그아웃에 성공하였습니다.");
     }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/com/wayble/server/auth/controller/AuthController.java around
lines 100 to 108, remove the redundant token validation logic since
JwtAuthenticationFilter already handles it. Instead, add a null check for
SecurityContextHolder.getContext().getAuthentication() before accessing its
principal to prevent NullPointerException. If authentication is null, handle it
appropriately, such as throwing an ApplicationException with
INVALID_CREDENTIALS.

@@ -1,4 +1,4 @@
package com.wayble.server.user.entity;
package com.wayble.server.auth.enttiy;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

패키지명 오타로 인한 컴파일 실패 가능성

enttiyentity 로 수정하지 않으면 동일 패키지를 import 하는 모든 클래스가 컴파일 오류가 발생합니다.
또한 실제 디렉터리 구조도 함께 수정되어야 합니다.

-package com.wayble.server.auth.enttiy;
+package com.wayble.server.auth.entity;
📝 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
package com.wayble.server.auth.enttiy;
package com.wayble.server.auth.entity;
🤖 Prompt for AI Agents
In src/main/java/com/wayble/server/auth/enttiy/RefreshToken.java at line 1, the
package name is misspelled as "enttiy" instead of "entity". Correct the package
declaration to "com.wayble.server.auth.entity" and rename the directory from
"enttiy" to "entity" to match the corrected package name, ensuring all imports
and references are updated accordingly to prevent compilation errors.

Copy link
Member

@seung-in-Yoo seung-in-Yoo left a comment

Choose a reason for hiding this comment

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

RefreshToken 파일 들어있는 폴더 이름이 enttiy로 되어있는 곳만 수정하면 될것 같네요 수고하셨습니다!

@@ -1,4 +1,4 @@
package com.wayble.server.user.entity;
package com.wayble.server.auth.enttiy;
Copy link
Member

Choose a reason for hiding this comment

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

요기 코드래빗 말처럼 entity로 수정해야 하지 않을까요??

package com.wayble.server.auth.repository;

import com.wayble.server.user.entity.RefreshToken;
import com.wayble.server.auth.enttiy.RefreshToken;
Copy link
Member

Choose a reason for hiding this comment

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

여기도 수정해야할거 같습니다!

Copy link
Member Author

Choose a reason for hiding this comment

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

@seung-in-Yoo ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ 수정했어요 감사합니다!!

@KiSeungMin KiSeungMin merged commit 81db6d0 into main Jul 29, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚙️ chore 패키지 매니저 및 기타 수정

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants