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

Re-login modal #717

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Re-login modal #717

wants to merge 2 commits into from

Conversation

chiragchhatrala
Copy link
Collaborator

@chiragchhatrala chiragchhatrala commented Mar 6, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a quick registration component that triggers post-login events, enhancing the account setup experience.
    • Added an enhanced authentication module supporting credential, social, and registration workflows with streamlined error feedback.
    • Updated OAuth callback and guest flows for smoother third-party authentication experiences.
  • Refactor

    • Simplified login and registration flows using async/await syntax for improved performance and error handling.
    • Centralized modal state management and refined event listeners for more responsive authentication interactions.

- Add QuickRegister component with improved modal management
- Integrate quick login/register with app store state
- Implement custom event handling for login/registration flow
- Update OAuth callback to support quick login in popup windows
- Refactor authentication-related components to use global events
- Create new useAuth composable to centralize login, registration, and social login logic
- Simplify authentication methods in LoginForm and RegisterForm
- Add event-based login/registration flow with quick login support
- Remove redundant API calls and consolidate authentication processes
- Improve error handling and analytics tracking for authentication events
@chiragchhatrala chiragchhatrala requested a review from JhumanJ March 6, 2025 10:23
Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

Walkthrough

This update refactors several authentication and registration components to streamline the login flow. The changes include adding global event handling via a new <QuickRegister /> component and updating methods to use async/await. State management has been centralized using a Pinia store with new modal properties. Additionally, error handling and OAuth callback logic have been simplified, and key composable functions have been introduced to consolidate authentication logic.

Changes

File(s) Change Summary
client/app.vue Added <QuickRegister /> component with event handling (handleAfterLogin) that emits a global 'after-quick-login' event.
client/components/pages/auth/components/LoginForm.vue
client/components/pages/auth/components/RegisterForm.vue
Refactored login/registration methods to use async/await; added lifecycle hooks for managing quick-login-complete event listeners; simplified API interactions.
client/components/pages/auth/components/QuickRegister.vue Migrated from Options API to Composition API; updated modal state and event handling to use centralized appStore; refactored method signatures.
client/composables/useAuth.js Introduced new composable function useAuth to encapsulate authentication functions such as loginWithCredentials, handleSocialCallback, and registerUser.
client/composables/useOpnApi.js Modified error handling in onResponseError to toggle quickLoginModal via the appStore instead of redirecting to the login page.
client/pages/forms/create/guest.vue Removed local modal state for registration; centralized modal control via appStore; added and cleaned up global after-quick-login event listener.
client/pages/oauth/callback.vue Refactored handleCallback into an async arrow function to simplify OAuth callback handling and control flow.
client/stores/app.js
client/stores/oauth_providers.js
Added new state properties quickLoginModal and quickRegisterModal to the appStore; modified guestConnect to open a new browser tab/window for OAuth rather than redirecting.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant QR as QuickRegister Component
    participant LF as LoginForm/RegisterForm
    participant GP as Guest Page
    participant PS as AppStore (Pinia)

    U->>QR: Initiate login action
    QR->>QR: Execute handleAfterLogin()
    QR->>window: Emit "after-quick-login" event
    window->>GP: Trigger afterLogin() via event listener
    GP->>PS: (Optional) Update central modal state
    LF->>PS: Manage lifecycle listeners (mounted/unmounted)
Loading
sequenceDiagram
    participant O as OAuth Provider
    participant CB as Callback Page
    participant AU as useAuth Composable
    participant U as User

    O->>CB: Redirect with OAuth code & UTM data
    CB->>AU: Call handleSocialCallback(provider, code, UTM)
    AU-->>CB: Return authentication result
    alt New User
        CB->>U: Redirect to form creation page, display success alert
    else Existing User
        CB->>window: Dispatch event to opener window
        CB->>window: Close callback window
    end
Loading

Suggested reviewers

  • JhumanJ

Poem

I’m a rabbit with a coding beat,
Hopping through logic, light and sweet.
Quick login and modals now align,
Async flows and events so fine.
In each change I find cheer,
Leaping happily, year to year!
🐇💻

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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: 3

🧹 Nitpick comments (3)
client/composables/useAuth.js (1)

31-38: Consider more robust error handling for analytics tracking.

The try-catch block for GTM tracking is good, but the error is only logged to the console. Consider adding more comprehensive error handling or fallback strategies for analytics failures.

try {
  useGtm().trackEvent({
    event: eventName,
    source
  })
} catch (error) {
  console.error(error)
+ // Consider adding a fallback analytics method or retry logic
}
client/pages/oauth/callback.vue (1)

53-59: Add fallback for window closing behavior.

The code currently attempts to close the window unconditionally after dispatching the event. This may not work in all browsers if the window wasn't opened via JavaScript. Consider adding a fallback.

if (!isNewUser) {
  // Handle existing user login
  if (window.opener) {
    window.opener.document.dispatchEvent(new CustomEvent('quick-login-complete'))
+   window.close()
+  } else {
+    // Fallback if window.opener is not available
+    router.push({ name: "home" })
  }
- window.close()
}
client/pages/forms/create/guest.vue (1)

96-104: Consider removing the setTimeout for form saving.

Using setTimeout for operations after login could be fragile. Consider using a more robust approach like watching for state changes or implementing a callback pattern.

const afterLogin = () => {
  isGuest.value = false
  fetchAllWorkspaces()
- setTimeout(() => {
+ // Wait for workspace loading to complete before saving
+ watch(() => workspacesStore.loading, (loading) => {
+   if (!loading && editor.value) {
+     editor.value.saveFormCreate()
+   }
+ }, { immediate: true })
- if (editor) {
-   editor.value.saveFormCreate()
- }
- }, 500)
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8894880 and adf2303.

📒 Files selected for processing (10)
  • client/app.vue (2 hunks)
  • client/components/pages/auth/components/LoginForm.vue (1 hunks)
  • client/components/pages/auth/components/QuickRegister.vue (3 hunks)
  • client/components/pages/auth/components/RegisterForm.vue (3 hunks)
  • client/composables/useAuth.js (1 hunks)
  • client/composables/useOpnApi.js (1 hunks)
  • client/pages/forms/create/guest.vue (2 hunks)
  • client/pages/oauth/callback.vue (1 hunks)
  • client/stores/app.js (1 hunks)
  • client/stores/oauth_providers.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build the Nuxt app
🔇 Additional comments (22)
client/stores/app.js (1)

12-13: Good addition of modal state properties.

Adding quickLoginModal and quickRegisterModal state properties to the Pinia store centralizes the modal visibility management, which aligns with the PR objective of streamlining the login flow.

client/stores/oauth_providers.js (1)

79-79: Improved user experience by opening OAuth in a new tab.

Changing from window.location.href to window.open(data.url, '_blank') keeps users on the current page while authentication happens in a new tab, preventing disruption to the user's current context.

client/composables/useOpnApi.js (1)

66-66: Enhanced UX by showing login modal instead of redirecting.

Replacing the redirect to login page with a modal dialog (useAppStore().quickLoginModal = true) when encountering a 401 error creates a smoother user experience, allowing users to re-authenticate without losing their current context.

client/app.vue (3)

53-53: Good implementation of the QuickRegister component.

Adding the <QuickRegister> component with the @after-login event handler creates a global registration mechanism that's accessible throughout the application.


108-112: Well-implemented global event propagation.

The handleAfterLogin method effectively creates a global event system for login events, allowing any component to listen for successful authentication without tight coupling.


117-117: Properly exposed the handler in the template.

Exposing the handleAfterLogin method in the return object ensures it's accessible from the template.

client/composables/useAuth.js (2)

1-108: Well-structured authentication composable with comprehensive functionality.

This new useAuth composable effectively centralizes authentication logic into a reusable module with clear separation of concerns. The code is well-structured with async/await patterns and proper error handling for the authentication flow.

A few observations:

  • The authenticateUser function handles both the authentication process and analytics tracking
  • Social login callbacks are properly managed with the isNewUser flag
  • AppSumo license validation is handled within the registration flow

74-101:

❓ Verification inconclusive

Verify login credential persistence after registration.

The registration flow submits the form twice - once for registration and once for login. This could potentially lead to issues if the server has validation rules that differ between the two endpoints.


🏁 Script executed:

#!/bin/bash
# Find all places where the login and registration endpoints are used
echo "Checking login and registration API usage:"
rg -A 3 "post.*'/login'" --glob "*.{js,vue}"
rg -A 3 "post.*'/register'" --glob "*.{js,vue}"

# Check for different validation rules between login and register
echo "Checking for validation differences:"
rg -A 5 "validate|validation" --glob "app/Http/Requests/*Request.php"

Length of output: 1241


Attention: Manual Verification of Endpoint Validation Required

The current authentication flow uses two form submissions—one for registration (/register) and one for login (/login). While our search confirmed the expected API calls in client/composables/useAuth.js, the automated query for validation logic differences (using the glob pattern for app/Http/Requests/*Request.php) did not return any files. This lack of output may be due to filtering issues rather than a definitive absence of discrepancies.

Action Points:

  • Verify Login Credential Persistence: Ensure that the token returned from the /login call is correctly persisted and that the user session remains authenticated.
  • Manual Validation Check: Manually review the server-side validation rules for both /register and /login endpoints to confirm they maintain consistent expectations regarding login credentials and handle validation similarly.

Please confirm these aspects so that we can be confident that the dual submission process does not introduce any edge-case issues.

client/pages/oauth/callback.vue (1)

42-68: Improved OAuth callback handling with the new auth composable.

The refactored callback handling is more concise and maintainable. Using the auth composable centralizes the authentication logic while properly handling different user scenarios.

client/pages/forms/create/guest.vue (2)

14-14: Improved state management with centralized modal control.

Using the app store for modal state management is a good improvement over local component state, providing better consistency across the application.


87-94: 🛠️ Refactor suggestion

Fix event listener reference for proper cleanup.

The event listener setup and cleanup should use the same function reference to ensure proper removal.

onMounted(() => {
  // Add event listener for after quick login
- window.addEventListener('after-quick-login', afterLogin)
+ window.addEventListener('after-quick-login', afterLogin)
})

onUnmounted(() => {
  // Clean up the event listener
- window.removeEventListener('after-quick-login', afterLogin)
+ window.removeEventListener('after-quick-login', afterLogin)
})

The current implementation looks correct, but I wanted to emphasize the importance of using the same function reference when adding and removing event listeners.

Likely an incorrect or invalid review comment.

client/components/pages/auth/components/LoginForm.vue (2)

149-163: Cleaner login implementation with async/await.

The refactored login method using async/await and the auth composable is more readable and maintainable.


157-159:

❓ Verification inconclusive

Verify self-host mode error handling.

The specific error message check for self-host mode seems unusual. Verify that this is the intended behavior and consider adding a comment explaining why this error is handled differently.


🏁 Script executed:

#!/bin/bash
# Look for other instances of this error message and how it's handled
echo "Checking for self-host mode error handling:"
rg "You must change your credentials when in self host mode" --glob "*.{js,vue,php}"

# Check related authentication logic for self-host mode
echo "Checking for self-host related code:"
rg "self.?host" --glob "app/Http/Controllers/Auth*.php"

Length of output: 634


Attention: Clarify Self-Host Error Handling

  • In client/components/pages/auth/components/LoginForm.vue (lines 157–159), the error message "You must change your credentials when in self host mode" is uniquely checked in this component.
  • Our search confirmed that this message only appears here, and no additional self-host handling logic was located in the expected backend files.
  • Please verify that using this specific error message to trigger a redirect is the intended behavior for self-host mode.
  • Consider adding a comment in the code to explain why errors in self-host mode are handled differently, especially since there’s no similar logic elsewhere.
client/components/pages/auth/components/QuickRegister.vue (5)

5-7: Good refactoring to centralized state management!

Using the appStore to manage the login modal state improves maintainability by centralizing state management rather than using local component state.


39-41: Consistent use of centralized state management

The register modal now follows the same pattern as the login modal, using appStore for state management.


73-78: Well-implemented Composition API conversion

Good transition from Options API to Composition API using <script setup>. The proper defineEmits usage ensures type safety for event handling.


80-90: Proper event listener cleanup

Excellent implementation of lifecycle hooks to add and remove event listeners. This prevents memory leaks by ensuring event listeners are properly cleaned up when the component is unmounted.


92-109: Clean method implementations

The refactored methods are well-implemented with clear responsibilities:

  • openLogin and openRegister toggle the appropriate modals
  • afterQuickLogin handles post-login behavior with proper timing

The use of emits for communication with parent components follows Vue best practices.

client/components/pages/auth/components/RegisterForm.vue (4)

77-94: Improved terms and conditions formatting

The terms and conditions section has been nicely reformatted for better readability and structure, while maintaining the same content.


209-211: Event listener for quick login added

Good addition of the event listener for the 'quick-login-complete' event, ensuring this component reacts appropriately when a quick login occurs elsewhere in the application.


237-253: Simplified registration logic

The register method has been nicely refactored to use the useAuth composable, which encapsulates authentication logic. This improves code maintainability and follows the principle of separation of concerns.

The error handling is now more streamlined with useAlert().


254-266: Good extraction of redirect logic

Extracting the navigation logic into a separate method improves code organization and reusability, especially since it's now used in both the register method and the event listener.

Comment on lines +137 to +146
mounted() {
document.addEventListener('quick-login-complete', () => {
this.redirect()
})
},
unmounted() {
document.removeEventListener('quick-login-complete', () => {
this.redirect()
})
},
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

Fix event listener removal implementation.

The current event listener removal doesn't work properly because it uses an inline function that won't match the original listener. Use a named function or store the handler in a variable.

+ data: () => ({
+   form: useForm({
+     email: "",
+     password: "",
+   }),
+   loading: false,
+   remember: false,
+   showForgotModal: false,
+   handleQuickLoginComplete: null,
+ }),

  mounted() {
+   this.handleQuickLoginComplete = () => {
+     this.redirect()
+   }
-   document.addEventListener('quick-login-complete', () => {
-     this.redirect()
-   })
+   document.addEventListener('quick-login-complete', this.handleQuickLoginComplete)
  },
  unmounted() {
-   document.removeEventListener('quick-login-complete', () => {
-     this.redirect()
-   })
+   document.removeEventListener('quick-login-complete', this.handleQuickLoginComplete)
  },
📝 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
mounted() {
document.addEventListener('quick-login-complete', () => {
this.redirect()
})
},
unmounted() {
document.removeEventListener('quick-login-complete', () => {
this.redirect()
})
},
export default {
// ... other component options
+ data: () => ({
+ form: useForm({
+ email: "",
+ password: "",
+ }),
+ loading: false,
+ remember: false,
+ showForgotModal: false,
+ handleQuickLoginComplete: null,
+ }),
mounted() {
+ this.handleQuickLoginComplete = () => {
+ this.redirect()
+ }
- document.addEventListener('quick-login-complete', () => {
- this.redirect()
- })
+ document.addEventListener('quick-login-complete', this.handleQuickLoginComplete)
},
unmounted() {
- document.removeEventListener('quick-login-complete', () => {
- this.redirect()
- })
+ document.removeEventListener('quick-login-complete', this.handleQuickLoginComplete)
},
// ... other component options
}

Comment on lines +86 to +90
onUnmounted(() => {
document.removeEventListener('quick-login-complete', () => {
afterQuickLogin()
})
})
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

Event listener callback mismatch

The callback function for removeEventListener should reference the same function instance as addEventListener, but you're creating a new anonymous function each time.

-onUnmounted(() => {
-  document.removeEventListener('quick-login-complete', () => {
-    afterQuickLogin()
-  })
-})
+onUnmounted(() => {
+  document.removeEventListener('quick-login-complete', afterQuickLogin)
+})

Similarly, update the addEventListener call:

-onMounted(() => {
-  document.addEventListener('quick-login-complete', () => {
-    afterQuickLogin()
-  })
-})
+onMounted(() => {
+  document.addEventListener('quick-login-complete', afterQuickLogin)
+})
📝 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
onUnmounted(() => {
document.removeEventListener('quick-login-complete', () => {
afterQuickLogin()
})
})
onMounted(() => {
document.addEventListener('quick-login-complete', afterQuickLogin)
})
onUnmounted(() => {
document.removeEventListener('quick-login-complete', afterQuickLogin)
})

Comment on lines +230 to +234
unmounted() {
document.removeEventListener('quick-login-complete', () => {
this.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

Event listener cleanup issue

The event listener removal has the same issue as in QuickRegister.vue. You're creating a new anonymous function instead of referencing the same function that was added.

-unmounted() {
-  document.removeEventListener('quick-login-complete', () => {
-    this.redirect()
-  })
-},
+unmounted() {
+  document.removeEventListener('quick-login-complete', this.redirect)
+},

Similarly, update the addEventListener call:

-mounted() {
-  document.addEventListener('quick-login-complete', () => {
-    this.redirect()
-  })
+mounted() {
+  document.addEventListener('quick-login-complete', this.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
unmounted() {
document.removeEventListener('quick-login-complete', () => {
this.redirect()
})
},
mounted() {
document.addEventListener('quick-login-complete', this.redirect)
},
unmounted() {
document.removeEventListener('quick-login-complete', this.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