Skip to content

Conversation

@Jihyun3478
Copy link
Contributor

@Jihyun3478 Jihyun3478 commented May 4, 2025

🔥 변경 사항

  • authMiddleware에서 UUID 기반 사용자 정보 전달
  • service 내에서 UUID로 유저 조회 후, bigint id로 토큰 생성되도록 변경

🏷 관련 이슈

  • 관련 이슈: #123

📸 스크린샷 (UI 변경 시 필수)

(변경 사항이 UI와 관련된 경우 스크린샷을 첨부해주세요.)

📌 체크리스트

  • 기능이 정상적으로 동작하는지 테스트 완료
  • 코드 스타일 가이드 준수 여부 확인
  • 관련 문서 업데이트 완료 (필요 시)

Summary by CodeRabbit

  • 버그 수정

    • QR 토큰 생성 시 사용자 식별에 velogUUID를 사용하도록 개선하여 사용자 조회 및 예외 처리가 보다 정확하게 동작합니다.
    • 사용자 토큰 생성 및 조회 과정에서 velogUUID를 명시적으로 사용하도록 변경하여 일관성을 높였습니다.
  • 테스트

    • QR 토큰 생성 서비스 테스트가 velogUUID 기반으로 변경되었으며, 사용자 미존재 및 토큰 생성 실패 상황에 대한 테스트가 추가되었습니다.
  • 공개 메서드 변경

    • QR 토큰 생성 메서드의 입력값이 userId에서 velogUUID로 변경되었습니다.
@Jihyun3478 Jihyun3478 added the bug Something isn't working label May 4, 2025
@Jihyun3478 Jihyun3478 self-assigned this May 4, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 4, 2025

"""

Walkthrough

이번 변경에서는 QR 로그인 토큰 생성 및 조회 과정에서 사용자 식별자를 기존의 숫자형 user ID에서 velog_uuid 문자열로 일원화하여 처리하도록 수정했습니다. UserService의 create 메서드 시그니처가 velogUUID를 받도록 변경되었고, 내부적으로 velogUUID로 사용자를 조회해 존재하지 않을 경우 예외를 발생시킵니다. UserController와 관련 테스트 코드도 이에 맞게 인자 전달 및 검증 로직이 velogUUID 기반으로 일치하도록 업데이트되었습니다.

Changes

파일/경로 변경 요약
src/services/user.service.ts create 메서드가 userId 대신 velogUUID를 받아 사용자 조회 후 토큰 생성 및 예외 처리 추가, 시그니처 변경
src/controllers/user.controller.ts QR 토큰 생성 및 조회 시 user.id → user.velog_uuid, found.user.toString() → String(found.user)로 변경
src/services/test/qr.service.test.ts 테스트 전반에서 velogUUID 사용, 사용자 조회 실패/저장 실패 케이스 추가, mock 객체 및 상수 일원화

Sequence Diagram(s)

sequenceDiagram participant Client participant UserController participant UserService participant UserRepository participant QRTokenRepository Client->>UserController: createToken(velogUUID, ip, userAgent) UserController->>UserService: create(velogUUID, ip, userAgent) UserService->>UserRepository: findByVelogUUID(velogUUID) alt 사용자 존재 UserService->>QRTokenRepository: createQRLoginToken(token, user.id, ip, userAgent) UserService-->>UserController: token UserController-->>Client: token else 사용자 없음 UserService-->>UserController: NotFoundError UserController-->>Client: 에러 반환 end 
Loading

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • six-standard

Poem

QR코드 속 숨은 토끼의 춤,
UUID로 신분증 바꿔 입었네.
숫자 대신 문자열로 깔끔하게,
테스트도 꼼꼼히 토끼처럼 튼튼하게!
오늘도 깡총깡총 코드밭을 달리며,
로그인 토큰은 더욱 안전해졌어요.
🐇✨
"""


📜 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 eac8e63 and cb934ed.

📒 Files selected for processing (1)
  • src/services/__test__/qr.service.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/services/test/qr.service.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-and-test (23)
  • GitHub Check: build-and-test (20)
  • GitHub Check: build-and-test (22)
✨ Finishing Touches
  • 📝 Generate Docstrings

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

Support

Need help? Create a ticket on our support page 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 docstrings to generate docstrings for this 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.
Copy link
Contributor

@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: 0

🧹 Nitpick comments (3)
src/services/user.service.ts (1)

139-147: UUID 기반 사용자 조회 및 토큰 생성 로직 개선!

사용자 ID 대신 velogUUID를 사용하여 사용자를 조회하고 토큰을 생성하는 방식으로 변경한 것이 좋습니다. 또한 사용자가 존재하지 않을 경우 적절한 에러 메시지를 반환하는 예외 처리도 추가되었습니다.

이렇게 함으로써:

  1. 사용자 식별 방식을 통일하여 일관성 유지
  2. 사용자 존재 여부를 명시적으로 검증
  3. 더 명확한 오류 메시지 제공

다만, 문서화 주석(JSDoc)을 추가하여 메서드의 인자와 반환값, 발생 가능한 예외에 대한 설명을 제공하면 더 좋을 것 같습니다.

+/** + * velogUUID로 사용자를 조회하고 QR 로그인 토큰을 생성합니다. + * @param velogUUID 사용자의 Velog UUID + * @param ip 요청 IP 주소 + * @param userAgent 사용자 에이전트 정보 + * @returns 생성된 QR 로그인 토큰 + * @throws {NotFoundError} 사용자를 찾을 수 없는 경우 + */ async create(velogUUID: string, ip: string, userAgent: string): Promise<string> { const user = await this.userRepo.findByUserVelogUUID(velogUUID); if (!user) { throw new NotFoundError('QR 토큰 생성 실패: 유저 없음'); } const token = generateRandomToken(10); await this.userRepo.createQRLoginToken(token, user.id, ip, userAgent); return token; }
src/services/__test__/qr.service.test.ts (2)

73-73: 일관된 테스트 파라미터 사용!

테스트에서 하드코딩된 값 대신 상수 변수(velogUUID, ip, userAgent)를 사용하면 테스트 일관성이 더 높아질 것입니다.

-await expect(service.create('uuid-1234', 'ip', 'agent')).rejects.toThrow('생성 실패'); +await expect(service.create(velogUUID, ip, userAgent)).rejects.toThrow('생성 실패');

64-64: any 타입 사용 개선!

null as any와 같은 타입 단언은 TypeScript의 타입 안전성을 우회합니다. 더 타입 안전한 접근 방식을 사용하는 것이 좋습니다.

-repo.findByUserVelogUUID.mockResolvedValueOnce(null as any); +repo.findByUserVelogUUID.mockResolvedValueOnce(null);

또는 만약 명시적 타입이 필요하다면:

-repo.findByUserVelogUUID.mockResolvedValueOnce(null as any); +repo.findByUserVelogUUID.mockResolvedValueOnce(null as unknown as typeof mockUser);
🧰 Tools
🪛 ESLint

[error] 64-64: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 408bfcf and eac8e63.

📒 Files selected for processing (3)
  • src/controllers/user.controller.ts (2 hunks)
  • src/services/__test__/qr.service.test.ts (1 hunks)
  • src/services/user.service.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/services/user.service.ts (2)
src/exception/index.ts (1)
  • NotFoundError (6-6)
src/utils/generateRandomToken.util.ts (1)
  • generateRandomToken (6-15)
🪛 ESLint
src/services/__test__/qr.service.test.ts

[error] 64-64: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build-and-test (23)
  • GitHub Check: build-and-test (22)
  • GitHub Check: build-and-test (21)
  • GitHub Check: build-and-test (20)
🔇 Additional comments (5)
src/controllers/user.controller.ts (2)

121-121: 변경이 적절합니다!

UUID를 사용하여 사용자를 식별하는 방식으로 변경한 것이 좋습니다. QR 토큰 생성 시 user.id 대신 user.velog_uuid를 사용하여 UUID 기반 사용자 식별 방식으로 일관성을 유지하고 있습니다.


150-150: String 변환 방식의 개선!

found.user.toString()에서 String(found.user)로 변경한 것은 좋은 접근입니다. String() 생성자를 사용하면 null이나 undefined 값도 안전하게 문자열로 변환할 수 있어 더 안정적입니다.

src/services/__test__/qr.service.test.ts (3)

35-61: 테스트 코드 재구성 및 개선!

테스트 코드를 재구성하여 상수와 모의 사용자 객체를 분리한 것은 가독성과 유지보수성을 높이는 좋은 방법입니다. velogUUID를 사용하여 사용자를 조회하는 새로운 로직에 맞게 테스트를 적절히 수정하였습니다.


63-67: 사용자 조회 실패 케이스 테스트 추가!

사용자가 존재하지 않을 경우의 예외 처리를 테스트하는 케이스를 추가한 것은 매우 좋습니다. 이는 에러 처리 로직의 정확성을 보장합니다.

🧰 Tools
🪛 ESLint

[error] 64-64: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)


70-70: Mock 사용자 반환 방식 개선!

테스트에서 findByUserVelogUUID의 모의 구현이 적절하게 수정되었습니다.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (2)
src/services/__test__/qr.service.test.ts (2)

70-73: DB 오류 전파 테스트가 수정되었습니다.

사용자 조회 모킹이 추가되어 테스트 시나리오가 완성되었습니다. 다만, 73번 줄에서는 상수 변수 대신 하드코딩된 값을 사용하고 있습니다.

73번 줄에서 하드코딩된 값 대신 앞서 정의한 상수를 사용하는 것이 좋습니다:

-await expect(service.create('uuid-1234', 'ip', 'agent')).rejects.toThrow('생성 실패'); +await expect(service.create(velogUUID, ip, userAgent)).rejects.toThrow('생성 실패');

64-64: 타입 어노테이션 개선이 필요합니다.

ESLint에서 지적한 바와 같이, null as any 사용은 타입 안전성을 저하시킵니다.

명시적인 타입을 사용하여 개선할 수 있습니다:

-repo.findByUserVelogUUID.mockResolvedValueOnce(null as any); +repo.findByUserVelogUUID.mockResolvedValueOnce(null);

타입 캐스팅이 필요하다면 더 구체적인 타입을 사용하세요:

repo.findByUserVelogUUID.mockResolvedValueOnce(null as unknown as User);
🧰 Tools
🪛 ESLint

[error] 64-64: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 408bfcf and eac8e63.

📒 Files selected for processing (3)
  • src/controllers/user.controller.ts (2 hunks)
  • src/services/__test__/qr.service.test.ts (1 hunks)
  • src/services/user.service.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/services/user.service.ts (2)
src/exception/index.ts (1)
  • NotFoundError (6-6)
src/utils/generateRandomToken.util.ts (1)
  • generateRandomToken (6-15)
🪛 ESLint
src/services/__test__/qr.service.test.ts

[error] 64-64: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build-and-test (23)
  • GitHub Check: build-and-test (22)
  • GitHub Check: build-and-test (21)
  • GitHub Check: build-and-test (20)
🔇 Additional comments (6)
src/services/user.service.ts (1)

139-147: 코드 변경이 요구사항을 적절히 해결하고 있습니다.

velogUUID를 사용하여 사용자를 조회하고 QR 토큰을 생성하는 방식으로 변경된 것이 좋습니다. 유저가 존재하지 않을 경우 명확한 에러 메시지와 함께 예외를 발생시키는 것도 적절합니다.

src/controllers/user.controller.ts (2)

121-121: 사용자 식별자 타입 변경이 정확하게 적용되었습니다.

해당 변경으로 user.id 대신 user.velog_uuid를 사용하여 토큰을 생성하도록 수정된 것이 요구사항과 일치합니다. 이제 UUID 타입 오류 문제가 해결되었습니다.


150-150: 문자열 변환 방식이 개선되었습니다.

found.user.toString()에서 String(found.user)로 변경한 것은 더 안전한 접근 방식입니다. found.user가 숫자 타입이거나 객체가 아닌 경우에도 오류 없이 문자열로 변환됩니다.

src/services/__test__/qr.service.test.ts (3)

36-50: 테스트 설정이 명확하게 개선되었습니다.

상수와 모의 사용자 객체를 재사용 가능한 방식으로 추출한 것이 좋습니다. 테스트 코드의 가독성과 유지보수성이 향상되었습니다.


53-61: 테스트 로직이 비즈니스 요구사항과 일치하도록 잘 수정되었습니다.

velogUUID로 사용자를 조회하고 해당 사용자의 ID를 사용하여 QR 토큰을 생성하는 로직을 정확하게 테스트하고 있습니다. 모의 객체의 설정과 호출 검증이 적절합니다.


63-67: 오류 케이스에 대한 테스트가 적절히 추가되었습니다.

사용자가 UUID로 조회되지 않을 경우의 오류 처리를 테스트하는 것은 중요합니다. 예상되는 오류 메시지가 정확하게 검증되고 있습니다.

🧰 Tools
🪛 ESLint

[error] 64-64: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

Copy link
Contributor

@ooheunda ooheunda left a comment

Choose a reason for hiding this comment

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

지현님 쉬는 날에도 고생 많으십니다!!!

PR 올리신 거 테스트시 컨트롤러에서 user.velog_uuidundefined로 나오길래 좀 봤는데요, 인증 미들웨어에 login(), verify() 두 개가 있어서 혼동이 있었던 것 같네요..!
지금 QR 생성 API에서 login()을 쓰고 계신데, 얘는 fetch 보내서 벨로그의 유저 정보를 담고 있어 velog_uuid가 들어왔던 것 같아요! (참고)
verify()를 쓰시면 저희 DB의 유저 정보를 가져와서, 기존 코드로도 잘 돌아갈 것 같습니다!

PS. 미들웨어 코드 리팩토링이 필요할 것 같네요... 🤔 query로 분기 처리 되어서 헷갈릴 여지가 커 보여요.

@Jihyun3478
Copy link
Contributor Author

지현님 쉬는 날에도 고생 많으십니다!!!

PR 올리신 거 테스트시 컨트롤러에서 user.velog_uuidundefined로 나오길래 좀 봤는데요, 인증 미들웨어에 login(), verify() 두 개가 있어서 혼동이 있었던 것 같네요..! 지금 QR 생성 API에서 login()을 쓰고 계신데, 얘는 fetch 보내서 벨로그의 유저 정보를 담고 있어 velog_uuid가 들어왔던 것 같아요! (참고) verify()를 쓰시면 저희 DB의 유저 정보를 가져와서, 기존 코드로도 잘 돌아갈 것 같습니다!

PS. 미들웨어 코드 리팩토링이 필요할 것 같네요... 🤔 query로 분기 처리 되어서 헷갈릴 여지가 커 보여요.

금같은 피드백 너무 감사합니다,,🥹 다시 확인해보겠습니다~!!

@Nuung Nuung closed this May 4, 2025
@Jihyun3478 Jihyun3478 deleted the hotfix/qrlogintoken branch May 7, 2025 15:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

4 participants