Skip to content

fix(auth): 카카오 로그인 시 UUID 형식 검증 오류 수정 - #59

Merged
evenif99 merged 5 commits into
devfrom
fix/auth-uuid-error
Jun 18, 2026
Merged

fix(auth): 카카오 로그인 시 UUID 형식 검증 오류 수정#59
evenif99 merged 5 commits into
devfrom
fix/auth-uuid-error

Conversation

@evenif99

@evenif99 evenif99 commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • 카카오 OAuth 최초 로그인(회원가입) 시 signIn 콜백에서 카카오 숫자 ID를 UUID 컬럼으로 조회하여 Prisma 에러 발생하던 문제 수정
  • signIn 콜백에 UUID 형식 검증을 추가하여 PrismaAdapter가 User를 생성하기 전 단계에서는 DB 조회를 스킵
  • events.createUser 핸들러를 추가하여 신규 사용자의 커스텀 필드(kakaoId, nickname, termsAgreedAt)를 안전하게 설정

Test plan

  • 신규 사용자 카카오 로그인(회원가입) 시 에러 없이 정상 가입 확인
  • 기존 사용자 카카오 로그인 시 정상 로그인 확인
  • 신규 사용자 가입 후 nickname, kakaoId 필드 정상 저장 확인

🤖 Generated with Claude Code

Summary by CodeRabbit

릴리스 노트

  • 버그 수정

    • Kakao 로그인 시 사용자 식별 검증 로직이 강화되어, 기존 사용자 조회 및 최초 로그인 처리의 안정성이 개선되었습니다.
  • 새로운 기능

    • 사용자 생성 및 최초 로그인 시 추가 정보(커스텀 필드)가 조건에 따라 자동으로 설정됩니다.
    • 계정 연동 시 저장되는 정보 범위가 제한되어 필요한 데이터만 처리됩니다.
  • UI/스타일

    • 카카오 버튼 색상/호버 스타일이 업데이트되었습니다.
    • 로그인 화면 푸터의 소셜 로그인 안내 문구 및 약관/개인정보 링크 텍스트가 변경되었습니다.

카카오 OAuth 최초 로그인 시 PrismaAdapter가 User를 생성하기 전에
signIn 콜백이 실행되면서 카카오 숫자 ID(길이 10)로 UUID 컬럼을
조회하여 Prisma 에러가 발생하던 문제 수정.

- signIn 콜백에 UUID 형식 검증 추가하여 비-UUID ID는 스킵
- events.createUser에서 신규 사용자 커스텀 필드 설정 처리

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@vercel

vercel Bot commented Jun 18, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
talky-owl Ready Ready Preview, Comment Jun 18, 2026 8:00am

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 939ea9b3-2d24-4d53-8519-697e897df2a2

📥 Commits

Reviewing files that changed from the base of the PR and between b32c1a0 and 9143e00.

📒 Files selected for processing (1)
  • src/app/(page)/login/page.tsx

📝 Walkthrough

Walkthrough

src/lib/auth/index.tsUUID_REGEX 상수와 ACCOUNT_FIELDS 화이트리스트가 추가되고, PrismaAdapter를 래핑하는 createAdapter() 함수가 도입되어 계정 필드를 필터링하도록 변경되었습니다. signIn 콜백에서 Kakao 사용자 조회 시 UUID 검증 조건이 강화되었으며, authOptions.events.createUser 핸들러가 신규 추가되어 사용자 생성 직후 Kakao 계정 정보를 조회하고 커스텀 필드를 설정하는 흐름이 확장되었습니다. 로그인 페이지에서 Kakao 버튼 색상을 조정하고 소셜 로그인 가입 안내 문구를 업데이트했습니다.

Changes

Kakao 인증 및 최초 로그인 필드 설정 강화

Layer / File(s) Summary
어댑터 래핑 및 계정 필드 화이트리스팅
src/lib/auth/index.ts
UUID_REGEX 상수와 ACCOUNT_FIELDS 화이트리스트를 추가하고, PrismaAdapterlinkAccount를 래핑하는 createAdapter() 함수를 도입하여 계정 객체를 필터링한 뒤 base linkAccount로 전달하도록 변경함. authOptions.adaptercreateAdapter()로 설정함.
signIn 콜백 UUID 검증 강화
src/lib/auth/index.ts
Kakao 로그인 시 user.idUUID_REGEX 패턴과 일치하는 경우에만 prisma.user.findUnique를 수행하도록 분기 조건을 변경함. UUID 검증 실패 시 기존 사용자 조회를 스킵함.
events.createUser 핸들러 신규 추가
src/lib/auth/index.ts
authOptionsevents.createUser 핸들러를 추가하여, 사용자 생성 직후 Kakao 프로바이더의 providerAccountId를 조회하고 존재 시 saveFirstLoginFields를 호출해 kakaoId, nickname, termsAgreedAt 등의 커스텀 필드를 설정함.

로그인 페이지 UI 개선

Layer / File(s) Summary
Kakao 버튼 색상 업데이트
src/app/(page)/login/login.module.scss
.kakaoButton의 기본 배경색을 #fee500에서 #ffe812로, :hover:not(:disabled) 상태의 배경색을 #f5dc00에서 #f5df00으로 갱신함.
소셜 로그인 안내 문구 개선
src/app/(page)/login/page.tsx
로그인 페이지 푸터의 소셜 로그인 가입 안내 문구를 "소셜 로그인 가입 시 본 ... 동의하시는 것으로 간주됩니다" 형태로 재작성하고, 약관 및 개인정보 링크 텍스트를 "서비스이용약관"과 "개인정보처리방침"으로 업데이트함.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • I5-Project/TALKY-OWL#50: src/lib/auth/index.tscallbacks.signIn 내 Kakao 최초 로그인 필드 초기화 로직을 동일하게 수정하며, 이번 PR은 해당 흐름에 UUID 조건 강화와 events.createUser 핸들러를 추가한 후속 변경임.

Poem

🐰 토끼가 UUID를 들고 뛰어왔네,
카카오 숲속에서 진짜 사용자만 맞이하려고~
어댑터를 살며시 감싸고 필터링하면,
createUser 문 앞에서 꼼꼼히 살펴봐요!
버튼 색깔 예쁘게 칠하고,
약관 문구도 깔끔하게 정돈하는 토끼의 마법 🎩✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning PR 설명이 요약, 테스트 계획을 포함하고 있으나 필수 템플릿의 대부분 섹션(작업 내용, 담당 영역, 관련 Issue 등)이 누락되어 있습니다. 제공된 템플릿의 1~12번 섹션을 모두 작성하여 작업 범위, 담당 영역, 관련 이슈, 테스트 결과, 보안 검토 등을 명확히 기록해주세요.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed PR 제목이 주요 변경사항인 카카오 로그인 시 UUID 형식 검증 오류 수정을 명확하게 요약하고 있습니다.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/auth-uuid-error

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/lib/auth/index.ts (1)

75-87: ⚡ Quick win

오류 발생 시 디버깅을 위한 로깅 추가를 고려해 주세요.

createUser 이벤트 핸들러 내 saveFirstLoginFields 호출 시 예기치 않은 오류가 발생하면, NextAuth 이벤트 특성상 오류가 조용히 무시될 수 있습니다. 이 경우 사용자는 생성되지만 커스텀 필드(kakaoId, nickname, termsAgreedAt)가 설정되지 않은 상태로 남을 수 있습니다.

프로덕션 환경에서 문제 추적을 위해 try-catch와 로깅을 추가하는 것이 좋습니다.

💡 오류 로깅 추가 제안
   events: {
     async createUser({ user }) {
       // PrismaAdapter가 User를 생성한 직후 호출됨 — 신규 사용자 커스텀 필드 설정
       const account = await prisma.account.findFirst({
         where: { userId: user.id, provider: 'kakao' },
         select: { providerAccountId: true },
       })
 
       if (account) {
-        await saveFirstLoginFields(user.id, account.providerAccountId)
+        try {
+          await saveFirstLoginFields(user.id, account.providerAccountId)
+        } catch (error) {
+          console.error('[createUser] Failed to save first login fields:', {
+            userId: user.id,
+            error,
+          })
+        }
       }
     },
   },
🤖 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 `@src/lib/auth/index.ts` around lines 75 - 87, The createUser event handler in
the events object lacks error handling, which means if the account lookup or
saveFirstLoginFields call fails, the error will be silently ignored and custom
fields may not be set for the user. Wrap the entire logic inside the createUser
async function (the prisma.account.findFirst call and the saveFirstLoginFields
invocation) in a try-catch block, and add error logging in the catch block that
includes the actual error details so failures can be tracked and debugged in
production environments.
🤖 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.

Nitpick comments:
In `@src/lib/auth/index.ts`:
- Around line 75-87: The createUser event handler in the events object lacks
error handling, which means if the account lookup or saveFirstLoginFields call
fails, the error will be silently ignored and custom fields may not be set for
the user. Wrap the entire logic inside the createUser async function (the
prisma.account.findFirst call and the saveFirstLoginFields invocation) in a
try-catch block, and add error logging in the catch block that includes the
actual error details so failures can be tracked and debugged in production
environments.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 0af40e5f-02c6-4293-9de2-dd19bd0646e6

📥 Commits

Reviewing files that changed from the base of the PR and between 560d9b7 and 50134dc.

📒 Files selected for processing (1)
  • src/lib/auth/index.ts

evenif99 and others added 2 commits June 18, 2026 16:18
카카오 OAuth 토큰 응답에 포함된 refresh_token_expires_in 필드가
Account 스키마에 없어서 linkAccount 단계에서 Prisma 에러 발생.
PrismaAdapter를 래핑하여 Account 스키마에 정의된 필드만 저장하도록 필터링.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/lib/auth/index.ts (1)

10-14: 💤 Low value

ACCOUNT_FIELDS 화이트리스트 유지보수 관련 참고 사항

이 접근 방식은 Kakao의 refresh_token_expires_in 문제를 해결하지만, 향후 NextAuth 버전에서 새로운 Account 필드가 추가되면 자동으로 필터링되어 누락될 수 있습니다. 화이트리스트 방식의 의도된 동작이므로, 향후 NextAuth 업그레이드 시 이 목록도 함께 검토해야 합니다.

또한 'id' 필드는 일반적으로 어댑터에서 자동 생성되므로 OAuth 응답에 포함되지 않습니다. 제거해도 무방합니다.

🤖 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 `@src/lib/auth/index.ts` around lines 10 - 14, The ACCOUNT_FIELDS Set in the
authentication configuration includes the 'id' field which is typically
auto-generated by the adapter and will not be present in OAuth responses, making
it unnecessary to include in the whitelist. Remove the 'id' field from the
ACCOUNT_FIELDS Set. Additionally, add a comment above the ACCOUNT_FIELDS
constant explaining that this whitelist is intentionally filtered to handle
provider-specific fields like Kakao's refresh_token_expires_in, and that it
should be reviewed during NextAuth version upgrades to ensure new Account fields
are not inadvertently filtered out.
🤖 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.

Nitpick comments:
In `@src/lib/auth/index.ts`:
- Around line 10-14: The ACCOUNT_FIELDS Set in the authentication configuration
includes the 'id' field which is typically auto-generated by the adapter and
will not be present in OAuth responses, making it unnecessary to include in the
whitelist. Remove the 'id' field from the ACCOUNT_FIELDS Set. Additionally, add
a comment above the ACCOUNT_FIELDS constant explaining that this whitelist is
intentionally filtered to handle provider-specific fields like Kakao's
refresh_token_expires_in, and that it should be reviewed during NextAuth version
upgrades to ensure new Account fields are not inadvertently filtered out.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 7acd3e93-9631-4cc9-88c3-9421098461a1

📥 Commits

Reviewing files that changed from the base of the PR and between 50134dc and e66003f.

📒 Files selected for processing (1)
  • src/lib/auth/index.ts

- 카카오 버튼 아이콘을 말풍선에서 TALK 아이콘으로 변경
- 버튼 배경색 #FFE812로 수정
- 약관 동의 문구를 서비스 가이드에 맞게 수정

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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.

1 participant