Skip to content

Conversation

@dioo1461
Copy link
Contributor

@dioo1461 dioo1461 commented Feb 20, 2025

#️⃣ 연관된 이슈>

📝 작업 내용> 이번 PR에서 작업한 내용을 간략히 설명해주세요(이미지 첨부 가능)

  • 로그인 상태에 따라, 헤더에 아바타 혹은 로그인 버튼을 표시합니다.

  • 로그인 상태

image
  • 비로그인 상태
image

🙏 여기는 꼭 봐주세요! > 리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요

Summary by CodeRabbit

  • New Features

    • Enhanced the navigation header to display a user avatar when logged in, offering a more personalized experience.
    • Improved the integration of user profile data for a responsive and consistent interface across login and landing pages.
  • Refactor

    • Streamlined the header structure and simplified login state handling to deliver a cleaner and more intuitive user experience.

@dioo1461 dioo1461 requested a review from hamo-o as a code owner February 20, 2025 04:47
@dioo1461 dioo1461 self-assigned this Feb 20, 2025
@dioo1461 dioo1461 added the 🖥️ FE Frontend label Feb 20, 2025
@coderabbitai
Copy link

coderabbitai bot commented Feb 20, 2025

Warning

Rate limit exceeded

@dioo1461 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 46 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 0cf85c494c07d165adfe164a7c3c46b063e59bb9 and ab0fa7a.

📒 Files selected for processing (10)
  • frontend/src/components/Avatar/index.tsx (2 hunks)
  • frontend/src/features/user/api/index.ts (1 hunks)
  • frontend/src/features/user/api/keys.ts (1 hunks)
  • frontend/src/features/user/api/queries.ts (1 hunks)
  • frontend/src/features/user/model/index.ts (1 hunks)
  • frontend/src/layout/GlobalNavBar/index.css.ts (1 hunks)
  • frontend/src/layout/GlobalNavBar/index.tsx (2 hunks)
  • frontend/src/routes/landing/index.tsx (1 hunks)
  • frontend/src/routes/login/index.lazy.tsx (1 hunks)
  • frontend/src/utils/auth/index.ts (1 hunks)

Walkthrough

This pull request introduces a new user API module alongside related model and query utilities. It implements a new API method to fetch the current user information and validates the response using a new schema. Related authentication utilities are refactored to use a constant for the access token key. In addition, the GlobalNavBar component is updated to conditionally render a user avatar instead of a login link, simplifying the layout in both landing and login pages.

Changes

Files Change Summary
frontend/.../user/api/index.ts
frontend/.../user/api/keys.ts
frontend/.../user/api/queries.ts
Introduced a new API module (userApi) with a getUserInfo method, a query key generator (userInfoQueryKey), and a custom React Query hook (useUserInfoQuery) for fetching user information.
frontend/.../user/model/index.ts Added a new schema (UserInfoSchema) to validate user information and exported a new type (UserInfo).
frontend/.../GlobalNavBar/index.tsx
frontend/.../routes/landing/index.tsx
frontend/.../routes/login/index.lazy.tsx
Updated GlobalNavBar to check for user authentication and display a UserAvatar instead of the login link; simplified the layout in landing and login pages.
frontend/.../utils/auth/index.ts Introduced a constant ACCESS_TOKEN_KEY and refactored getAccessToken and isLogin functions to use this constant for consistency.

Sequence Diagram(s)

sequenceDiagram
    participant UI as GlobalNavBar
    participant Query as useUserInfoQuery
    participant Auth as getAccessToken
    participant API as userApi.getUserInfo
    participant Server as /api/v1/user/current

    UI->>Query: Render & trigger user query
    Query->>Auth: Retrieve accessToken
    Auth-->>Query: Return accessToken
    Query->>API: Call getUserInfo()
    API->>Server: GET /api/v1/user/current
    Server-->>API: Return user data
    API->>API: Validate data with UserInfoSchema
    API-->>Query: Return parsed user info
    Query-->>UI: Provide user data for display (UserAvatar)
Loading

Possibly related PRs

Suggested labels

🛠️ BE

Suggested reviewers

  • hamo-o

Poem

I'm a coding bunny, hopping through the night,
Fetching user data with all my might.
I nibble on code and hop through the lines,
Bringing fresh changes in neat little signs.
With a twitch of my nose, our project shines bright!


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.

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

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

🧹 Nitpick comments (4)
frontend/src/features/user/api/keys.ts (1)

2-3: Consider implementing the TODO to enhance security.

The current implementation exposes the raw access token in the query key. While functionally correct, implementing the suggested hash would improve security by preventing the raw token from being exposed in debugging tools and logs.

Consider using a one-way hash function like SHA-256. Example implementation:

-export const userInfoQueryKey = (accessToken: string | null) => ['userInfo', accessToken];
+export const userInfoQueryKey = (accessToken: string | null) => ['userInfo', accessToken ? sha256(accessToken) : null];
frontend/src/utils/auth/index.ts (1)

3-4: Add type safety and error handling for localStorage operations.

The current implementation assumes localStorage operations will always succeed. Consider adding type safety and error handling:

-export const getAccessToken = () => localStorage.getItem(ACCESS_TOKEN_KEY);
+export const getAccessToken = (): string | null => {
+  try {
+    return localStorage.getItem(ACCESS_TOKEN_KEY);
+  } catch (error) {
+    console.error('Failed to access localStorage:', error);
+    return null;
+  }
+};

-export const isLogin = () => localStorage.getItem(ACCESS_TOKEN_KEY) !== null;
+export const isLogin = (): boolean => {
+  try {
+    return localStorage.getItem(ACCESS_TOKEN_KEY) !== null;
+  } catch (error) {
+    console.error('Failed to check login status:', error);
+    return false;
+  }
+};
frontend/src/features/user/api/queries.ts (1)

8-11: Enhance React Query configuration with essential options.

The query configuration could benefit from additional options to improve user experience and error handling:

+import type { UserInfo } from '../model';

-export const useUserInfoQuery = () => useQuery({
+export const useUserInfoQuery = () => useQuery<UserInfo, Error>({
   queryKey: userInfoQueryKey(getAccessToken()),
   queryFn: () => userApi.getUserInfo(),
+  retry: 2,
+  staleTime: 5 * 60 * 1000, // 5 minutes
+  cacheTime: 30 * 60 * 1000, // 30 minutes
+  refetchOnWindowFocus: true,
+  onError: (error) => {
+    console.error('Failed to fetch user info:', error);
+  },
 });
frontend/src/layout/GlobalNavBar/index.tsx (1)

35-39: Consider using theme tokens for gap values.

The gap value of 300 seems arbitrary. Consider:

  1. Using theme tokens for consistent spacing
  2. Ensuring the layout is responsive
 <Flex
   align='center'
   direction='row'
-  gap={300}
+  gap={theme.spacing.lg}
 >
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e42137b and 0cf85c494c07d165adfe164a7c3c46b063e59bb9.

📒 Files selected for processing (8)
  • frontend/src/features/user/api/index.ts (1 hunks)
  • frontend/src/features/user/api/keys.ts (1 hunks)
  • frontend/src/features/user/api/queries.ts (1 hunks)
  • frontend/src/features/user/model/index.ts (1 hunks)
  • frontend/src/layout/GlobalNavBar/index.tsx (2 hunks)
  • frontend/src/routes/landing/index.tsx (1 hunks)
  • frontend/src/routes/login/index.lazy.tsx (1 hunks)
  • frontend/src/utils/auth/index.ts (1 hunks)
🔇 Additional comments (5)
frontend/src/routes/login/index.lazy.tsx (1)

8-8: LGTM! Clean and consistent with the new GlobalNavBar implementation.

The removal of LoginLink from GlobalNavBar is appropriate as the login state is now handled internally by the GlobalNavBar component.

frontend/src/routes/landing/index.tsx (1)

8-8: LGTM! Clean and consistent with the new GlobalNavBar implementation.

The removal of LoginLink from GlobalNavBar is appropriate as the login state is now handled internally by the GlobalNavBar component.

frontend/src/features/user/model/index.ts (2)

10-13: LGTM! Well-structured schema for user info.

The UserInfoSchema is appropriately defined with necessary fields for avatar display and includes proper URL validation for the picture field.


15-16: LGTM! Clean type definitions.

Types are correctly inferred from the Zod schemas, providing type safety throughout the application.

frontend/src/layout/GlobalNavBar/index.tsx (1)

34-44: LGTM! Clean conditional rendering based on login state.

The implementation correctly handles the display of either UserAvatar or LoginLink based on the login state.

Comment on lines +6 to +10
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and type safety for API response.

The API call should handle potential network errors and invalid responses. Also, consider adding explicit return type:

+import { UserInfo } from '../model';

 export const userApi = {
-  getUserInfo: async () => {
+  getUserInfo: async (): Promise<UserInfo> => {
     try {
       const response = await request.get('/api/v1/user/current');
       const parsedData = UserInfoSchema.parse(response);
       return parsedData;
+    } catch (error) {
+      if (error instanceof Error) {
+        console.error('Failed to fetch user info:', error.message);
+      }
+      throw error;
     }
   },
 };
📝 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
getUserInfo: async () => {
const response = await request.get('/api/v1/user/current');
const parsedData = UserInfoSchema.parse(response);
return parsedData;
},
import { UserInfo } from '../model';
export const userApi = {
getUserInfo: async (): Promise<UserInfo> => {
try {
const response = await request.get('/api/v1/user/current');
const parsedData = UserInfoSchema.parse(response);
return parsedData;
} catch (error) {
if (error instanceof Error) {
console.error('Failed to fetch user info:', error.message);
}
throw error;
}
},
};

Comment on lines 50 to 60
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance loading and error states in UserAvatar component.

The current loading and error messages are not user-friendly. Consider:

  1. Using a loading skeleton or spinner for better UX
  2. Implementing proper error handling with retry mechanism
  3. Adding error boundaries for graceful fallback

Example implementation:

 const UserAvatar = () => {
   const { data, isPending } = useUserInfoQuery();
-  if (isPending) return <div>pending ...</div>;
-  if (!data) return <div>user data is undefined or null</div>;
+  if (isPending) return <Avatar.Skeleton size='lg' />;
+  if (!data) {
+    return (
+      <ErrorBoundary fallback={<Avatar.Fallback size='lg' />}>
+        <RetryButton onClick={() => queryClient.invalidateQueries({ queryKey: ['userInfo'] })} />
+      </ErrorBoundary>
+    );
+  }
   return (
     <Avatar imageUrls={[data.picture]} size='lg' />
   );
 };
📝 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 UserAvatar = () => {
const { data, isPending } = useUserInfoQuery();
if (isPending) return <div>pending ...</div>;
if (!data) return <div>user data is undefined or null</div>;
return (
<Avatar imageUrls={[data.picture]} size='lg' />
);
};
const UserAvatar = () => {
const { data, isPending } = useUserInfoQuery();
if (isPending) return <Avatar.Skeleton size='lg' />;
if (!data) {
return (
<ErrorBoundary fallback={<Avatar.Fallback size='lg' />}>
<RetryButton onClick={() => queryClient.invalidateQueries({ queryKey: ['userInfo'] })} />
</ErrorBoundary>
);
}
return (
<Avatar imageUrls={[data.picture]} size='lg' />
);
};

Copy link
Contributor

@hamo-o hamo-o left a comment

Choose a reason for hiding this comment

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

굿굿 이거 CSS만 수정 부탁드립니다 (디자인에서는 버튼끼리는 갭 없어용)

image

@dioo1461 dioo1461 force-pushed the feature/fe/header-avatar branch from 9b618db to ab0fa7a Compare February 20, 2025 05:44
@dioo1461
Copy link
Contributor Author

굿굿 이거 CSS만 수정 부탁드립니다 (디자인에서는 버튼끼리는 갭 없어용)

ab0fa7a
반영되었습니다~

@dioo1461 dioo1461 merged commit 68c89eb into dev Feb 20, 2025
1 check passed
@dioo1461 dioo1461 deleted the feature/fe/header-avatar branch February 20, 2025 05:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🖥️ FE Frontend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants