Skip to content

VER-228 - Handle redirect after logged in#204

Merged
giahung68 merged 2 commits intomainfrom
features/228-redirect-after-logged-in
Dec 3, 2024
Merged

VER-228 - Handle redirect after logged in#204
giahung68 merged 2 commits intomainfrom
features/228-redirect-after-logged-in

Conversation

@giahung68
Copy link
Collaborator

@giahung68 giahung68 commented Dec 3, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced login functionality with conditional redirection based on URL parameters.
    • Flexible login redirection after Google sign-in.
  • Bug Fixes

    • Improved error handling in the LanguageTabs and SnippetDetail components to prevent runtime errors.
    • Added null checks to ensure safe access of language properties in various components.
  • Documentation

    • Updated comments in the SnippetAudioPlayer for clarity on audio playback features.

@linear
Copy link

linear bot commented Dec 3, 2024

@coderabbitai
Copy link

coderabbitai bot commented Dec 3, 2024

Walkthrough

The pull request includes modifications across several components to enhance error handling and improve user navigation. Key changes involve adding null checks and optional chaining in the LanguageTabs, SnippetDetail, and LoginPage components. Additionally, the PublicHeaderBar component now conditionally redirects users based on URL parameters, while the AuthProvider component's loginWithGoogle method has been updated to accept a customizable redirect URL. These changes collectively improve the robustness and flexibility of the application without altering existing functionalities.

Changes

File Change Summary
src/components/LanguageTab.tsx Updated logic for isSourceEnglish to include a null check for sourceLanguage.
src/components/LoginPage.tsx Integrated useLocation for redirect path extraction; updated navigation logic to use redirectTo.
src/components/PublicHeaderBar.tsx Added useParams to retrieve snippetId; modified login handling to redirect conditionally.
src/components/SnippetDetail.tsx Implemented optional chaining for accessing snippet.language.primary_language.
src/providers/auth.tsx Updated loginWithGoogle method to accept an optional redirectTo parameter for flexibility.

Possibly related PRs

Suggested reviewers

  • nlgthuan

🐇 In the code we hop and play,
With checks for null along the way.
A path to follow, clear and bright,
Redirects guide us, day and night.
Robust and ready, we leap with glee,
For every user, happy they’ll be! 🌟


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

@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

🧹 Outside diff range and nitpick comments (3)
src/components/LanguageTab.tsx (1)

33-33: Simplify the null check

The current implementation has redundant null checks. Since && already ensures sourceLanguage exists, the optional chaining operator ?. is unnecessary.

-  const isSourceEnglish = sourceLanguage && sourceLanguage?.toLowerCase() === 'english'
+  const isSourceEnglish = sourceLanguage && sourceLanguage.toLowerCase() === 'english'
src/components/LoginPage.tsx (1)

Line range hint 52-58: Consider handling loading state for Google sign-in

The Google sign-in flow should indicate loading state to prevent multiple clicks.

Add loading state management:

 const handleGoogleSignIn = async () => {
+  setIsLoading(true)
   const { error } = await loginWithGoogle(redirectTo)
   if (error) {
     setError('root', {
       message: error.message
     })
   }
+  setIsLoading(false)
 }
src/components/PublicHeaderBar.tsx (1)

21-23: Consider adding loading state to login button

The login button should indicate when the navigation is in progress.

Add loading state:

-<Button variant='ghost' onClick={handleLogin} className='text-white hover:bg-blue-100 hover:text-blue-700'>
+<Button 
+  variant='ghost' 
+  onClick={handleLogin} 
+  className='text-white hover:bg-blue-100 hover:text-blue-700'
+  disabled={isNavigating}
+>
-  Login
+  {isNavigating ? 'Redirecting...' : 'Login'}
 </Button>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ac8222d and 25b63ce.

📒 Files selected for processing (6)
  • src/components/LanguageTab.tsx (1 hunks)
  • src/components/LoginPage.tsx (5 hunks)
  • src/components/PublicHeaderBar.tsx (2 hunks)
  • src/components/SnippetAudioPlayer.tsx (0 hunks)
  • src/components/SnippetDetail.tsx (3 hunks)
  • src/providers/auth.tsx (2 hunks)
💤 Files with no reviewable changes (1)
  • src/components/SnippetAudioPlayer.tsx
🧰 Additional context used
🪛 eslint
src/components/PublicHeaderBar.tsx

[error] 3-3: Missing file extension for "@/components/ui/button"

(import/extensions)

🔇 Additional comments (4)
src/components/SnippetDetail.tsx (1)

Line range hint 1-447: Implementation looks solid!

The component demonstrates good practices:

  • Proper error handling for async operations
  • Optimistic updates with rollback
  • Clear user feedback through toasts
  • Type-safe implementation
src/providers/auth.tsx (1)

9-9: LGTM: Interface update is consistent with implementation

The AuthContextType interface correctly reflects the new optional redirectTo parameter.

src/components/LoginPage.tsx (1)

36-39: LGTM: Proper dependency handling in useEffect

The useEffect hook correctly includes redirectTo in its dependency array, ensuring proper reactivity.

src/components/PublicHeaderBar.tsx (1)

9-12: LGTM: Proper URL handling in login redirect

The handleLogin function correctly handles the redirect URL construction and encoding.

})
const [snippetLanguage, setSnippetLanguage] = useState<string | undefined>(
snippet?.language?.primary_language.toLowerCase()
snippet?.language?.primary_language?.toLowerCase()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Standardize fallback language handling

While the optional chaining is good for safety, the fallback to 'english' is only implemented in one location. Consider standardizing the fallback across all usages for consistency.

-  const [snippetLanguage, setSnippetLanguage] = useState<string | undefined>(
-    snippet?.language?.primary_language?.toLowerCase()
-  )
+  const [snippetLanguage, setSnippetLanguage] = useState<string>(
+    snippet?.language?.primary_language?.toLowerCase() || 'english'
+  )

-  setSnippetLanguage(snippet.language?.primary_language?.toLowerCase())
+  setSnippetLanguage(snippet.language?.primary_language?.toLowerCase() || 'english')

   sourceLanguage={snippet.language?.primary_language?.toLowerCase() || 'english'}

This ensures consistent behavior when the language is undefined and removes the need for undefined in the state type.

Also applies to: 183-183, 411-411

Comment on lines +79 to +81
const loginWithGoogle = async (redirectTo?: string): Promise<{ error: AuthError | null }> => {
try {
const redirectUrl = (import.meta.env.VITE_AUTH_REDIRECT_URL as string) || '/dashboard'
const redirectUrl = `${window.location.origin}${redirectTo}`
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add URL validation to prevent open redirect vulnerabilities

The current implementation directly concatenates the redirectTo parameter with origin, which could lead to open redirect vulnerabilities if not properly validated.

Consider adding URL validation:

 const loginWithGoogle = async (redirectTo?: string): Promise<{ error: AuthError | null }> => {
   try {
-    const redirectUrl = `${window.location.origin}${redirectTo}`
+    // Validate that redirectTo starts with '/' and only contains allowed paths
+    const validatedPath = redirectTo && /^\/(?:search|snippet\/[\w-]+|onboarding)(?:\?.*)?$/.test(redirectTo)
+      ? redirectTo
+      : '/search'
+    const redirectUrl = `${window.location.origin}${validatedPath}`
     const { error } = await supabase.auth.signInWithOAuth({
📝 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 loginWithGoogle = async (redirectTo?: string): Promise<{ error: AuthError | null }> => {
try {
const redirectUrl = (import.meta.env.VITE_AUTH_REDIRECT_URL as string) || '/dashboard'
const redirectUrl = `${window.location.origin}${redirectTo}`
const loginWithGoogle = async (redirectTo?: string): Promise<{ error: AuthError | null }> => {
try {
// Validate that redirectTo starts with '/' and only contains allowed paths
const validatedPath = redirectTo && /^\/(?:search|snippet\/[\w-]+|onboarding)(?:\?.*)?$/.test(redirectTo)
? redirectTo
: '/search'
const redirectUrl = `${window.location.origin}${validatedPath}`

Comment on lines +31 to +33
// Extract the redirect path from query parameters
const params = new URLSearchParams(location.search)
const redirectTo = params.get('redirect') || '/search'
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Sanitize URL parameters to prevent XSS attacks

The URL parameter extraction should include sanitization to prevent potential XSS attacks through malicious redirect URLs.

Add URL encoding/decoding:

 // Extract the redirect path from query parameters
 const params = new URLSearchParams(location.search)
-const redirectTo = params.get('redirect') || '/search'
+const redirectTo = decodeURIComponent(params.get('redirect') || '/search')

Committable suggestion skipped: line range outside the PR's diff.

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

🧹 Outside diff range and nitpick comments (1)
src/providers/auth.tsx (1)

81-81: Simplify the conditional expression

The ternary operator is unnecessary when providing a default value.

-const redirectUrl = `${window.location.origin}${redirectTo ? redirectTo : import.meta.env.VITE_AUTH_REDIRECT_URL}`
+const redirectUrl = `${window.location.origin}${redirectTo || import.meta.env.VITE_AUTH_REDIRECT_URL}`
🧰 Tools
🪛 eslint

[error] 81-81: Unnecessary use of conditional expression for default assignment.

(no-unneeded-ternary)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 25b63ce and 89c8183.

📒 Files selected for processing (1)
  • src/providers/auth.tsx (2 hunks)
🧰 Additional context used
🪛 eslint
src/providers/auth.tsx

[error] 81-81: Unnecessary use of conditional expression for default assignment.

(no-unneeded-ternary)

🔇 Additional comments (2)
src/providers/auth.tsx (2)

9-9: LGTM: Interface change maintains backward compatibility

The addition of the optional redirectTo parameter is well-typed and maintains backward compatibility with existing code.


79-81: ⚠️ Potential issue

Add URL validation to prevent open redirect vulnerabilities

The current implementation directly concatenates the redirectTo parameter with origin, which could lead to open redirect vulnerabilities if not properly validated.

Consider adding URL validation:

 const loginWithGoogle = async (redirectTo?: string): Promise<{ error: AuthError | null }> => {
   try {
-    const redirectUrl = `${window.location.origin}${redirectTo ? redirectTo : import.meta.env.VITE_AUTH_REDIRECT_URL}`
+    // Validate that redirectTo starts with '/' and only contains allowed paths
+    const validatedPath = redirectTo && /^\/(?:search|snippet\/[\w-]+|onboarding)(?:\?.*)?$/.test(redirectTo)
+      ? redirectTo
+      : import.meta.env.VITE_AUTH_REDIRECT_URL
+    const redirectUrl = `${window.location.origin}${validatedPath}`
     const { error } = await supabase.auth.signInWithOAuth({
🧰 Tools
🪛 eslint

[error] 81-81: Unnecessary use of conditional expression for default assignment.

(no-unneeded-ternary)

@giahung68 giahung68 merged commit 632c1a6 into main Dec 3, 2024
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