Skip to content

feat: 카카오 로그인 구현 (회원가입 기능 완료 전)#97

Merged
hyeeuncho merged 1 commit intodevelopfrom
feat/#96/login
Apr 14, 2025
Merged

feat: 카카오 로그인 구현 (회원가입 기능 완료 전)#97
hyeeuncho merged 1 commit intodevelopfrom
feat/#96/login

Conversation

@hyeeuncho
Copy link
Copy Markdown
Member

@hyeeuncho hyeeuncho commented Apr 14, 2025

소셜 로그인 연동
-> 전화번호 추가로 받아서 넘기는 작업 전

Summary by CodeRabbit

  • New Features
    • 카카오와 구글 로그인을 통한 OAuth 인증 기능이 추가되어, 한층 간편한 로그인 경험을 제공합니다.
  • Style
    • 주요 페이지 내 UI 구성 요소 간격 및 레이아웃이 개선되어 깔끔한 화면 구성이 구현되었습니다.
  • Chores
    • 사용자 인증 및 세션 유지 관리 기능이 강화되어, 전반적인 로그인 경험이 한층 안정적으로 개선되었습니다.

@hyeeuncho hyeeuncho linked an issue Apr 14, 2025 that may be closed by this pull request
2 tasks
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 14, 2025

Walkthrough

이번 PR은 AuthStore에 토큰 관리를 위한 속성과 메서드를 추가하고, zustand의 persist 미들웨어를 적용하여 상태를 저장하도록 개선했습니다. 또한 MainPage와 LoginModal에서 UI 포맷팅 수정 및 OAuth 로그인 기능이 추가되었으며, MyTicketPage에서는 js-cookie를 사용해 쿠키에서 토큰을 불러와 AuthStore에 설정하는 로직이 도입되었습니다. http-client 설정도 수정되어 withCredentials 옵션이 추가되고, 인증 헤더 관련 코드는 주석 처리되었습니다.

Changes

Files Change Summary
src/app/…/authStore.ts, src/pages/menu/…/MyTicketPage.tsx AuthStore 인터페이스에 accessToken, refreshToken 및 관련 setter 추가, zustand persist 미들웨어 적용. MyTicketPage에서 쿠키에서 토큰을 읽어 AuthStore 업데이트.
src/pages/home/…/MainPage.tsx EventCard에 고유 id prop 추가 및 포맷팅(공백) 수정.
src/shared/…/http-client.ts axios 클라이언트에 withCredentials: true 추가, Authorization 헤더 및 토큰 관련 코드 주석 처리.
src/widgets/main/…/LoginModal.tsx Kakao, Google OAuth 로그인을 위한 kakaoLogingooleLogin 함수 추가, onClick 핸들러 업데이트.

Sequence Diagram(s)

sequenceDiagram
    participant U as 사용자
    participant LM as LoginModal
    participant B as 브라우저
    participant OP as OAuth 제공자
    U->>LM: Kakao/Google 버튼 클릭
    LM->>B: window.location.href 설정 (리다이렉트)
    B->>OP: OAuth 로그인 요청
Loading
sequenceDiagram
    participant MTP as MyTicketPage
    participant C as js-cookie
    participant AS as AuthStore
    MTP->>C: access-token, refresh-token 조회
    C-->>MTP: 토큰 반환 (존재 시)
    MTP->>AS: setAccessToken(token) 호출
    MTP->>AS: setRefreshToken(token) 호출
Loading

Possibly related PRs

Suggested labels

🔧 Feature

Suggested reviewers

  • xaexunxang
  • Yejiin21

Poem

나는 깡총깡총 작은 토끼,
AuthStore 속 비밀을 담았네.
쿠키 속 토큰 맛있게 챙기고,
OAuth 창문 넘어 뛰어가네.
오늘도 행복한 코드 정원에서 춤을 추네 🐰✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ 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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@hyeeuncho hyeeuncho requested a review from Yejiin21 April 14, 2025 15:00
Copy link
Copy Markdown
Contributor

@Yejiin21 Yejiin21 left a comment

Choose a reason for hiding this comment

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

확인했습니당

@github-actions
Copy link
Copy Markdown

Copy link
Copy Markdown

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

🧹 Nitpick comments (3)
src/pages/home/ui/MainPage.tsx (2)

54-54: 빈 함수 포맷팅이 수정되었습니다.

빈 함수를 사용하고 있는데, 실제로 기능이 필요 없다면 해당 prop을 제거하는 것이 좋습니다.

필요 없는 prop이라면 다음과 같이 수정할 것을 제안합니다:

-            onChange={() => { }}
+            // onChange prop 제거

-        leftButtonClick={() => { }}
+        // leftButtonClick prop 제거 또는 실제 기능 구현

Also applies to: 59-59


94-94: EventCard 컴포넌트에 id prop이 추가되었습니다.

배열의 인덱스를 id로 사용하는 것은 배열 순서가 바뀌거나 항목이 추가/삭제될 때 문제가 발생할 수 있습니다.

이벤트 데이터에 고유 식별자가 있다면 해당 값을 id로 사용하는 것이 좋습니다:

-                id={index}
+                id={event.id} // 이벤트 객체에 실제 고유 id가 있다면 그것을 사용

Also applies to: 131-131, 170-170

src/app/provider/authStore.ts (1)

15-27: 인증 스토어 구현 개선

Zustand persist를 활용한 인증 스토어 구현이 잘 되어 있습니다. 다만, 몇 가지 추가 개선 사항을 고려해 보세요:

  1. 로그아웃 기능 추가 - 토큰을 초기화하는 메서드가 있으면 좋을 것 같습니다.
  2. 토큰 만료 처리 - 토큰 만료 시간을 저장하고 확인하는 메서드 추가 고려
  3. 스토리지 옵션 설정 - 현재는 기본 localStorage를 사용하는데, 보안이 중요한 경우 sessionStorage 옵션을 고려해 볼 수 있습니다.
export const useAuthStore = create<AuthStore>()(
  persist(
    (set) => ({
      accessToken: null,
      refreshToken: null,
      setAccessToken: (token) => set({ accessToken: token }),
      setRefreshToken: (token) => set({ refreshToken: token }),
+     logout: () => set({ accessToken: null, refreshToken: null }),
      isModalOpen: false,
      openModal: () => set({ isModalOpen: true }),
      closeModal: () => set({ isModalOpen: false }),
-   }), { name: 'auth-storage' }
+   }), { 
+     name: 'auth-storage',
+     storage: sessionStorage // 보안이 중요한 경우 sessionStorage 사용 고려
+   }
  )
);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 449162a and 7ce1266.

📒 Files selected for processing (5)
  • src/app/provider/authStore.ts (1 hunks)
  • src/pages/home/ui/MainPage.tsx (5 hunks)
  • src/pages/menu/ui/MyTicketPage.tsx (2 hunks)
  • src/shared/types/api/http-client.ts (1 hunks)
  • src/widgets/main/ui/LoginModal.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/pages/menu/ui/MyTicketPage.tsx (1)
src/app/provider/authStore.ts (1)
  • useAuthStore (15-27)
src/widgets/main/ui/LoginModal.tsx (1)
design-system/ui/buttons/HorizontalCardButton.tsx (1)
  • HorizontalCardButton (12-40)
src/pages/home/ui/MainPage.tsx (1)
src/app/provider/authStore.ts (1)
  • useAuthStore (15-27)
🔇 Additional comments (7)
src/widgets/main/ui/LoginModal.tsx (1)

39-39: 카카오 로그인 버튼 클릭 핸들러가 추가되었습니다.

src/pages/menu/ui/MyTicketPage.tsx (1)

11-12: 인증 관련 의존성이 올바르게 추가되었습니다.

src/shared/types/api/http-client.ts (1)

9-9: withCredentials 옵션이 추가되었습니다.

이제 요청 시 인증 정보(쿠키)가 함께 전송됩니다.

src/pages/home/ui/MainPage.tsx (1)

35-35: spacing 수정이 적용되었습니다.

src/app/provider/authStore.ts (3)

2-2: Zustand persist 미들웨어 추가

Zustand의 persist 미들웨어를 추가하여 인증 상태를 브라우저 스토리지에 유지하도록 구현했습니다. 이는 페이지 새로고침 후에도 로그인 상태를 유지할 수 있게 해줍니다.


5-9: 토큰 관리 기능 추가

AuthStore 인터페이스에 액세스 토큰과 리프레시 토큰을 관리하기 위한 속성과 메서드가 적절하게 추가되었습니다. 타입을 string | null로 지정한 것은 토큰의 존재 여부를 명확히 표현할 수 있어 좋은 접근법입니다.


15-27: 보안 관련 고려사항

토큰을 브라우저 스토리지에 저장하는 것은 XSS 공격에 취약할 수 있습니다. 만약 이 프로젝트에서 보안이 중요하다면, 리프레시 토큰은 httpOnly 쿠키에 저장하고 액세스 토큰만 store에서 관리하는 방식을 고려해 보세요. 또한 중요한 API 요청을 할 때마다 토큰의 유효성을 확인하는 로직도 필요할 수 있습니다.

iconPath={<img src={google} alt="구글 아이콘" className="" />}
label="Google 로그인"
onClick={() => {}}
onClick={gooleLogin}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

구글 로그인 버튼에 오타가 있는 함수를 사용하고 있습니다.

구글 로그인 기능을 호출하는 함수명에 오타가 있습니다.

-              onClick={gooleLogin}
+              onClick={googleLogin}
📝 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
onClick={gooleLogin}
onClick={googleLogin}

Comment on lines +12 to +17
const kakaoLogin = () => {
window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/kakao';
};
const gooleLogin = () => {
window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/google';
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

OAuth 로그인 함수 구현 개선이 필요합니다.

OAuth 로그인 함수에 다음과 같은 개선이 필요합니다:

  1. gooleLogin 함수명에 오타가 있습니다 (googleLogin으로 수정 필요)
  2. 하드코딩된 URL은 환경 변수로 이동하는 것이 바람직합니다
  3. 로딩 상태 표시나 오류 처리 메커니즘이 없습니다

다음과 같이 개선할 것을 제안합니다:

-  const kakaoLogin = () => {
-    window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/kakao';
-  };
-  const gooleLogin = () => {
-    window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/google';
-  }
+  const [isLoading, setIsLoading] = useState(false);
+  
+  const kakaoLogin = () => {
+    try {
+      setIsLoading(true);
+      window.location.href = import.meta.env.VITE_API_BASE_URL + '/oauth2/authorization/kakao';
+    } catch (error) {
+      console.error('카카오 로그인 중 오류 발생:', error);
+      setIsLoading(false);
+    }
+  };
+  
+  const googleLogin = () => {
+    try {
+      setIsLoading(true);
+      window.location.href = import.meta.env.VITE_API_BASE_URL + '/oauth2/authorization/google';
+    } catch (error) {
+      console.error('구글 로그인 중 오류 발생:', error);
+      setIsLoading(false);
+    }
+  }
📝 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
const kakaoLogin = () => {
window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/kakao';
};
const gooleLogin = () => {
window.location.href = 'http://ec2-3-35-48-123.ap-northeast-2.compute.amazonaws.com:8080/oauth2/authorization/google';
}
const [isLoading, setIsLoading] = useState(false);
const kakaoLogin = () => {
try {
setIsLoading(true);
window.location.href = import.meta.env.VITE_API_BASE_URL + '/oauth2/authorization/kakao';
} catch (error) {
console.error('카카오 로그인 중 오류 발생:', error);
setIsLoading(false);
}
};
const googleLogin = () => {
try {
setIsLoading(true);
window.location.href = import.meta.env.VITE_API_BASE_URL + '/oauth2/authorization/google';
} catch (error) {
console.error('구글 로그인 중 오류 발생:', error);
setIsLoading(false);
}
}

Comment on lines +38 to +52
const { setAccessToken, setRefreshToken } = useAuthStore();
useEffect(() => {
const accessToken = Cookies.get('access-token');
const refreshToken = Cookies.get('refresh-token');

console.log("access-token:", accessToken);
console.log("refresh-token:", refreshToken);

if (accessToken) {
setAccessToken(accessToken);
}
if (refreshToken) {
setRefreshToken(refreshToken);
}
}, []);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

토큰 관리 로직에 보안 및 최적화 문제가 있습니다.

다음과 같은 문제점이 있습니다:

  1. 민감한 토큰이 콘솔에 출력되고 있어 보안 위험이 있습니다
  2. 의존성 배열이 비어 있어 컴포넌트 마운트 시에만 실행됩니다
  3. 토큰 설정 시 오류 처리가 없습니다

다음과 같이 개선할 것을 제안합니다:

  const { setAccessToken, setRefreshToken } = useAuthStore();
  useEffect(() => {
    const accessToken = Cookies.get('access-token');
    const refreshToken = Cookies.get('refresh-token');
  
-    console.log("access-token:", accessToken);
-    console.log("refresh-token:", refreshToken);
-  
    if (accessToken) {
      setAccessToken(accessToken);
    }
    if (refreshToken) {
      setRefreshToken(refreshToken);
    }
-  }, []);
+  }, [setAccessToken, setRefreshToken]);
📝 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
const { setAccessToken, setRefreshToken } = useAuthStore();
useEffect(() => {
const accessToken = Cookies.get('access-token');
const refreshToken = Cookies.get('refresh-token');
console.log("access-token:", accessToken);
console.log("refresh-token:", refreshToken);
if (accessToken) {
setAccessToken(accessToken);
}
if (refreshToken) {
setRefreshToken(refreshToken);
}
}, []);
const { setAccessToken, setRefreshToken } = useAuthStore();
useEffect(() => {
const accessToken = Cookies.get('access-token');
const refreshToken = Cookies.get('refresh-token');
if (accessToken) {
setAccessToken(accessToken);
}
if (refreshToken) {
setRefreshToken(refreshToken);
}
}, [setAccessToken, setRefreshToken]);

headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${import.meta.env.VITE_HEADER_TOKEN}`,
//Authorization: `Bearer `,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

인증 관련 코드가 일관되지 않게 주석 처리되었습니다.

Authorization 헤더와 토큰 설정 로직이 주석 처리되었지만, 완전히 제거되지 않았습니다. 이는 코드 품질과 유지보수성을 저하시킵니다. 또한 line 49에서는 여전히 access_token을 참조하고 있으나 다른 부분에서는 access-token을 사용하고 있습니다.

다음과 같이 개선할 것을 제안합니다:

  headers: {
    'Content-Type': 'application/json',
-    //Authorization: `Bearer `,
  },
});

axiosClient.interceptors.request.use(
  config => {
-    //const token = Cookies.get('access_token');
-    //zustand 사용함으로써 코드변경 할 듯 현재는 임시 입니다.
-    // const token = useAuthStore.getState().accessToken;
-    // if (token) {
-    //   config.headers.Authorization = `Bearer ${token}`;
-    // }
+    const token = useAuthStore.getState().accessToken;
+    if (token) {
+      config.headers.Authorization = `Bearer ${token}`;
+    }

    return config;

그리고 아래의 에러 처리 부분도 수정이 필요합니다:

  // 401(토큰 만료)일 경우 로그아웃 처리 or 토큰 갱신 가능
  if (errorInfo.status === 401) {
-    Cookies.remove('access_token');
+    Cookies.remove('access-token');
+    Cookies.remove('refresh-token');

    useAuthStore.getState().openModal();
  }

Also applies to: 18-23

@hyeeuncho hyeeuncho merged commit 26906d8 into develop Apr 14, 2025
2 checks passed
@hyeeuncho hyeeuncho deleted the feat/#96/login branch April 14, 2025 15:04
@coderabbitai coderabbitai bot mentioned this pull request Apr 15, 2025
@Yejiin21 Yejiin21 assigned Yejiin21 and hyeeuncho and unassigned Yejiin21 May 13, 2025
@Yejiin21 Yejiin21 added the 🔧 Feature 기능 구현 label May 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🔧 Feature 기능 구현

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[feat] 소셜 로그인 및 회원가입 구현

2 participants