Skip to content

[Feat/logout] 로그아웃 api, refresh token 삭제 로직 구현#96

Merged
jeeheaG merged 21 commits intomainfrom
feat/logout
May 26, 2025
Merged

[Feat/logout] 로그아웃 api, refresh token 삭제 로직 구현#96
jeeheaG merged 21 commits intomainfrom
feat/logout

Conversation

@jeeheaG
Copy link
Contributor

@jeeheaG jeeheaG commented May 18, 2025

[작업 사항]

  • refresh token 삭제 로직 구현
  • 탈퇴 api 에 해당 로직 적용
  • 로그아웃 api 구현, 해당 로직 적용
  • health check api 구현

[추가 작업 사항]
로그아웃 성공 응답을 두가지로 분리했습니다.

  1. 일반 로그아웃 성공 응답(200) : refresh token 삭제 성공 시
  2. 이미 로그아웃된 사용자 성공 응답(200) : refresh token 존재하지 않을 시

또한 아래 통합 테스트 케이스들 추가했습니다!

  1. 기존 로그아웃 성공 테스트 -> '이미 로그아웃된 사용자' 성공 응답 케이스로 이름 변경
  2. 카카오 로그인 - 로그아웃 성공 케이스
  3. 애플 로그인 - 로그아웃 성공 케이스
  4. '토큰 유효하지 않음' 실패 케이스
  5. '사용자 찾을 수 없음' 실패 케이스

[comment]
로그아웃은 현재 내부적으로 하는 일이 refersh token 삭제 뿐이나,
이후 로그아웃 후처리에서 추가적인 로직이 들어갈 수도 있을거라 생각해서 usecase 정의했습니다.
또한 log out 네이밍 시
띄어쓰기를 넣느냐 안넣느냐에 대해 혼란스러울 수 있을 것 같아
모두 띄어쓰기 하는 걸로 작업했습니다.

Summary by CodeRabbit

  • New Features
    • Added a health check API endpoint accessible without authentication.
    • Introduced a logout API endpoint that allows users to log out and handles cases where users are already logged out.
    • Implemented the ability to remove refresh tokens during user logout and withdrawal processes.
  • Bug Fixes
    • Improved error handling for invalid tokens and user-not-found scenarios during logout.
  • Tests
    • Added integration and acceptance tests for health check and logout endpoints, covering both success and failure cases.
    • Included new SQL test data for user and OAuth account scenarios.
  • Documentation
    • Enhanced API documentation for new endpoints and error codes.
  • Chores
    • Updated security settings to whitelist the new health check endpoint.

@jeeheaG jeeheaG requested a review from ekgns33 May 18, 2025 16:53
@jeeheaG jeeheaG self-assigned this May 18, 2025
@coderabbitai
Copy link

coderabbitai bot commented May 18, 2025

Walkthrough

This update introduces a complete user logout feature, including controllers, service logic, repository methods, exception handling, and integration tests. It also adds a health check endpoint and ensures public access to its route. The logout flow invalidates refresh tokens, handles expired tokens, and provides appropriate success or error responses. Related constants and enums are updated accordingly.

Changes

