Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix redirect logic in analytics platform #2531

Merged
merged 2 commits into from
Feb 25, 2025
Merged

Conversation

Codebmk
Copy link
Member

@Codebmk Codebmk commented Feb 25, 2025

This pull request includes changes to the withAuth function in src/platform/src/core/utils/protectedRoute.js to improve the handling of user redirection during authentication. The most important changes include defining a constant for the login route, adding a state to manage redirection to the login page, and ensuring the redirection logic is handled in a separate useEffect hook.

Improvements to user redirection:

  • Defined a constant LOGIN_ROUTE for the login path to avoid hardcoding the route multiple times.
  • Added a new state redirectToLogin to manage the redirection to the login page.
  • Updated the authentication logic to set redirectToLogin instead of directly pushing to the login route.
  • Introduced a new useEffect hook to handle the deferred redirect to the login page based on the redirectToLogin state.
  • Ensured the isRedirecting state is reset to false upon successful authentication.

Summary by CodeRabbit

  • New Features

    • Introduced a new constant for the login route and enhanced the redirection logic for user authentication.
    • Added state management for redirecting users to the login page based on authentication errors.
  • Refactor

    • Updated the export method for the Home component to utilize dynamic imports, improving the handling of authentication during page loads.

@Codebmk Codebmk requested a review from Baalmart February 25, 2025 15:26
@Codebmk Codebmk self-assigned this Feb 25, 2025
Copy link

coderabbitai bot commented Feb 25, 2025

📝 Walkthrough

Walkthrough

The changes refactor the redirection mechanism in protectedRoute.js. A new constant LOGIN_ROUTE is introduced, and a state variable redirectToLogin is used to track when a redirect should occur. Instead of directly calling router.push('/account/login') upon authentication failures or errors, the flag is set to true. A new useEffect hook then checks this flag and performs the redirection, centralizing the logic and ensuring proper state management during user session setups.

Changes

File Path Change Summary
src/platform/src/core/utils/protectedRoute.js Added LOGIN_ROUTE constant; introduced redirectToLogin and isMounted state variables; refactored error and authentication handling to set the redirection flag instead of calling router.push directly; implemented a useEffect hook to execute redirection based on the flag.
src/platform/src/pages/Home/index.jsx Updated export statement to use dynamic import for Home component, replacing withAuth HOC with asynchronous loading and disabling server-side rendering (SSR).

Possibly related PRs

Suggested labels

ready for review

Suggested reviewers

  • Baalmart
  • OchiengPaul442

Poem

A new route emerges, neat and kind,
Guiding each user with state aligned.
Through useEffect’s watchful, careful eye,
It redirects smoothly—no more erring by.
Cheers to code that flows just right,
Lighting our path with future bright! 🚀

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.

📜 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 46ca899 and 26d1057.

📒 Files selected for processing (2)
  • src/platform/src/core/utils/protectedRoute.js (2 hunks)
  • src/platform/src/pages/Home/index.jsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-push-deploy-analytics-platform-preview
  • GitHub Check: test-analytics-platform-changes
🔇 Additional comments (12)
src/platform/src/pages/Home/index.jsx (2)

1-1: Good addition of dynamic import.

The inclusion of dynamic from Next.js is necessary to support the updated export strategy at line 305.


305-305: Well-structured dynamic component loading with disabled SSR.

The change from a direct export to using Next.js dynamic import with ssr: false is a good approach. This ensures that authentication checks happen only on the client side where localStorage is available, preventing hydration mismatches that could occur when server and client render different content based on auth state.

This approach aligns well with the redirection logic improvements in the protectedRoute.js file.

src/platform/src/core/utils/protectedRoute.js (10)

17-17: Good practice using a constant for the login route.

Creating a LOGIN_ROUTE constant eliminates magic strings and makes future route changes easier to maintain.


24-26: Refined state initialization using router query.

The state initialization is now properly structured to check if the user is coming from Google authentication.


27-28: Good addition of state variables for redirect control.

The new state variables redirectToLogin and isMounted provide better control over the redirection flow, avoiding potential race conditions and ensuring the component is properly mounted before navigation occurs.


64-64: Clear state management after authentication success.

Explicitly resetting isRedirecting to false after successful authentication ensures proper state cleanup.


68-71: Proper mount tracking implementation.

The implementation of the isMounted state helps prevent unnecessary redirects and state updates when the component is not yet mounted.


73-118: Well-structured authentication flow with centralized error handling.

The refactored authentication logic into a handleAuth function improves readability and maintainability. The changes properly manage redirect states instead of directly navigating to the login page, which allows for more controlled redirects.

I particularly like how the code now sets the redirect flag instead of directly calling router.push() in multiple places, centralizing the navigation logic.


93-93: Proper error handling for Google authentication.

When Google authentication fails, setting redirectToLogin instead of directly navigating ensures consistent behavior in the redirect flow.


101-102: Improved redirection logic for unauthenticated users.

Setting the redirect flag and returning early improves the control flow and prevents unnecessary code execution.


106-115: Thorough cleanup before redirection.

The code properly cleans up both localStorage and Redux state before redirecting to login when there's no stored user group, which is essential for preventing authentication state inconsistencies.


126-130: Excellent centralized redirection handling.

Using a dedicated useEffect for handling redirects is a smart approach. This ensures that all redirects happen in one place and only when the component is mounted, preventing potential issues with multiple redirect attempts.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 or @coderabbitai title 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: 0

🧹 Nitpick comments (1)
src/platform/src/core/utils/protectedRoute.js (1)

102-107: Good separation of concerns with dedicated useEffect.

Creating a separate useEffect for handling redirects follows the principle of separation of concerns and keeps the code more maintainable.

However, consider resetting the redirectToLogin state after navigation occurs to prevent potential issues if the component doesn't unmount:

useEffect(() => {
  if (redirectToLogin) {
    router.push(LOGIN_ROUTE);
+   setRedirectToLogin(false);
  }
}, [redirectToLogin, router]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 716b56b and 46ca899.

📒 Files selected for processing (1)
  • src/platform/src/core/utils/protectedRoute.js (5 hunks)
🔇 Additional comments (6)
src/platform/src/core/utils/protectedRoute.js (6)

17-17: Good practice: Using a constant for the login route path.

Using a constant instead of hardcoded strings improves maintainability. If the login route changes in the future, you'll only need to update it in one place rather than hunting down multiple occurrences.


27-27: Clean approach: Using state to manage redirect logic.

Using a dedicated state variable to control redirects separates the decision to redirect from the actual redirection action. This is a cleaner architectural approach than directly calling navigation methods throughout the code.


79-87: Improved error handling with centralized redirect logic.

The changes properly centralize the redirect logic by setting a state flag instead of directly calling router.push. This is more consistent and follows React's declarative approach to UI management.


82-83: Consider the timing of this redirect check.

The check if (!userCredentials.success) in the finally block might cause unexpected behavior. This will run regardless of whether the preceding code succeeded or failed, potentially triggering a redirect even if the error was unrelated to authentication.

Consider moving this check outside the finally block or being more specific about when to redirect:

.catch((error) => {
  console.error('Google auth error:', error);
  setIsRedirecting(false);
  setRedirectToLogin(true);
})
.finally(() => {
-  if (!userCredentials.success) setRedirectToLogin(true);
});

93-94: Consistent redirect approach.

Using setRedirectToLogin(true) here maintains consistency with the new pattern established elsewhere in the file. Good consistency!


63-63: Ensure this reset occurs at the right time.

This line resets isRedirecting to false once the user session is successfully set up, which is appropriate. Make sure this matches your intended flow of showing/hiding the spinner during authentication.

Copy link
Contributor

New next-platform changes available for preview here

Copy link
Contributor

New next-platform changes available for preview here

@Baalmart Baalmart merged commit 8dec558 into staging Feb 25, 2025
28 of 29 checks passed
@Baalmart Baalmart deleted the feat-google-login branch February 25, 2025 17:21
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.

2 participants