Skip to content

Conversation

@nahowo
Copy link
Contributor

@nahowo nahowo commented Nov 21, 2024

Summary

Redis와 리프레시 토큰 로직 추가

Description

feat

  • config > redis 디렉토리 추가
    • 테스트용 RefreshTokenController, CreateRefreshTokenRequest 생성
    • RefreshToken 생성: RedisHash로 도메인 생성
    • RefreshTokenRepository 생성: RefreshToken 엔티티 관리
    • RefreshTokenService 생성: redis로 RefreshToken 저장, 조회, 생성
  • jwt 파일 수정
    • JwtController 수정: createRefreshToken 추가
    • JwtTokenProvider 수정
      • resolveToken에서 토큰이 존재하지 않을 시 null을 리턴하는 대신 예외를 던지도록 수정
      • validateToken에서 토큰 만료 시 예외를 던지는 대신 false를 리턴하도록 수정
      • getEmailFromToken에서 만료된 토큰에서도 이메일 추출이 가능하도록 수정
    • JwtAuthenticationFilter 수정: doFilterInternal 검증 로직 수정
      • 토큰 null 여부 검증 로직 삭제
      • 액세스 토큰 만료 시 이메일로 리프레시 토큰 추출, 새 액세스 토큰을 발급해 redis에 저장
      • 액세스 토큰 재발급 시 리프레시 토큰도 재발급하는 로직 제거

fix

  • userService.updateUserDetail: 유저 정보 업데이트가 안 되는 문제 해결

Screenshot

Test Checklist

  • 체크리스트

Summary by CodeRabbit

  • 신규 기능

    • Redis 기반의 리프레시 토큰 저장 및 관리 기능이 추가되었습니다.
    • 리프레시 토큰 관련 신규 API 엔드포인트가 제공됩니다.
  • 버그 수정

    • 기존 사용자 정보 반환 시 리프레시 토큰이 포함되지 않도록 수정되었습니다.
  • 리팩터

    • 리프레시 토큰 발급, 저장, 삭제 로직이 서비스 계층으로 분리되어 관리됩니다.
    • JWT 인증 필터와 인증 성공 처리 로직이 리프레시 토큰 서비스와 연동되도록 개선되었습니다.
  • 문서화

    • Swagger 문서에 리프레시 토큰 관련 보안 스키마가 단순화되었습니다.
  • 환경설정

    • Redis 서비스가 docker-compose에 추가되어 운영 환경에서 자동으로 실행됩니다.
    • Spring Boot Redis 스타터가 의존성에 추가되었습니다.

@nahowo nahowo requested a review from dlwhsk0 November 21, 2024 13:00
@nahowo nahowo self-assigned this Nov 21, 2024
@nahowo nahowo linked an issue Nov 21, 2024 that may be closed by this pull request
@nahowo nahowo marked this pull request as draft April 1, 2025 23:56
@nahowo
Copy link
Contributor Author

nahowo commented Apr 4, 2025

2025.4.5 추가

refresh 재발급

  • redis 캐시값 업데이트
  • 테스트 이외에는 refresh 재발급 로직이 없기 때문에 블랙리스트는 처리하지 않음

토큰에 type 필드 추가

  • 만료되지 않은 refresh 토큰을 사용해도 요청이 성공하는 오류 발생
    • 토큰에 type 필드를 추가해 access 토큰만 요청을 수행하도록 수정

Redis-MySQL 동기화

  • DataInitializer에 redis 목업 데이터 추가
  • User 삭제 시 redis 캐시 제거

@nahowo nahowo marked this pull request as ready for review April 4, 2025 23:58
@nahowo nahowo merged commit 5a7d6f4 into develop Apr 14, 2025
1 check passed
@nahowo nahowo deleted the refactor/#97 branch April 14, 2025 03:07
@nahowo
Copy link
Contributor Author

nahowo commented Apr 15, 2025

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Apr 15, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link

coderabbitai bot commented Apr 15, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

이번 변경 사항은 리프레시 토큰(Refresh Token)의 발급, 저장, 검증 및 재발급을 Redis 기반으로 전환하는 데 중점을 두고 있습니다. 이를 위해 Redis 연동 설정, 토큰 엔티티 및 저장소, 서비스, 컨트롤러가 추가되었으며, 기존 JWT 인증 및 사용자 서비스 로직이 새 리프레시 토큰 서비스와 통합되었습니다. 또한 도커 컴포즈에 Redis 서비스가 추가되고, Spring Boot 프로젝트에 Redis 의존성이 포함되었습니다. Swagger 및 CI/CD, DTO, 결과 코드 등도 이에 맞게 수정되었습니다.

Changes

파일/경로 변경 요약
.github/workflows/cicd.yml 배포 단계(SSH를 통한 원격 배포) 전체 주석 처리
build.gradle Redis Starter 의존성 추가, 슬랙 API 의존성 선언 방식 변경
docker-compose.yml Redis 서비스 추가, springboot 서비스에 build 명시, 서비스 순서 조정
src/main/java/com/Alchive/backend/config/DataInitializer.java RefreshTokenService 의존성 주입 및 초기 사용자에 대한 리프레시 토큰 생성/저장 로직 추가
src/main/java/com/Alchive/backend/config/SwaggerConfig.java Swagger에서 Refresh Token 보안 스키마 제거
src/main/java/com/Alchive/backend/config/auth/SecurityConfig.java RefreshTokenService 필드 및 JwtAuthenticationFilter 생성자 인자 추가
src/main/java/com/Alchive/backend/config/auth/handler/OAuth2SuccessHandler.java RefreshTokenService를 통한 리프레시 토큰 생성/저장, 리다이렉트 URL에서 리프레시 토큰 제거
src/main/java/com/Alchive/backend/config/jwt/JwtAuthenticationFilter.java RefreshTokenService 연동, 리프레시 토큰 검증 및 액세스 토큰 재발급 로직 추가, 예외 처리 및 로그 보강
src/main/java/com/Alchive/backend/config/jwt/JwtController.java 토큰 재발급 메서드명, 경로, 결과 코드 명확화 및 수정
src/main/java/com/Alchive/backend/config/jwt/JwtTokenProvider.java 토큰 타입(ACCESS/REFRESH) 클레임 분리, 토큰 검증 및 추출 로직 개선, 예외 처리 강화
src/main/java/com/Alchive/backend/config/redis/CreateRefreshTokenRequest.java 리프레시 토큰 저장 요청용 DTO 클래스 신설
src/main/java/com/Alchive/backend/config/redis/RefreshToken.java Redis 해시 기반 리프레시 토큰 엔티티 클래스 신설(TTL, 인덱스 포함)
src/main/java/com/Alchive/backend/config/redis/RefreshTokenController.java 리프레시 토큰 저장, 조회, 신규 발급 API 컨트롤러 신설
src/main/java/com/Alchive/backend/config/redis/RefreshTokenRepository.java 리프레시 토큰 Redis CRUD 리포지토리 인터페이스 신설
src/main/java/com/Alchive/backend/config/redis/RefreshTokenService.java 리프레시 토큰 생성, 저장, 조회, 삭제 서비스 클래스 신설
src/main/java/com/Alchive/backend/config/result/ResultCode.java 토큰 관련 결과 코드 명칭 변경 및 신규 코드 추가(TOKEN_REFRESH_SAVE_SUCCESS 등)
src/main/java/com/Alchive/backend/dto/response/UserResponseDTO.java refreshToken 필드 및 생성자 파라미터 제거
src/main/java/com/Alchive/backend/service/UserService.java RefreshTokenService 연동, 리프레시 토큰 생성/저장/삭제 로직 추가 및 기존 로직 수정

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant JwtAuthenticationFilter
    participant RefreshTokenService
    participant JwtTokenProvider
    participant UserService

    Client->>JwtAuthenticationFilter: 요청(Access Token 포함)
    JwtAuthenticationFilter->>JwtTokenProvider: Access Token 유효성 검사
    alt Access Token 유효
        JwtAuthenticationFilter->>UserService: 사용자 인증
        JwtAuthenticationFilter-->>Client: 정상 응답
    else Access Token 만료/무효
        JwtAuthenticationFilter->>RefreshTokenService: 이메일로 Refresh Token 조회
        RefreshTokenService-->>JwtAuthenticationFilter: Refresh Token 반환
        JwtAuthenticationFilter->>JwtTokenProvider: Refresh Token 유효성 검사
        alt Refresh Token 유효
            JwtAuthenticationFilter->>JwtTokenProvider: 새 Access Token 생성
            JwtAuthenticationFilter-->>Client: 새 Access Token 헤더로 응답
        else Refresh Token 만료/무효
            JwtAuthenticationFilter-->>Client: 인증 실패(토큰 만료)
        end
    end
Loading
sequenceDiagram
    participant UserService
    participant RefreshTokenService
    participant RefreshTokenRepository
    participant JwtTokenProvider

    UserService->>RefreshTokenService: createRefreshToken(email)
    RefreshTokenService->>JwtTokenProvider: 토큰 생성 요청(email, type=REFRESH)
    JwtTokenProvider-->>RefreshTokenService: Refresh Token 반환
    RefreshTokenService->>RefreshTokenRepository: 저장(email, refreshToken)
    RefreshTokenRepository-->>RefreshTokenService: 저장 완료
    RefreshTokenService-->>UserService: Refresh Token 반환
Loading

Poem

🥕
리프레시 토큰 hop! hop!
Redis 속에 쏙쏙 저장,
만료되면 다시 hop!
새 토큰으로 깡총깡총,
깔끔한 인증 흐름 완성!
토끼도 안심하고 로그인~
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 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 e912afe and 8d90b31.

📒 Files selected for processing (18)
  • .github/workflows/cicd.yml (1 hunks)
  • build.gradle (1 hunks)
  • docker-compose.yml (1 hunks)
  • src/main/java/com/Alchive/backend/config/DataInitializer.java (3 hunks)
  • src/main/java/com/Alchive/backend/config/SwaggerConfig.java (1 hunks)
  • src/main/java/com/Alchive/backend/config/auth/SecurityConfig.java (3 hunks)
  • src/main/java/com/Alchive/backend/config/auth/handler/OAuth2SuccessHandler.java (3 hunks)
  • src/main/java/com/Alchive/backend/config/jwt/JwtAuthenticationFilter.java (5 hunks)
  • src/main/java/com/Alchive/backend/config/jwt/JwtController.java (2 hunks)
  • src/main/java/com/Alchive/backend/config/jwt/JwtTokenProvider.java (3 hunks)
  • src/main/java/com/Alchive/backend/config/redis/CreateRefreshTokenRequest.java (1 hunks)
  • src/main/java/com/Alchive/backend/config/redis/RefreshToken.java (1 hunks)
  • src/main/java/com/Alchive/backend/config/redis/RefreshTokenController.java (1 hunks)
  • src/main/java/com/Alchive/backend/config/redis/RefreshTokenRepository.java (1 hunks)
  • src/main/java/com/Alchive/backend/config/redis/RefreshTokenService.java (1 hunks)
  • src/main/java/com/Alchive/backend/config/result/ResultCode.java (1 hunks)
  • src/main/java/com/Alchive/backend/dto/response/UserResponseDTO.java (1 hunks)
  • src/main/java/com/Alchive/backend/service/UserService.java (4 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

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.

[refactor] 토큰 저장을 위한 Redis 추가

2 participants