File(s) Change Summary
.../auth/repository/DatabaseTokenRepository.java
.../InMemoryTokenRepository.java
.../JwtTokenRepository.java
.../RefreshTokenJpaRepository.java
Added deleteRefreshTokenByUserId(Long userId) method to repositories and interface for refresh token deletion.
.../auth/service/TokenRefreshService.java Added getStoredRefreshToken(Long userId) and removeRefreshToken(Long userId) methods; refactored logic.
.../user/service/WithdrawService.java Injected TokenRefreshService; now removes refresh token on user withdrawal.
.../auth/jwt/JwtResolver.java Wrapped JWT verification in try-catch; throws UserJwtException on failure.
.../user/enums/UserHttpResponseCode.java Added TOKEN_DELETE_REFRESH_FAIL, ALREADY_LOG_OUT_SUCCESS, and USER_NOT_FOUND enum constants.
.../user/exception/UserException.java Introduced new UserException class with constructors and a factory method.
.../exceptions/GlobalExceptionHandler.java Added handler for UserException.
.../auth/service/logout/LogOutUsecase.java Introduced LogOutUsecase interface for logout logic.
.../auth/service/logout/LogOutUsecaseImpl.java Implemented logout use case; handles user lookup, token validation, and deletion.
.../auth/controller/LogOutController.java Added REST controller for /api/v1/auth/log-out endpoint with OpenAPI docs.
.../checker/controller/HealthCheckController.java Added REST controller for /checker/health-check endpoint.
.../common/GlobalConsts.java Added "/checker" to WHITE_LIST_ENDPOINTS.
.../config/SecurityConfig.java Allowed unauthenticated access to /checker/** endpoints.
.../checker/controller/HealthCheckControllerTest.java Added integration test for health check endpoint.
.../user/api/LogOutAcceptanceFailTest.java Added integration tests for logout failure scenarios (token invalid, user not found).
.../user/api/LogOutAcceptanceSuccessTest.java Added integration tests for successful logout scenarios, including after login.
.../resources/sql/log_out_test_data.sql Added SQL script for user and OAuth test data setup.

Sequence Diagram(s)

User Logout Flow

sequenceDiagram
    participant Client
    participant LogOutController
    participant LogOutUsecaseImpl
    participant JwtResolver
    participant UserFinder
    participant TokenRefreshService
    participant JwtTokenRepository

    Client->>LogOutController: POST /api/v1/auth/log-out (Authorization: Bearer token)
    LogOutController->>LogOutUsecaseImpl: execute(accessToken)
    LogOutUsecaseImpl->>JwtResolver: getUserIdFromJwtToken(accessToken)
    JwtResolver-->>LogOutUsecaseImpl: userPublicId or throw UserJwtException
    LogOutUsecaseImpl->>UserFinder: findUserByPublicId(userPublicId)
    UserFinder-->>LogOutUsecaseImpl: User or throw UserException
    LogOutUsecaseImpl->>TokenRefreshService: getStoredRefreshToken(userId)
    TokenRefreshService-->>LogOutUsecaseImpl: refreshToken or throw UserJwtException
    LogOutUsecaseImpl->>TokenRefreshService: removeRefreshToken(userId)
    TokenRefreshService->>JwtTokenRepository: deleteRefreshTokenByUserId(userId)
    JwtTokenRepository-->>TokenRefreshService: (void)
    TokenRefreshService-->>LogOutUsecaseImpl: (void)
    LogOutUsecaseImpl-->>LogOutController: true/false
    LogOutController-->>Client: 200 OK (logout success or already logged out)
Loading

Health Check Endpoint

sequenceDiagram
    participant Client
    participant HealthCheckController

    Client->>HealthCheckController: GET /checker/health-check
    HealthCheckController-->>Client: 200 OK (SuccessResponse)
Loading

Poem

🐇
A logout leap, a token's end,
With careful checks, old tokens send—
Away they hop, no longer bound,
In code and tests, new flows are found.
Health checks bloom, endpoints free,
Springtime changes—secure as can be!

—Your friendly CodeRabbit


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 798ae75 and 2bb7704.

📒 Files selected for processing (10)
  • src/main/java/org/runimo/runimo/auth/controller/LogOutController.java (1 hunks)
  • src/main/java/org/runimo/runimo/auth/service/TokenRefreshService.java (1 hunks)
  • src/main/java/org/runimo/runimo/auth/service/logout/LogOutUsecase.java (1 hunks)
  • src/main/java/org/runimo/runimo/auth/service/logout/LogOutUsecaseImpl.java (1 hunks)
  • src/main/java/org/runimo/runimo/exceptions/GlobalExceptionHandler.java (2 hunks)
  • src/main/java/org/runimo/runimo/user/enums/UserHttpResponseCode.java (1 hunks)
  • src/test/java/org/runimo/runimo/checker/controller/HealthCheckControllerTest.java (1 hunks)
  • src/test/java/org/runimo/runimo/user/api/LogOutAcceptanceFailTest.java (1 hunks)
  • src/test/java/org/runimo/runimo/user/api/LogOutAcceptanceSuccessTest.java (1 hunks)
  • src/test/resources/sql/log_out_test_data.sql (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/main/java/org/runimo/runimo/auth/service/logout/LogOutUsecase.java
  • src/test/java/org/runimo/runimo/checker/controller/HealthCheckControllerTest.java
  • src/main/java/org/runimo/runimo/auth/service/TokenRefreshService.java
  • src/main/java/org/runimo/runimo/auth/service/logout/LogOutUsecaseImpl.java
  • src/main/java/org/runimo/runimo/user/enums/UserHttpResponseCode.java

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

🪧 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? Join our Discord community 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 sequence diagram to generate a sequence diagram of the changes in 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.

@ekgns33
Copy link
Contributor

ekgns33 commented May 19, 2025

고생하셨어요! 몇가지 리뷰 남겼습니다 😄

@jeeheaG
Copy link
Contributor Author

jeeheaG commented May 19, 2025

꼼꼼하게 봐주셔서 감사합니다!
로그인+로그아웃 통합테스트 관련된 건 따로 질문드렸고 나머지는 반영 완료했어요

Copy link
Contributor

@ekgns33 ekgns33 left a comment

Choose a reason for hiding this comment

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

고생하셨습니다!! getPublicId 위치 조정에 대해서만 하나 봐주세용 👍

@jeeheaG
Copy link
Contributor Author

jeeheaG commented May 20, 2025

토큰 로직 수정되었습니다.
테스트케이스 내일 추가해볼게요,,

@jeeheaG
Copy link
Contributor Author

jeeheaG commented May 26, 2025

로그아웃 성공 응답을 두가지로 분리했습니다.

  1. 일반 로그아웃 성공 응답(200) : refresh token 삭제 성공 시
  2. 이미 로그아웃된 사용자 성공 응답(200) : refresh token 존재하지 않을 시

또한 아래 통합 테스트 케이스들 추가했습니다!

  1. 기존 로그아웃 성공 테스트 -> '이미 로그아웃된 사용자' 성공 응답 케이스로 이름 변경
  2. 카카오 로그인 - 로그아웃 성공 케이스
  3. 애플 로그인 - 로그아웃 성공 케이스
  4. '토큰 유효하지 않음' 실패 케이스
  5. '사용자 찾을 수 없음' 실패 케이스

감사합니다. 또 놓친 부분 있다면 말씀주시고 없으시면 머지할게요

Copy link
Contributor

@ekgns33 ekgns33 left a comment

Choose a reason for hiding this comment

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

LGTM! 머지하죠

@jeeheaG jeeheaG merged commit 884a3f2 into main May 26, 2025
4 checks passed
@jeeheaG jeeheaG deleted the feat/logout branch May 26, 2025 14:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants