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

Add redirection after login #396

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

Conversation

wet6123
Copy link
Contributor

@wet6123 wet6123 commented Nov 2, 2024

What this PR does / why we need it:

Store previous page URL before login.
Redirect user back to stored URL after successful login.
Add default redirect to home page if URL doesn't exists.
Until now, Codepair always redirects you to home after login failure. This allows you to redirect to the intended location.

Which issue(s) this PR fixes:

Fixes #308

Special notes for your reviewer:

Does this PR introduce a user-facing change?:

Redirect user to previous page after successful login.

Additional documentation:


Checklist:

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • New Features

    • Enhanced login functionality to support location-based redirection after authentication.
    • Improved redirection logic after successful authentication to navigate users to their intended destination.
  • Bug Fixes

    • Fixed the handling of redirect paths to ensure users are directed appropriately post-login.

Store previous page URL before login.
Redirect user back to stored URL after successful login.
Add default redirect to home page if URL doesn't exists.
Copy link
Contributor

coderabbitai bot commented Nov 2, 2024

Walkthrough

The changes introduced in this pull request enhance the user login flow by implementing location-based redirection. In the Index component, the useLocation hook is utilized to capture the user's intended pathname, which is stored in session storage upon login. The CallbackIndex component is updated to retrieve this redirect path from session storage after authentication, ensuring users are directed to their intended page instead of the root path.

Changes

File Change Summary
frontend/src/pages/Index.tsx Added useLocation import and a constant location to capture the pathname for redirection. Updated handleLogin to store the redirect path in session storage.
frontend/src/pages/auth/callback/Index.tsx Modified CallbackIndex to retrieve the redirect path from session storage and navigate to it after setting tokens.

Assessment against linked issues

Objective Addressed Explanation
Redirect users to their intended page after login failure (#308)

Possibly related PRs

  • Implement Refresh Token #317: The changes in the CallbackIndex component for handling redirection after authentication are directly related to the modifications in the Index component, which also focuses on managing user login and redirect paths.

Suggested labels

enhancement 🌟

Poem

In the burrow where we hop and play,
A path was lost, but now it's okay.
With every login, we find our way,
To the page we seek, come what may!
Hooray for redirects, let’s cheer and sway! 🐇✨


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

🧹 Outside diff range and nitpick comments (2)
frontend/src/pages/auth/callback/Index.tsx (1)

24-26: Consider validating the redirect path.

The implementation looks good and aligns with the PR objectives. However, consider validating the redirect path from sessionStorage to prevent potential open redirect vulnerabilities.

Here's a suggested improvement:

-		const redirect = sessionStorage.getItem("redirect") || "/";
-		sessionStorage.removeItem("redirect");
-		navigate(redirect);
+		const redirect = sessionStorage.getItem("redirect");
+		sessionStorage.removeItem("redirect");
+		// Ensure the redirect path is internal
+		const isValidPath = redirect && (redirect.startsWith('/') && !redirect.startsWith('//'));
+		navigate(isValidPath ? redirect : '/');
frontend/src/pages/Index.tsx (1)

15-19: Consider handling error cases in the login flow.

The implementation meets the core requirement but should consider handling these scenarios:

  1. Social login failure - how to preserve the redirect path
  2. Invalid stored paths - how to gracefully fallback
  3. Timeout scenarios - how long should the redirect path persist

Consider adding error boundaries and appropriate error handling to ensure a smooth user experience even when things go wrong.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 20a84cf and 5020a7d.

📒 Files selected for processing (2)
  • frontend/src/pages/Index.tsx (2 hunks)
  • frontend/src/pages/auth/callback/Index.tsx (1 hunks)
🔇 Additional comments (3)
frontend/src/pages/auth/callback/Index.tsx (1)

24-26: Verify the storage of redirect path.

Let's verify that the Index component correctly stores the redirect path in sessionStorage.

✅ Verification successful

Let me gather more information about how the redirect is being set in Index.tsx.


The redirect path storage and retrieval implementation is correct

The implementation forms a complete flow:

  • In frontend/src/pages/Index.tsx, the redirect path is properly stored using sessionStorage.setItem("redirect", from) before OAuth login, where from captures the original location
  • In the callback component, this path is correctly retrieved and cleared using sessionStorage.getItem("redirect") followed by sessionStorage.removeItem("redirect")
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of redirect path storage in Index component

# Test: Search for sessionStorage.setItem with "redirect"
echo "Searching for redirect path storage implementation..."
rg -l 'sessionStorage\.setItem.*redirect' 'frontend/src'

# Test: Verify the usage of useLocation
echo "Verifying useLocation usage for pathname..."
ast-grep --pattern 'const $_ = useLocation()'

Length of output: 756


Script:

#!/bin/bash
# Get the implementation from Index.tsx where redirect is being set
echo "Checking Index.tsx implementation for redirect storage:"
rg -A 5 -B 5 'sessionStorage\.setItem.*redirect' frontend/src/pages/Index.tsx

# Check the auth callback implementation
echo -e "\nChecking auth callback implementation:"
cat frontend/src/pages/auth/callback/Index.tsx

Length of output: 1575

frontend/src/pages/Index.tsx (2)

4-4: LGTM! Appropriate use of react-router-dom's useLocation hook.

The import is correctly placed and uses the recommended hook for accessing router location information.


14-14: Consider validating the redirect pathname for security.

While the code correctly handles the redirect path, it's important to validate the pathname to prevent open redirect vulnerabilities. Consider implementing checks to ensure the path is internal to your application.

Example validation approach:

const isValidRedirectPath = (path: string) => {
  // Ensure path starts with / and doesn't contain protocol/domain
  return path.startsWith('/') && !path.includes('://') && !path.includes('//');
};

const from = location.state?.from?.pathname || "/";
const safePath = isValidRedirectPath(from) ? from : "/";

Also applies to: 16-16

frontend/src/pages/Index.tsx Show resolved Hide resolved
@wet6123 wet6123 self-assigned this Nov 2, 2024
Copy link
Member

@devleejb devleejb left a comment

Choose a reason for hiding this comment

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

It seems that it’s not working as expected.

I tested the following case:

  1. Access a document without an authorization token and get redirected to the login page.
  2. Log in with GitHub.
  3. The page is redirected to the workspace instead of the document page (it should redirect to the document page).

I think it is routed byfrontend/src/components/common/GuestRoute.tsx.

@wet6123
Copy link
Contributor Author

wet6123 commented Nov 3, 2024

@devleejb
Oh, I forgot to mention about the strict mode. I stored the previous URL at the session storage. And then when login success, use the URL and remove it. In strict mode, this code will run twice and the URL will be gone. Then it goes to "/".
So, if you disable strict mode, it works fine.
Or I can change it not to remove the URL at the session storage. To ensure that it works well even in strict mode.

@devleejb
Copy link
Member

devleejb commented Nov 3, 2024

@wet6123 I believe it should also work well in strict mode. What do you think?

@wet6123
Copy link
Contributor Author

wet6123 commented Nov 5, 2024

@devleejb I think it's better to make it work in strict mode. I can finish it until this weekend.

@devleejb
Copy link
Member

devleejb commented Dec 8, 2024

Is there any progress?

@wet6123
Copy link
Contributor Author

wet6123 commented Dec 9, 2024

@devleejb
I'm sorry for the delay. I was busy with my work, so I couldn't proceed.

Currently, this function is implemented to perform using session storage. If we simply remove 'removeItem' for session storage, it will be able to operate in strict mode. This has the disadvantage of leaving url in session storage. However, it seems to be the simplest way.

Another way I think is to customize the github authguard on the nestjs server to manage the "url to move after login" as a cookie. This seems quite difficult because oauth is handled by the server and redirection is used. For this, I think I can study more about the nestjs authguard or work with someone I know well.

So my suggestion is to use the session storage method and then apply the new method through backend refactoring. If possible, I'd like to continue with refactoring.

What do you think about this?

@devleejb
Copy link
Member

It’s OK!

If it can be implemented using AuthGuard, I agree with this approach.
Could you then explain your plan for customizing AuthGuard?

@wet6123
Copy link
Contributor Author

wet6123 commented Dec 11, 2024

@devleejb
The way I thought about it was saving url with cookies before moving to login flow from authguard.

But today, I found that after the oauth login process, we are now sending the token as a query parameter. I think we should send it with HTTP header or body.

If you want to talk more about this, can we talk on Discord voice chat? Anytime after 9pm is fine today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

Add feature to redirect users to their intended page after login failure
2 participants