Skip to content

🔀 Profile Search#37

Merged
ohyuchan123 merged 6 commits intodevelopfrom
feature/profile-search
Jan 15, 2025
Merged

🔀 Profile Search#37
ohyuchan123 merged 6 commits intodevelopfrom
feature/profile-search

Conversation

@ohyuchan123
Copy link
Member

@ohyuchan123 ohyuchan123 commented Jan 15, 2025

📌 관련 이슈

#31 사용자 프로필 조회

✨ 과제 내용

사용자는 자신의 프로필을 조회할 수 있습니다.

📸 스크린샷(선택)

image

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

Summary by CodeRabbit

  • 새로운 기능

    • 프로필 정보 조회 API 추가
    • JWT 토큰 인증 방식 변경 (쿠키에서 헤더 기반 인증으로 전환)
  • 버그 수정

    • 데이터베이스 스키마 관리 방식 개선 (스키마 재생성 대신 업데이트)
  • 기타 변경사항

    • 인증 및 프로필 관련 서비스 및 컨트롤러 구조 개선

@coderabbitai
Copy link

coderabbitai bot commented Jan 15, 2025

Warning

Rate limit exceeded

@ohyuchan123 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 18 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a3bffe3 and 99593bc.

📒 Files selected for processing (2)
  • src/main/java/com/mycom/socket/auth/config/SecurityConfig.java (1 hunks)
  • src/main/java/com/mycom/socket/auth/jwt/JWTFilter.java (3 hunks)

Walkthrough

이 풀 리퀘스트는 프로필 관리 및 인증 메커니즘에 대한 중요한 변경 사항을 포함하고 있습니다. JWT 토큰 인증 방식이 쿠키 기반에서 헤더 기반으로 변경되었으며, 새로운 ProfileControllerProfileResponse가 추가되었습니다. 또한 MemberService가 도입되어 사용자 관련 서비스 로직을 처리하고, 개발 환경의 데이터베이스 스키마 관리 설정이 업데이트되었습니다.

Changes

파일 변경 요약
src/main/java/com/mycom/socket/auth/jwt/JWTFilter.java - resolveTokenFromCookie 메서드 제거
- resolveTokenFromHeader 메서드 추가
- 토큰 해결 로직을 쿠키에서 헤더로 변경
src/main/java/com/mycom/socket/go_socket/controller/ProfileController.java - 새로운 프로필 컨트롤러 추가
- /api/profile GET 엔드포인트 구현
src/main/java/com/mycom/socket/go_socket/dto/response/ProfileResponse.java - 프로필 응답 레코드 생성
- of 정적 팩토리 메서드 추가
src/main/java/com/mycom/socket/go_socket/service/MemberService.java - 새로운 멤버 서비스 클래스 추가
- MemberRepository 주입
src/main/resources/yaml/application-dev.yml - Hibernate ddl-auto 설정을 create에서 update로 변경

Sequence Diagram

sequenceDiagram
    participant Client
    participant JWTFilter
    participant AuthenticationManager
    participant ProfileController
    participant MemberService

    Client->>JWTFilter: HTTP Request with Bearer Token
    JWTFilter->>JWTFilter: Resolve Token from Header
    JWTFilter->>AuthenticationManager: Authenticate Token
    AuthenticationManager-->>JWTFilter: Authentication Success
    Client->>ProfileController: GET /api/profile
    ProfileController->>MemberService: Retrieve Member Details
    MemberService-->>ProfileController: Return Member Information
    ProfileController-->>Client: Return ProfileResponse
Loading

Possibly related PRs

Suggested labels

✅ Test, ✨ Feature, 🔨 Refactor

Poem

🐰 토큰의 춤, 헤더에 실려
프로필 창을 활짝 열어
보안의 문을 살며시 두드리니
데이터는 반짝이며 흐르네
코드의 토끼, 춤추듯 노래해! 🎉


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 self-assigned this Jan 15, 2025
@ohyuchan123 ohyuchan123 added 🔨 Refactor 코드 리팩토링 ✨ Feature 기능 개발 labels Jan 15, 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: 5

🧹 Nitpick comments (1)
src/main/resources/yaml/application-dev.yml (1)

5-5: 파일 끝에 개행 문자를 추가해주세요.

YAML 파일 표준에 따라 파일 끝에 개행 문자가 필요합니다.

 spring:
   jpa:
     show-sql: true
     hibernate:
-      ddl-auto: update
+      ddl-auto: update
+
🧰 Tools
🪛 yamllint (1.35.1)

[error] 5-5: no new line character at the end of file

(new-line-at-end-of-file)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e009402 and a3bffe3.

📒 Files selected for processing (5)
  • src/main/java/com/mycom/socket/auth/jwt/JWTFilter.java (2 hunks)
  • src/main/java/com/mycom/socket/go_socket/controller/ProfileController.java (1 hunks)
  • src/main/java/com/mycom/socket/go_socket/dto/response/ProfileResponse.java (1 hunks)
  • src/main/java/com/mycom/socket/go_socket/service/MemberService.java (1 hunks)
  • src/main/resources/yaml/application-dev.yml (1 hunks)
🧰 Additional context used
🪛 yamllint (1.35.1)
src/main/resources/yaml/application-dev.yml

[error] 5-5: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (1)
src/main/resources/yaml/application-dev.yml (1)

5-5: 데이터베이스 스키마 관리 전략 변경에 대한 검토가 필요합니다.

ddl-auto: update 설정은 기존 데이터를 보존하면서 스키마를 업데이트하므로 개발 과정에서 데이터 지속성을 개선합니다. 하지만 다음 사항을 고려해주세요:

  1. 스키마 변경 이력 관리를 위해 Flyway나 Liquibase 같은 마이그레이션 도구 도입을 검토해보세요.
  2. 프로덕션 환경에서는 validate 모드 사용을 권장드립니다.

다음 스크립트로 현재 프로젝트의 프로필별 설정을 확인해보세요:

✅ Verification successful

데이터베이스 구성이 적절하게 설정되어 있습니다.

기본 프로파일에서 ddl-auto: none을 사용하고 개발 프로파일에서만 update 모드를 활성화하는 현재 설정은 안전하고 적절합니다. 다만, 제안 드린 대로 향후 데이터베이스 마이그레이션 도구 도입을 고려해보시면 좋겠습니다.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check database configuration across different profiles

echo "Checking database configuration across profiles..."
fd -e yml -e yaml . src/main/resources | xargs grep -l "ddl-auto"

Length of output: 255


Script:

#!/bin/bash
# Check the database configuration in both files
echo "=== Default Profile (application.yml) ==="
rg -A 5 -B 5 "ddl-auto" src/main/resources/application.yml

echo -e "\n=== Dev Profile (application-dev.yml) ==="
rg -A 5 -B 5 "ddl-auto" src/main/resources/yaml/application-dev.yml

Length of output: 518

🧰 Tools
🪛 yamllint (1.35.1)

[error] 5-5: no new line character at the end of file

(new-line-at-end-of-file)

Comment on lines +11 to +14
public class MemberService {

private final MemberRepository memberRepository;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

서비스 클래스에 필요한 메서드 구현이 누락되었습니다.

현재 MemberService 클래스가 비어있습니다. 프로필 조회 기능을 위해 다음과 같은 메서드들의 구현이 필요합니다:

  • 회원 프로필 조회
  • 회원 존재 여부 확인
  • 예외 처리 로직

다음과 같은 메서드 구현을 제안드립니다:

 @Service
 @RequiredArgsConstructor
 @Transactional(readOnly = true)
 public class MemberService {
     private final MemberRepository memberRepository;
+    
+    public Member getMemberByEmail(String email) {
+        return memberRepository.findByEmail(email)
+            .orElseThrow(() -> new EntityNotFoundException("회원을 찾을 수 없습니다."));
+    }
+    
+    public boolean existsByEmail(String email) {
+        return memberRepository.existsByEmail(email);
+    }
 }

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

Comment on lines +10 to +16
public static ProfileResponse of(Member member) {
return new ProfileResponse(
member.getEmail(),
member.getNickname(),
member.getIntro()
);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

팩토리 메서드에 유효성 검사와 문서화가 필요합니다.

of 메서드에 다음 사항들이 누락되어 있습니다:

  • null 체크
  • JavaDoc 문서화
  • 민감한 정보 노출 가능성 검토

다음과 같이 개선을 제안드립니다:

+    /**
+     * Member 엔티티로부터 ProfileResponse를 생성합니다.
+     *
+     * @param member 프로필 정보를 가져올 회원 엔티티 (null이 아니어야 함)
+     * @return 생성된 ProfileResponse 객체
+     * @throws IllegalArgumentException member가 null인 경우
+     */
     public static ProfileResponse of(Member member) {
+        if (member == null) {
+            throw new IllegalArgumentException("Member must not be null");
+        }
+        
         return new ProfileResponse(
                 member.getEmail(),
                 member.getNickname(),
                 member.getIntro()
         );
     }
📝 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
public static ProfileResponse of(Member member) {
return new ProfileResponse(
member.getEmail(),
member.getNickname(),
member.getIntro()
);
}
/**
* Member 엔티티로부터 ProfileResponse를 생성합니다.
*
* @param member 프로필 정보를 가져올 회원 엔티티 (null이 아니어야 )
* @return 생성된 ProfileResponse 객체
* @throws IllegalArgumentException member가 null인 경우
*/
public static ProfileResponse of(Member member) {
if (member == null) {
throw new IllegalArgumentException("Member must not be null");
}
return new ProfileResponse(
member.getEmail(),
member.getNickname(),
member.getIntro()
);
}

Comment on lines +16 to +19
@GetMapping
public ProfileResponse getProfile(@AuthenticationPrincipal MemberDetails memberDetails) {
return ProfileResponse.of(memberDetails.getMember());
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

컨트롤러에 예외 처리와 API 문서화가 필요합니다.

다음 사항들이 누락되어 있습니다:

  • 응답 상태 코드 명시
  • Swagger/OpenAPI 문서화
  • 예외 처리
  • 로깅

다음과 같이 개선을 제안드립니다:

+    private final Logger log = LoggerFactory.getLogger(ProfileController.class);
+
+    /**
+     * 현재 인증된 사용자의 프로필 정보를 조회합니다.
+     *
+     * @param memberDetails 인증된 사용자 정보
+     * @return 사용자 프로필 정보
+     */
     @GetMapping
+    @ResponseStatus(HttpStatus.OK)
+    @Operation(summary = "프로필 조회", description = "현재 로그인한 사용자의 프로필 정보를 조회합니다.")
+    @ApiResponse(responseCode = "200", description = "프로필 조회 성공")
+    @ApiResponse(responseCode = "401", description = "인증되지 않은 사용자")
     public ProfileResponse getProfile(@AuthenticationPrincipal MemberDetails memberDetails) {
+        log.debug("프로필 조회 요청: {}", memberDetails.getUsername());
+        if (memberDetails == null) {
+            throw new UnauthorizedException("인증 정보가 없습니다.");
+        }
         return ProfileResponse.of(memberDetails.getMember());
     }

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

Comment on lines 33 to 36
// Bearer 토큰 확인
String bearerToken = resolveTokenFromHeader(request);
if (StringUtils.hasText(bearerToken) && jwtUtil.validateToken(bearerToken, "ACCESS_TOKEN")) {
setAuthentication(bearerToken);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

JWT 토큰 처리 로직 보안 강화가 필요합니다.

현재 구현에서 다음과 같은 보안 관련 개선사항이 필요합니다:

  • Bearer 접두사 상수화
  • 토큰 형식 검증 강화
  • 구체적인 예외 처리

다음과 같이 개선을 제안드립니다:

+    private static final String BEARER_PREFIX = "Bearer ";
+    private static final String TOKEN_TYPE = "ACCESS_TOKEN";
+
     try {
-        // Bearer 토큰 확인
         String bearerToken = resolveTokenFromHeader(request);
-        if (StringUtils.hasText(bearerToken) && jwtUtil.validateToken(bearerToken, "ACCESS_TOKEN")) {
+        if (isValidBearerToken(bearerToken)) {
             setAuthentication(bearerToken);
         }
     } catch (Exception e) {
private boolean isValidBearerToken(String token) {
    return StringUtils.hasText(token) &&
           token.matches("^[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=]+\\.?[A-Za-z0-9-_.+/=]*$") &&
           jwtUtil.validateToken(token, TOKEN_TYPE);
}

Comment on lines 46 to 50
private String resolveTokenFromHeader(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

토큰 추출 메서드의 보안성 강화가 필요합니다.

토큰 추출 시 다음과 같은 보안 검증이 추가되어야 합니다:

  • 헤더 존재 여부 검증
  • 토큰 길이 제한
  • XSS 방지를 위한 문자열 이스케이프

다음과 같이 개선을 제안드립니다:

     private String resolveTokenFromHeader(HttpServletRequest request) {
         String bearerToken = request.getHeader("Authorization");
-        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
-            return bearerToken.substring(7);
+        if (!StringUtils.hasText(bearerToken)) {
+            return null;
+        }
+        if (!bearerToken.startsWith(BEARER_PREFIX)) {
+            log.warn("잘못된 토큰 형식: Bearer 접두사 없음");
+            return null;
+        }
+        String token = bearerToken.substring(BEARER_PREFIX.length());
+        if (token.length() > 1000) {  // 최대 토큰 길이 제한
+            log.warn("토큰 길이 초과");
+            return null;
         }
-        return null;
+        return HtmlUtils.htmlEscape(token);
     }

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

@ohyuchan123 ohyuchan123 merged commit 22fa66a into develop Jan 15, 2025
2 checks passed
@ohyuchan123 ohyuchan123 changed the title Profile Search 🔀 Profile Search Jan 15, 2025
@ohyuchan123 ohyuchan123 deleted the feature/profile-search branch January 15, 2025 09:26
@coderabbitai coderabbitai bot mentioned this pull request Jan 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✨ Feature 기능 개발 🔨 Refactor 코드 리팩토링

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant