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

Login redirection fixed #546

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open

Login redirection fixed #546

wants to merge 1 commit into from

Conversation

erenfn
Copy link
Collaborator

@erenfn erenfn commented Feb 18, 2025

Solves #536

Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Walkthrough

The changes update the authentication redirection flow. The Private component now uses the useLocation hook to capture the current URL, enabling redirection back to the intended page after login. Similarly, the LoginPage extracts the redirect query parameter from the URL and passes it to the authentication success handler. The handleAuthSuccess function was modified to conditionally navigate based on team existence or the provided redirection route.

Changes

File(s) Change Summary
frontend/src/components/Private.jsx
frontend/src/scenes/login/LoginPage.jsx
Added useLocation from react-router-dom to capture the current URL. In Private.jsx, the redirection now includes the current pathname and query string when the user is not logged in. In LoginPage.jsx, the redirect query parameter (redirect) is extracted and passed to handleAuthSuccess.
frontend/src/utils/loginHelper.js Updated handleAuthSuccess function signature to include an optional redirectTo parameter. Modified the control flow to navigate to /progress-steps if no team exists, to the provided redirectTo route if available, or default to / otherwise.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant P as Private Component
    participant L as Login Page
    participant H as Login Helper

    U->>P: Request private content
    P--)P: Check authentication status (isFetching, isLoggedIn)
    alt Data is fetching
        P->>U: Render LoadingPage
    else User is logged in
        P->>U: Render component
    else User is not logged in
        P->>L: Redirect to Login with current URL as query parameter
        L->>L: Extract "redirect" parameter from URL
        U->>L: Submit login credentials
        L->>H: Call handleAuthSuccess(response, loginAuth, navigate, redirectTo)
        H--)H: Check if team exists
        alt Team does not exist
            H->>U: Navigate to /progress-steps
        else redirectTo provided or not
            H->>U: Navigate to redirectTo or default '/'
        end
    end
Loading
✨ 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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

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

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: 3

🧹 Nitpick comments (2)
frontend/src/utils/loginHelper.js (1)

25-25: There's errors on his sweater already!

The error logging could be more informative for debugging.

Enhance error logging:

- .catch(err => console.error(err));
+ .catch(err => {
+   console.error('Auth navigation failed:', err);
+   navigate('/');  // Fallback to home on error
+ });
frontend/src/scenes/login/LoginPage.jsx (1)

54-54: He's nervous, but on the surface the code looks calm and ready!

The handleAuthSuccess call is clean, but we should handle potential navigation failures.

Add error boundary:

- handleAuthSuccess(response, loginAuth, navigate, redirectTo);
+ try {
+   handleAuthSuccess(response, loginAuth, navigate, redirectTo);
+ } catch (error) {
+   console.error('Navigation failed:', error);
+   setServerErrors(['Login successful but navigation failed. Please try again.']);
+ }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b2dd50 and e549745.

⛔ Files ignored due to path filters (1)
  • frontend/dist/index.html is excluded by !**/dist/**
📒 Files selected for processing (3)
  • frontend/src/components/Private.jsx (1 hunks)
  • frontend/src/scenes/login/LoginPage.jsx (3 hunks)
  • frontend/src/utils/loginHelper.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (1)
frontend/src/components/Private.jsx (1)

10-10: Mom's spaghetti... I mean, nice loading handling!

The loading state prevents jarring redirects. Good UX consideration.


const Private = ({ Component }) => {
const { isLoggedIn, isFetching } = useAuth();
const location = useLocation();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Yo dawg, we need to sanitize that URL parameter!

The redirect URL needs validation to prevent open redirect vulnerabilities. An attacker could craft malicious redirect URLs.

Add URL validation before encoding:

- <Navigate to={`/login?redirect=${encodeURIComponent(location.pathname + location.search)}`} />
+ const isValidRedirect = (url) => url.startsWith('/') && !url.startsWith('//');
+ const redirectPath = location.pathname + location.search;
+ <Navigate to={`/login?redirect=${isValidRedirect(redirectPath) ? encodeURIComponent(redirectPath) : ''}`} />

Also applies to: 15-15

@@ -1,7 +1,7 @@
import { getTeamCount } from '../services/teamServices';
import toastEmitter, { TOAST_EMITTER_KEY } from './toastEmitter';

export const handleAuthSuccess = (response, loginAuth, navigate) => {
export const handleAuthSuccess = (response, loginAuth, navigate, redirectTo = null) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Knees weak, arms are heavy... but this error handling's not ready!

The navigation logic looks good, but we should enhance error handling for the redirect path.

Add validation and error handling:

- export const handleAuthSuccess = (response, loginAuth, navigate, redirectTo = null) => {
+ export const handleAuthSuccess = (response, loginAuth, navigate, redirectTo = '/') => {
     // ... existing code ...
     if (!teamExists) {
         navigate('/progress-steps');
-    } else if(redirectTo){
+    } else if(redirectTo && redirectTo.startsWith('/')){
         navigate(redirectTo)
     }
     else {
         navigate('/');
     }

Also applies to: 18-23

Comment on lines +32 to +33
const params = new URLSearchParams(location.search);
const redirectTo = params.get("redirect") || '/';
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Vomit on his sweater already... but this URL handling's steady!

Clean URL parameter extraction, but let's add some validation.

Add URL validation:

  const params = new URLSearchParams(location.search);
- const redirectTo = params.get("redirect") || '/';
+ const redirect = params.get("redirect");
+ const redirectTo = (redirect && redirect.startsWith('/') && !redirect.startsWith('//')) ? redirect : '/';
📝 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 params = new URLSearchParams(location.search);
const redirectTo = params.get("redirect") || '/';
const params = new URLSearchParams(location.search);
const redirect = params.get("redirect");
const redirectTo = (redirect && redirect.startsWith('/') && !redirect.startsWith('//')) ? redirect : '/';

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