Skip to content

🔀 File Directory Refactor#30

Merged
ohyuchan123 merged 9 commits intodevelopfrom
refactor/file-directory
Jan 8, 2025
Merged

🔀 File Directory Refactor#30
ohyuchan123 merged 9 commits intodevelopfrom
refactor/file-directory

Conversation

@ohyuchan123
Copy link
Member

@ohyuchan123 ohyuchan123 commented Jan 8, 2025

📌 관련 이슈

#28 코드 구조 개선

✨ 과제 내용

기존에 코더 래빗이 제시해준 코드를 해결하는데만 집중하여 점점
불필요한 코드들이나 코드들이 뒤죽박죽 되어가서 코드 구조 및 기존 코드들과 함께 통일화 하는 과정입니다.

📸 스크린샷(선택)

📚 레퍼런스 (또는 새로 알게 된 내용) 혹은 궁금한 사항들

Summary by CodeRabbit

릴리즈 노트

  • 새로운 기능

    • JWT 토큰 관리를 위한 구성 가능한 속성 추가
    • 이메일 인증 프로세스 개선
    • 로그인 및 회원가입 응답 구조 최적화
  • 개선 사항

    • 쿠키 생성 및 관리 유틸리티 추가
    • 인증 관련 DTO 이름 및 구조 리팩토링
    • 보안 설정 및 토큰 처리 로직 강화
  • 버그 수정

    • 이메일 인증 및 로그인 프로세스의 오류 처리 개선

@ohyuchan123 ohyuchan123 self-assigned this Jan 8, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jan 8, 2025

워크스루

이 풀 리퀘스트는 인증 및 보안 관련 코드의 광범위한 리팩토링을 포함합니다. 주요 변경 사항은 DTO 클래스 이름 변경, JWT 속성 구성 도입, 쿠키 관리 유틸리티 추가, 이메일 인증 프로세스 개선 등을 포함합니다. 이러한 변경은 코드의 구조화, 구성 가능성 및 오류 처리를 향상시키는 데 중점을 두고 있습니다.

변경 사항

파일 변경 요약
SecurityConfig.java JWT 속성 주입 및 필터 구성 업데이트
AuthController.java DTO 이름 변경, 메서드 시그니처 업데이트
JWTFilter.java 인증 로직 모듈화, JWT 속성 통합
JWTUtil.java 토큰 생성 및 검증 로직 리팩토링
MailService.java 이메일 검증 응답 구조 개선
AuthService.java 로그인, 등록, 로그아웃 메서드 업데이트

제안된 레이블

🔨 Refactor

관련 가능성 있는 PR

시퀀스 다이어그램

sequenceDiagram
    participant Client
    participant AuthController
    participant AuthService
    participant MailService
    participant JWTUtil

    Client->>AuthController: 로그인 요청
    AuthController->>AuthService: 로그인 처리
    AuthService->>JWTUtil: 토큰 생성
    JWTUtil-->>AuthService: 토큰 반환
    AuthService-->>AuthController: 로그인 응답
    AuthController->>Client: 인증 쿠키 및 로그인 응답
Loading

시 (토끼의 관점에서)

🐰 코드의 숲을 달리며
JWT의 새 길을 열어
리팩토링의 바람결에
보안은 더욱 단단해지고
우리의 애플리케이션은 춤을 춘다! 🌟


🪧 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. (Beta)
  • @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.

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.

@ohyuchan123 ohyuchan123 added ✅ Test test 관련(storybook, jest...) 🔨 Refactor 코드 리팩토링 ✨ Feature 기능 개발 labels Jan 8, 2025
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: 8

🧹 Nitpick comments (13)
src/main/java/com/mycom/socket/auth/service/data/VerificationData.java (2)

15-17: 정적 팩토리 메서드의 구현이 명확합니다만, 유효 기간을 설정 가능하게 만드는 것이 좋겠습니다.

CODE_VALID_DURATION을 설정 파일이나 환경 변수를 통해 구성 가능하게 만드는 것을 고려해보세요. 이는 다양한 환경에서의 유연성을 높여줄 것입니다.


27-29: 메서드 이름을 더 명확하게 변경하는 것이 좋겠습니다.

withVerified 보다는 createVerifiedCopy나 markAsVerified와 같이 더 명시적인 이름을 사용하면 메서드의 의도를 더 잘 전달할 수 있을 것 같습니다.

-    public VerificationData withVerified() {
+    public VerificationData createVerifiedCopy() {
         return new VerificationData(this.code, this.expiryTime, true);
     }
src/main/java/com/mycom/socket/auth/service/MailService.java (3)

72-72: 이메일 주소의 형식 검증을 추가하는 것을 권장드립니다.

sendMail 메서드에서 전달받은 email 파라미터에 대해 이메일 형식이 올바른지 검증하여 유효하지 않은 이메일로 메일을 발송하는 것을 방지하는 것이 좋습니다.


76-78: verificationDataMap의 만료된 데이터 제거를 고려해보세요.

인증 코드가 만료되거나 사용된 후에도 verificationDataMap에 데이터가 남아있어 메모리 누수가 발생할 수 있습니다. 만료된 데이터나 인증된 데이터를 주기적으로 제거하는 로직을 추가하는 것을 권장합니다.

Also applies to: 107-108


117-120: isEmailVerified 메서드의 null 체크 및 예외 처리 검토

isEmailVerified 메서드에서 verificationDataMap.get(email)null인 경우 data.isExpired()에서 NullPointerException이 발생하지 않도록 안전한 접근을 하고 있습니다. 그러나 이메일이 인증되지 않았을 경우에 대한 명확한 예외 처리나 로그를 추가하면 디버깅에 도움이 될 수 있습니다.

src/main/java/com/mycom/socket/auth/dto/response/RegisterResponse.java (1)

9-11: 메시지 처리 개선 제안

성공 메시지가 코드에 직접 하드코딩되어 있습니다. 다국어 지원이나 메시지 관리를 위해 별도의 메시지 설정 파일로 분리하는 것을 고려해보세요.

+    private static final String REGISTER_SUCCESS_MESSAGE = "회원가입이 완료되었습니다.";
     public static RegisterResponse of(Long memberId, String email, String nickname) {
-        return new RegisterResponse(memberId, email, nickname, "회원가입이 완료되었습니다.");
+        return new RegisterResponse(memberId, email, nickname, REGISTER_SUCCESS_MESSAGE);
     }
src/main/java/com/mycom/socket/auth/security/CookieUtil.java (1)

28-35: 만료 쿠키 생성 시 보안 설정 개선이 필요합니다.

만료 쿠키 생성 시 secure 설정을 하드코딩하지 말고 JWTProperties에서 가져오는 것이 좋습니다.

-        cookie.setSecure(true);
+        cookie.setSecure(jwtProperties.isSecureCookie());
src/main/java/com/mycom/socket/auth/jwt/JWTFilter.java (1)

Line range hint 44-52: 쿠키 검증 로직 개선이 필요합니다.

null 체크 외에도 쿠키 값의 유효성 검증을 추가하는 것이 좋습니다.

 private String resolveTokenFromCookie(HttpServletRequest request) {
     Cookie[] cookies = request.getCookies();
     if (cookies != null) {
         for (Cookie cookie : cookies) {
             if (jwtProperties.getCookieName().equals(cookie.getName())) {
-                return cookie.getValue();
+                String value = cookie.getValue();
+                if (StringUtils.hasText(value)) {
+                    return value;
+                }
             }
         }
     }
     return null;
 }
src/main/java/com/mycom/socket/auth/security/LoginFilter.java (1)

Line range hint 44-45: 예외 메시지를 더 구체적으로 작성해주세요.

현재 예외 메시지가 너무 일반적입니다. 사용자가 문제를 더 쉽게 파악할 수 있도록 구체적인 정보를 제공하면 좋겠습니다.

-throw new RuntimeException("로그인 요청 처리 중 오류가 발생했습니다.", e);
+throw new RuntimeException("로그인 요청 데이터 파싱 중 오류가 발생했습니다. 요청 형식을 확인해주세요.", e);
src/test/java/com/mycom/socket/member/service/RegisterServiceTest.java (1)

71-77: 비밀번호 인코딩 검증을 추가해주세요.

회원가입 성공 테스트에서 비밀번호 인코딩이 올바르게 수행되었는지 검증이 누락되었습니다.

다음과 같이 검증을 추가하는 것을 제안합니다:

 assertThat(response.email()).isEqualTo(request.email());
 assertThat(response.nickname()).isEqualTo(request.nickname());
 assertThat(response.message()).isEqualTo("회원가입이 완료되었습니다.");

 verify(memberRepository).save(any(Member.class));
 verify(mailService).isEmailVerified(request.email());
+verify(passwordEncoder).encode(request.password());
src/test/java/com/mycom/socket/member/service/LoginTest.java (1)

65-69: 쿠키 속성을 상수로 추출해주세요.

테스트의 가독성과 유지보수성을 높이기 위해 쿠키 속성값들을 상수로 추출하는 것이 좋겠습니다.

다음과 같이 수정을 제안합니다:

+private static final String COOKIE_NAME = "Authorization";
+private static final int COOKIE_MAX_AGE = 1800;
+private static final String COOKIE_PATH = "/";

 Cookie authCookie = new Cookie("Authorization", token);
 authCookie.setHttpOnly(true);
 authCookie.setSecure(true);
-authCookie.setPath("/");
-authCookie.setMaxAge(1800);
+authCookie.setPath(COOKIE_PATH);
+authCookie.setMaxAge(COOKIE_MAX_AGE);
src/test/java/com/mycom/socket/member/controller/AuthControllerTest.java (2)

113-119: 테스트 데이터의 상수화가 필요합니다.

테스트 헬퍼 메서드에서 사용되는 고정값들을 상수로 추출하면 테스트의 의도가 더 명확해질 것 같습니다.

다음과 같이 수정을 제안합니다:

+private static final Long TEST_MEMBER_ID = 1L;
+private static final String TEST_EMAIL = "test@example.com";
+private static final String TEST_NICKNAME = "testUser";
+private static final String TEST_PASSWORD = "password123";
+private static final String TEST_INTRO = "안녕하세요";

 private RegisterRequest createRegisterRequest(String email, String nickname, String password) {
-    return new RegisterRequest(email, nickname, password, "안녕하세요");
+    return new RegisterRequest(email, nickname, password, TEST_INTRO);
 }

 private RegisterResponse createRegisterResponse(Long memberId, String email, String nickname) {
     return RegisterResponse.of(memberId, email, nickname);
 }

97-110: 소개글(intro) 필드에 대한 유효성 검증 테스트를 추가해주세요.

현재 이메일, 닉네임, 비밀번호에 대한 유효성 검증은 테스트되고 있지만, 소개글 필드에 대한 검증이 누락되었습니다.

다음과 같은 테스트 케이스 추가를 제안합니다:

@Test
@WithMockUser
void 회원가입_실패_소개글_길이초과() throws Exception {
    // given
    String longIntro = "a".repeat(1001); // 1000자 초과
    RegisterRequest request = createRegisterRequest(TEST_EMAIL, TEST_NICKNAME, TEST_PASSWORD, longIntro);

    // when
    ResultActions resultActions = performRegisterRequest(request);

    // then
    resultActions
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.message").value("소개글은 1000자를 초과할 수 없습니다."));
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a86e950 and 15b650b.

📒 Files selected for processing (24)
  • src/main/java/com/mycom/socket/auth/config/SecurityConfig.java (3 hunks)
  • src/main/java/com/mycom/socket/auth/controller/AuthController.java (2 hunks)
  • src/main/java/com/mycom/socket/auth/dto/request/EmailRequest.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/dto/request/EmailVerificationRequest.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/dto/request/LoginRequest.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/dto/request/RegisterRequest.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/dto/response/EmailVerificationCheckResponseDto.java (0 hunks)
  • src/main/java/com/mycom/socket/auth/dto/response/EmailVerificationResponse.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/dto/response/EmailVerificationResponseDto.java (0 hunks)
  • src/main/java/com/mycom/socket/auth/dto/response/LoginResponse.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/dto/response/LoginResponseDto.java (0 hunks)
  • src/main/java/com/mycom/socket/auth/dto/response/RegisterResponse.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/jwt/JWTFilter.java (3 hunks)
  • src/main/java/com/mycom/socket/auth/jwt/JWTProperties.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/jwt/JWTUtil.java (2 hunks)
  • src/main/java/com/mycom/socket/auth/security/CookieUtil.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/security/LoginFilter.java (3 hunks)
  • src/main/java/com/mycom/socket/auth/service/AuthService.java (5 hunks)
  • src/main/java/com/mycom/socket/auth/service/MailService.java (3 hunks)
  • src/main/java/com/mycom/socket/auth/service/data/VerificationData.java (1 hunks)
  • src/test/java/com/mycom/socket/member/controller/AuthControllerTest.java (3 hunks)
  • src/test/java/com/mycom/socket/member/service/LoginIntegrationTest.java (3 hunks)
  • src/test/java/com/mycom/socket/member/service/LoginTest.java (4 hunks)
  • src/test/java/com/mycom/socket/member/service/RegisterServiceTest.java (4 hunks)
💤 Files with no reviewable changes (3)
  • src/main/java/com/mycom/socket/auth/dto/response/EmailVerificationResponseDto.java
  • src/main/java/com/mycom/socket/auth/dto/response/EmailVerificationCheckResponseDto.java
  • src/main/java/com/mycom/socket/auth/dto/response/LoginResponseDto.java
✅ Files skipped from review due to trivial changes (2)
  • src/main/java/com/mycom/socket/auth/dto/request/RegisterRequest.java
  • src/main/java/com/mycom/socket/auth/dto/request/LoginRequest.java
🔇 Additional comments (17)
src/main/java/com/mycom/socket/auth/service/data/VerificationData.java (2)

7-11: 레코드 선언이 잘 되어있습니다!

불변성을 보장하는 record 타입의 사용이 적절하며, 검증 상태를 추적하기 위한 verified 필드의 추가가 좋습니다.


19-20: 생성자 구현이 적절합니다!

기본 생성자가 주 생성자에게 적절히 위임하고 있으며, 기본값 설정이 일관성 있게 되어 있습니다.

src/main/java/com/mycom/socket/auth/controller/AuthController.java (1)

3-9: 새로운 DTO 클래스가 올바르게 임포트되었습니다.

DTO 클래스들의 패키지 경로 및 이름 변경이 정확하게 반영되었습니다.

src/main/java/com/mycom/socket/auth/service/AuthService.java (1)

50-50: 쿠키 설정 시 보안 옵션을 확인하십시오.

CookieUtil을 사용하여 쿠키를 생성할 때, 쿠키에 HttpOnly, Secure와 같은 보안 속성이 설정되어 있는지 확인하는 것이 좋습니다. 이를 통해 쿠키 탈취 등의 위험을 줄일 수 있습니다.

Also applies to: 103-103

src/main/java/com/mycom/socket/auth/dto/response/EmailVerificationResponse.java (1)

3-9: EmailVerificationResponse 레코드 정의가 적절합니다.

간결하고 불변 객체를 나타내기 위해 자바 레코드를 사용한 것은 좋은 선택입니다.

src/main/java/com/mycom/socket/auth/dto/response/LoginResponse.java (1)

3-10: LoginResponse 레코드 정의가 적절합니다.

로그인 응답 데이터를 간결하게 표현하기 위해 자바 레코드를 활용한 것은 효율적입니다.

src/main/java/com/mycom/socket/auth/dto/request/EmailRequest.java (1)

Line range hint 6-11: DTO 이름 변경이 일관성 있게 적용되었습니다.

클래스 이름에서 Dto 접미사를 제거한 변경이 전체적인 리팩토링 방향과 잘 일치합니다. 이메일 유효성 검사도 적절하게 구현되어 있습니다.

src/main/java/com/mycom/socket/auth/dto/request/EmailVerificationRequest.java (1)

Line range hint 7-15: 유효성 검사가 잘 구현되어 있습니다.

이메일과 인증 코드에 대한 유효성 검사가 적절하게 구현되어 있으며, 에러 메시지도 명확합니다. 6자리 숫자 코드에 대한 정규식 패턴도 정확합니다.

src/main/java/com/mycom/socket/auth/security/CookieUtil.java (1)

16-23: 쿠키 설정이 적절하게 구현되었습니다.

보안 관련 설정(httpOnly, secure)이 잘 적용되어 있으며, JWTProperties를 통한 설정 관리가 체계적으로 되어 있습니다.

src/main/java/com/mycom/socket/auth/config/SecurityConfig.java (1)

35-38: JWT 필터 설정이 적절합니다.

JWTProperties를 통한 설정 주입이 잘 되어있으며, 필터 체인에 올바르게 통합되었습니다.

src/test/java/com/mycom/socket/member/service/LoginIntegrationTest.java (2)

53-58: 테스트 케이스가 잘 구현되었습니다.

LoginRequest와 LoginResponse를 사용한 테스트 구조가 명확하며, 실제 서비스 로직을 잘 검증하고 있습니다.


66-68: 설정값 검증이 적절합니다.

JWTProperties의 설정값들을 이용한 쿠키 속성 검증이 체계적으로 구현되었습니다.

src/main/java/com/mycom/socket/auth/jwt/JWTFilter.java (2)

Line range hint 28-41: 예외 처리와 로깅이 개선되었습니다.

인증 실패 시의 예외 처리와 로깅이 적절하게 구현되었으며, SecurityContext 정리가 올바르게 수행됩니다.


56-68: 인증 로직 분리가 잘 되었습니다.

setAuthentication 메소드로 인증 로직을 분리한 것이 코드 가독성과 유지보수성을 향상시켰습니다.

src/main/java/com/mycom/socket/auth/security/LoginFilter.java (1)

56-58: 쿠키 생성 로직이 잘 개선되었습니다!

쿠키 생성 로직을 CookieUtil로 분리한 것은 좋은 리팩토링입니다. 이를 통해:

  • 쿠키 설정의 일관성 유지
  • 보안 관련 설정의 중앙화
  • 코드 재사용성 향상
src/test/java/com/mycom/socket/member/service/RegisterServiceTest.java (1)

80-115: 에러 케이스에 대한 테스트가 잘 작성되었습니다!

이메일 미인증과 중복 이메일에 대한 테스트 케이스가 명확하게 작성되었습니다. 예외 메시지도 구체적이고 이해하기 쉽게 작성되었습니다.

src/test/java/com/mycom/socket/member/service/LoginTest.java (1)

Line range hint 89-126: 로그인 실패 테스트가 잘 작성되었습니다!

실패 케이스에 대한 테스트가 꼼꼼하게 작성되었습니다:

  • 이메일 없음 케이스 검증
  • 잘못된 비밀번호 케이스 검증
  • 실패 시 쿠키가 설정되지 않는지 확인

Comment on lines +42 to +43
public EmailVerificationResponse sendVerificationEmail(@Valid @RequestBody EmailRequest request) {
return mailService.sendMail(request.email());
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

예외 처리를 추가하여 안정성을 향상시키십시오.

sendVerificationEmail 메서드에서 이메일 전송 중 발생할 수 있는 예외에 대한 처리가 없습니다. 이메일 전송 실패 시 사용자에게 적절한 피드백을 제공할 수 있도록 예외 처리를 추가하는 것이 좋습니다.

Comment on lines +47 to +48
public EmailVerificationResponse verifyEmail(@Valid @RequestBody EmailVerificationRequest request) {
return mailService.verifyCode(request.email(), request.code());
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

예외 처리를 추가하여 안정성을 향상시키십시오.

verifyEmail 메서드에서 이메일 검증 중 발생할 수 있는 예외에 대한 처리가 없습니다. 인증 코드 검증 실패 시 사용자에게 적절한 피드백을 제공할 수 있도록 예외 처리를 추가하는 것이 좋습니다.

return true;
} catch (Exception e) {
log.warn("JWT 토큰 검증 중 에러 발생: {}", e.getMessage());
log.warn("JWT 토큰 검증 실패", e);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

예외 메시지에 민감한 정보가 포함되지 않도록 로그를 개선하십시오.

validateToken 메서드에서 예외 발생 시 전체 예외를 로그에 기록하고 있습니다. 예외 메시지에 민감한 정보가 포함될 수 있으므로, 로그에 예외 메시지를 포함하지 않거나 최소한의 정보만 기록하는 것이 좋습니다.

Comment on lines +79 to +84
try {
javaMailSender.send(message);
return true;
}catch (Exception e) {
throw new BaseException("이메일 발송 중 오류가 발생했습니다: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
return EmailVerificationResponse.of("이메일 전송 성공");
} catch (Exception e) {
throw new BaseException("이메일 발송 중 오류가 발생했습니다: " + e.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

예외 처리를 구체적인 예외로 제한하는 것을 제안합니다.

현재 sendMail 메서드에서 모든 예외를 포괄하는 Exception을 캐치하고 있습니다. 이는 예외의 원인을 파악하기 어렵게 만들 수 있으므로, MailException이나 MessagingException과 같은 구체적인 예외를 캐치하여 정확한 예외 처리를 권장합니다.

@ConfigurationProperties(prefix = "jwt")
public class JWTProperties {
private String secret;
private long accessTokenValidityInSeconds = 1800;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

토큰 유효 기간에 대한 최소값 검증 필요

토큰 유효 기간이 너무 짧지 않도록 최소값 검증이 필요합니다.

-    private long accessTokenValidityInSeconds = 1800;
+    @Min(value = 300, message = "토큰 유효 기간은 최소 5분 이상이어야 합니다.")
+    private long accessTokenValidityInSeconds = 1800;
📝 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
private long accessTokenValidityInSeconds = 1800;
@Min(value = 300, message = "토큰 유효 기간은 최소 5분 이상이어야 합니다.")
private long accessTokenValidityInSeconds = 1800;

@Component
@ConfigurationProperties(prefix = "jwt")
public class JWTProperties {
private String secret;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

JWT secret 필드에 대한 유효성 검사 필요

JWT secret은 필수 값이므로 @NotEmpty 어노테이션을 추가하여 유효성 검사를 수행해야 합니다.

-    private String secret;
+    @NotEmpty(message = "JWT secret은 필수 값입니다.")
+    private String secret;
📝 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
private String secret;
@NotEmpty(message = "JWT secret은 필수 값입니다.")
private String secret;

private long accessTokenValidityInSeconds = 1800;
private String cookieName = "Authorization";
private String issuer = "go_socket";
private boolean secureCookie = false;
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

보안 쿠키 설정 문제 확인됨

현재 구성에서 다음과 같은 심각한 보안 문제가 확인되었습니다:

  • JWTProperties의 secureCookie 기본값이 false로 설정됨
  • 프로덕션 환경을 포함한 어떤 환경 설정 파일에서도 이 값을 재정의하지 않음
  • SecurityConfig에서도 쿠키 보안 설정을 별도로 구성하지 않음

프로덕션 환경의 보안을 위해 반드시 secureCookie를 true로 설정해야 합니다.

🔗 Analysis chain

보안 쿠키 설정 검토 필요

프로덕션 환경에서는 보안 쿠키를 활성화해야 합니다. 현재 기본값이 false로 설정되어 있어 보안상 위험할 수 있습니다.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if secureCookie is properly configured in different environments

# Check application properties files for secure cookie configuration
echo "Checking application properties files for secure cookie configuration..."
rg -l "jwt\.secure-cookie" 

Length of output: 183


Script:

#!/bin/bash
# Search for various possible property naming patterns
echo "Checking different property naming patterns..."
rg -l "jwt\.(secure-?cookie|cookie\.secure|secureCookie)"

echo -e "\nChecking for application properties/yml files..."
fd -e properties -e yml

echo -e "\nChecking for security configuration classes..."
fd -e java -x grep -l "SecurityConfig\|WebSecurityConfig"

Length of output: 730


Script:

#!/bin/bash
echo "Checking application.yml content..."
cat src/main/resources/application.yml

echo -e "\nChecking application-dev.yml content..."
cat src/main/resources/yaml/application-dev.yml

echo -e "\nChecking SecurityConfig.java for cookie configurations..."
cat src/main/java/com/mycom/socket/auth/config/SecurityConfig.java

Length of output: 2900

Comment on lines +60 to +65
// 로그인 응답 생성
LoginResponse loginResponse = new LoginResponse(member.getEmail(), member.getNickname());

response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
objectMapper.writeValue(response.getWriter(), ApiResponse.success("로그인 성공", loginResponse));
objectMapper.writeValue(response.getWriter(), loginResponse);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

응답 처리에 예외 처리를 추가해주세요.

objectMapper.writeValue() 호출 시 발생할 수 있는 IOException에 대한 예외 처리가 필요합니다.

다음과 같이 수정을 제안합니다:

 // 로그인 응답 생성
 LoginResponse loginResponse = new LoginResponse(member.getEmail(), member.getNickname());

 response.setContentType(MediaType.APPLICATION_JSON_VALUE);
 response.setCharacterEncoding("UTF-8");
-objectMapper.writeValue(response.getWriter(), loginResponse);
+try {
+    objectMapper.writeValue(response.getWriter(), loginResponse);
+} catch (IOException e) {
+    throw new RuntimeException("로그인 응답 생성 중 오류가 발생했습니다.", e);
+}
📝 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
// 로그인 응답 생성
LoginResponse loginResponse = new LoginResponse(member.getEmail(), member.getNickname());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
objectMapper.writeValue(response.getWriter(), ApiResponse.success("로그인 성공", loginResponse));
objectMapper.writeValue(response.getWriter(), loginResponse);
// 로그인 응답 생성
LoginResponse loginResponse = new LoginResponse(member.getEmail(), member.getNickname());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
try {
objectMapper.writeValue(response.getWriter(), loginResponse);
} catch (IOException e) {
throw new RuntimeException("로그인 응답 생성 중 오류가 발생했습니다.", e);
}

@ohyuchan123 ohyuchan123 merged commit 16bf7a5 into develop Jan 8, 2025
2 checks passed
@ohyuchan123 ohyuchan123 changed the title File Directory Refactor 🔀 File Directory Refactor Jan 8, 2025
@ohyuchan123 ohyuchan123 added 🐞 BugFix Something isn't working and removed ✅ Test test 관련(storybook, jest...) labels Jan 8, 2025
This was referenced Jan 14, 2025
@ohyuchan123 ohyuchan123 deleted the refactor/file-directory branch January 15, 2025 09:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 BugFix Something isn't working ✨ Feature 기능 개발 🔨 Refactor 코드 리팩토링

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant