Skip to content

feat: impl BoundedBCryptPasswordEncoder and Redis cache configuration - #65

Merged
jaejo merged 5 commits into
developfrom
feature/login-refactor
Aug 10, 2026
Merged

feat: impl BoundedBCryptPasswordEncoder and Redis cache configuration#65
jaejo merged 5 commits into
developfrom
feature/login-refactor

Conversation

@jaejo

@jaejo jaejo commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

작업 내용

  • BCrypt 동시성 제한 래퍼(BoundedBCryptPasswordEncoder) 구현
  • 유저 정보 Redis 캐시 레이어 (UserCacheService & CacheConfig) 구축
  • 유저 정보 변경 시 캐시 정합성(Cache Eviction) 보장
  • Spring Security 로그인 실패 핸들러(LoginFailureHandler) 예외 응답 개선
  • JWT 인증 필터(JwtAuthenticationFilter) 비활성 계정 검증 강화

변경 사항

체크리스트

  • 테스트 코드 작성 완료
  • 리뷰어 지정 완료

참고 사항

관련 이슈

Summary by CodeRabbit

요약

  • 새 기능

    • 사용자 정보와 인증 조회에 캐시를 적용해 반복 조회 성능을 개선했습니다.
    • 로그인 처리 동시성을 제어해 서버 과부하를 완화합니다.
  • 버그 수정

    • 정지 또는 탈퇴한 계정의 인증을 차단합니다.
    • 정지·탈퇴 계정 로그인 실패 시 정확한 오류를 안내합니다.
    • 이메일 형식을 일관되게 처리해 인증 안정성을 높였습니다.
  • 개선 사항

    • 사용자 정보 변경 시 관련 캐시가 자동으로 무효화됩니다.
    • 서버가 일시적으로 혼잡할 때 재시도 안내와 서비스 이용 불가 상태를 표시합니다.

@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 8465b443-f250-4a94-8ec7-22224830fe57

📥 Commits

Reviewing files that changed from the base of the PR and between 9ae56b3 and 2458fd7.

📒 Files selected for processing (3)
  • momogo-api/src/main/java/com/momogo/api/auth/handler/LoginFailureHandler.java
  • momogo-api/src/main/java/com/momogo/api/auth/listener/UserSessionEventListener.java
  • momogo-core/src/main/java/com/momogo/core/domain/user/service/UserCacheService.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • momogo-api/src/main/java/com/momogo/api/auth/listener/UserSessionEventListener.java

📝 Walkthrough

Walkthrough

BCrypt 인증 동시성 제한, Redis 사용자 응답 캐시, 사용자 상태 변경 후 캐시 무효화, 정지·탈퇴 계정 인증 검사가 추가되었습니다.

Changes

인증 처리량 제한

Layer / File(s) Summary
BCrypt 동시성 제한과 인증 설정
momogo-api/.../security/BoundedBCryptPasswordEncoder.java, momogo-api/.../config/SecurityConfig.java, momogo-core/.../exception/AuthErrorCode.java, momogo-api/.../handler/LoginFailureHandler.java, momogo-api/src/main/resources/application.yaml
BCrypt encodematches의 동시 실행을 제한합니다. 슬롯 획득 실패 시 LOGIN_SERVER_BUSY를 사용합니다. 인증 공급자는 주입된 PasswordEncoder를 사용합니다.

사용자 캐시 및 인증 연동

Layer / File(s) Summary
Redis 사용자 캐시 기반
momogo-api/.../config/CacheConfig.java, momogo-core/.../service/UserCacheService.java
user_dtos Redis 캐시를 30분 TTL로 설정합니다. 정규화된 이메일로 UserResponse를 조회하고 캐시 미스 시 저장합니다.
인증 사용자 조회 연동
momogo-api/.../auth/details/*, momogo-api/.../auth/jwt/JwtAuthenticationFilter.java
토큰 인증과 OAuth2 인증이 캐시된 사용자 응답을 사용합니다. 탈퇴 계정은 비활성화하고, 정지·탈퇴 계정의 JWT 인증을 차단합니다.
사용자 변경 시 캐시 무효화
momogo-core/.../domain/user/event/UserCacheEvictEvent.java, momogo-core/.../domain/user/service/UserServiceImpl.java, momogo-api/.../auth/listener/UserSessionEventListener.java
사용자 수정, 삭제, 복구, 밴 상태 변경 후 커밋 시점에 정규화된 이메일 기준으로 user_dtos 캐시를 제거합니다.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant OAuth2UserDetailsService
  participant UserCacheService
  participant RedisCacheManager
  participant UserRepository
  participant UserSessionEventListener

  OAuth2UserDetailsService->>UserCacheService: 정규화된 이메일로 UserResponse 조회
  UserCacheService->>RedisCacheManager: user_dtos 캐시 조회
  alt 캐시 미스
    UserCacheService->>UserRepository: 사용자 조회
    UserRepository-->>UserCacheService: User
    UserCacheService->>RedisCacheManager: UserResponse 저장
  end
  UserCacheService-->>OAuth2UserDetailsService: UserResponse
  UserSessionEventListener->>RedisCacheManager: 커밋 후 user_dtos 캐시 제거
Loading

Possibly related PRs

Suggested reviewers: sunghuii

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 BoundedBCryptPasswordEncoder 구현과 Redis 캐시 설정이라는 변경의 주요 내용을 정확하고 간결하게 요약합니다.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/login-refactor

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
momogo-api/src/main/java/com/momogo/api/auth/security/BoundedBCryptPasswordEncoder.java (1)

74-87: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

LOGIN_SERVER_BUSY이 인증 실패 핸들러를 통과하도록 예외를 감싸세요.

BusinessExceptionAuthenticationException이 아니므로, UsernamePasswordAuthenticationFilteronAuthenticationFailure(handler) 호출에는 전달되지 않습니다. 이 경우 /api/auth/sign-in에서 정의한 503/AUTH-6014 응답이 나오지 않고, 일반 전역 예외 핸들러나 서블릿 오류 경로를 타게 됩니다.

PasswordEncoder.matches(...) 내부에서 BusinessException(AuthErrorCode.LOGIN_SERVER_BUSY)가 발생할 때, AuthenticationException(예: InternalAuthenticationServiceException)에 wrapping하여 AuthenticationFailureHandler가 처리할 수 있도록 바꾸거나, 이 코드 경로에서 의도한 503 응답을 필터 예외 처리 전에 별도 처리하세요.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@momogo-api/src/main/java/com/momogo/api/auth/security/BoundedBCryptPasswordEncoder.java`
around lines 74 - 87, Update the interrupted-operation path in
BoundedBCryptPasswordEncoder so LOGIN_SERVER_BUSY is propagated as an
AuthenticationException, such as InternalAuthenticationServiceException, rather
than only as BusinessException. Preserve the existing error code, 503 response
mapping, and interrupt restoration while ensuring
UsernamePasswordAuthenticationFilter routes the failure through its
AuthenticationFailureHandler.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@momogo-api/src/main/java/com/momogo/api/auth/details/OAuth2UserDetailsService.java`:
- Around line 69-70: Move cache writes and invalidations for user state changes
to execute only after transaction commit. In
OAuth2UserDetailsService.java:69-70, remove getUserResponseCached(String
normalizedEmail) from the transactional registerSocialUser()/user.restore()
path, retaining only the existing-user cache lookup or adding a post-commit
refresh. In UserServiceImpl.java:122, 215-219, 254, and 379, update user change,
deletion, restoration, and ban-status cache handling to use
CommitTransactionApplicationEvent with AFTER_COMMIT, or
TransactionSynchronizationManager.afterCommit(), and consolidate
restoration/deletion invalidation through the existing UserSessionEventListener
user-event pattern.

In
`@momogo-api/src/main/java/com/momogo/api/auth/security/BoundedBCryptPasswordEncoder.java`:
- Around line 39-42: Validate maxConcurrency in the BoundedBCryptPasswordEncoder
constructor and explicitly reject values below 1 before creating the Semaphore.
Preserve the existing initialization for valid values so misconfigured
deployments fail at startup rather than allowing an unusable semaphore.

In
`@momogo-core/src/main/java/com/momogo/core/domain/user/service/UserCacheService.java`:
- Around line 34-43: JWT 인증 경로의 loadUserByUsernameForToken()에서 deletedAt을 무시하지
않도록 활성 사용자 조건을 적용하십시오. UserResponse.deletedAt을 기준으로 탈퇴 대기·만료 사용자가
MoMoGoUserDetails로 생성되지 않게 하고, isEnabled() 및 isAccountNonLocked() 검사가 동일한 활성 사용자
기준을 사용하도록 수정하십시오. 기존 로그인 경로의 탈퇴 검증 기준과 일치시키되 다른 캐시 조회 동작은 유지하십시오.

---

Nitpick comments:
In
`@momogo-api/src/main/java/com/momogo/api/auth/security/BoundedBCryptPasswordEncoder.java`:
- Around line 74-87: Update the interrupted-operation path in
BoundedBCryptPasswordEncoder so LOGIN_SERVER_BUSY is propagated as an
AuthenticationException, such as InternalAuthenticationServiceException, rather
than only as BusinessException. Preserve the existing error code, 503 response
mapping, and interrupt restoration while ensuring
UsernamePasswordAuthenticationFilter routes the failure through its
AuthenticationFailureHandler.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 54719453-83fa-44a9-b75f-5c52e1536928

📥 Commits

Reviewing files that changed from the base of the PR and between 7135f48 and b516d5b.

📒 Files selected for processing (10)
  • momogo-api/src/main/java/com/momogo/api/auth/config/SecurityConfig.java
  • momogo-api/src/main/java/com/momogo/api/auth/details/MoMoGoUserDetailsService.java
  • momogo-api/src/main/java/com/momogo/api/auth/details/OAuth2UserDetailsService.java
  • momogo-api/src/main/java/com/momogo/api/auth/security/BoundedBCryptPasswordEncoder.java
  • momogo-api/src/main/java/com/momogo/api/common/config/CacheConfig.java
  • momogo-api/src/main/resources/application.yaml
  • momogo-core/build.gradle
  • momogo-core/src/main/java/com/momogo/core/common/exception/AuthErrorCode.java
  • momogo-core/src/main/java/com/momogo/core/domain/user/service/UserCacheService.java
  • momogo-core/src/main/java/com/momogo/core/domain/user/service/UserServiceImpl.java

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@momogo-api/src/main/java/com/momogo/api/auth/listener/UserSessionEventListener.java`:
- Around line 62-70: Remove the `@Async` annotation from handleUserCacheEvictEvent
so the USER_DTO_CACHE eviction runs synchronously after the transaction commits.
Leave the `@TransactionalEventListener` configuration and existing cache eviction
logic unchanged.

In
`@momogo-api/src/main/java/com/momogo/api/auth/security/BoundedBCryptPasswordEncoder.java`:
- Around line 40-42: BoundedBCryptPasswordEncoder의 초기화 검증에 acquireTimeoutMs 음수
거부 조건을 추가하세요. acquireTimeoutMs가 0인 fail-fast 설정은 허용하고, 0보다 작은 경우에만 명확한
IllegalArgumentException을 발생시키도록 기존 maxConcurrency 검증과 같은 시작 시점 검증 흐름을 유지하세요.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f3fed343-1e80-42ac-95c1-aea9437e072e

📥 Commits

Reviewing files that changed from the base of the PR and between b516d5b and 6c34aa3.

📒 Files selected for processing (8)
  • momogo-api/src/main/java/com/momogo/api/auth/details/MoMoGoUserDetails.java
  • momogo-api/src/main/java/com/momogo/api/auth/details/OAuth2UserDetailsService.java
  • momogo-api/src/main/java/com/momogo/api/auth/handler/LoginFailureHandler.java
  • momogo-api/src/main/java/com/momogo/api/auth/jwt/JwtAuthenticationFilter.java
  • momogo-api/src/main/java/com/momogo/api/auth/listener/UserSessionEventListener.java
  • momogo-api/src/main/java/com/momogo/api/auth/security/BoundedBCryptPasswordEncoder.java
  • momogo-core/src/main/java/com/momogo/core/domain/user/event/UserCacheEvictEvent.java
  • momogo-core/src/main/java/com/momogo/core/domain/user/service/UserServiceImpl.java

… into feature/login-refactor

# Conflicts:
#	momogo-core/build.gradle

@SungHuii SungHuii left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

수고하셨습니다 👍

@idktomorrow idktomorrow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

저는 따로 문제점 없어 보입니다! 고생 많으셨습니다 ❤️

@jaejo
jaejo merged commit 2cbfb22 into develop Aug 10, 2026
2 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.

3 participants