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 4 commits into
base: main
Choose a base branch
from
Open

Re-login modal #717

wants to merge 4 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 a "Remember Me" feature to the login process for improved session persistence.
    • 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 Updated authentication functions to handle token data as an object; modified methods to accommodate new parameters for session persistence.
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.
api/.env.example
api/config/jwt.php
Updated JWT settings to extend token validity periods and introduced a new configuration for "remember me" tokens.
api/app/Http/Controllers/Auth/LoginController.php Enhanced attemptLogin method to set custom TTL for tokens based on "remember me" option.
client/stores/auth.js Updated setToken and setCookie methods to handle expiration settings; ensured proper cleanup of tokens during logout and impersonation stop actions.

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!
🐇💻


📜 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 adf2303 and 18f72d3.

📒 Files selected for processing (16)
  • client/pages/oauth/callback.vue (1 hunks)
  • client/components/pages/auth/components/LoginForm.vue (1 hunks)
  • client/components/pages/auth/components/RegisterForm.vue (3 hunks)
  • client/composables/useAuth.js (1 hunks)
  • client/pages/oauth/callback.vue (1 hunks)
  • api/.env.example (1 hunks)
  • api/app/Console/Commands/Tax/GenerateTaxExport.php (5 hunks)
  • api/app/Http/Controllers/Admin/ImpersonationController.php (1 hunks)
  • api/app/Http/Controllers/Auth/LoginController.php (1 hunks)
  • api/app/Notifications/Forms/FormEmailNotification.php (1 hunks)
  • api/config/jwt.php (1 hunks)
  • client/components/pages/admin/ImpersonateUser.vue (1 hunks)
  • client/components/pages/auth/components/LoginForm.vue (1 hunks)
  • client/composables/useAuth.js (4 hunks)
  • client/middleware/01.check-auth.global.js (1 hunks)
  • client/stores/auth.js (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • client/composables/useAuth.js
  • client/components/pages/auth/components/LoginForm.vue
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build the Nuxt app
🔇 Additional comments (21)
api/app/Notifications/Forms/FormEmailNotification.php (1)

164-182: Improved email threading implementation

The changes to the message ID generation and threading logic are well-implemented. By removing timestamps and using consistent hashed submission IDs, email clients will now properly thread conversations by submission rather than creating separate threads for each notification. This is a valuable improvement for users who interact with form submissions via email.

client/middleware/01.check-auth.global.js (1)

5-11: Improved code readability and structure

The refactoring of token retrieval and store initialization improves code readability by:

  1. Breaking down the operation into clear, logical steps
  2. Adding explanatory comments
  3. Using named variables that make the code's intent more explicit

This change maintains the same functionality while making the code more maintainable.

api/.env.example (1)

58-59: Session duration extensions look good

The JWT token lifetime extensions (7 days default, 30 days for "remember me") improve user experience by requiring less frequent logins. These durations are reasonable for a modern web application.

Verify that these extended token lifetimes align with your application's security requirements and user expectations.

api/app/Http/Controllers/Admin/ImpersonationController.php (1)

44-45: Enhanced token response with standard fields

Adding token_type and expires_in fields to the response improves API consistency by following OAuth 2.0 conventions. The client can now use the expiration time to properly manage token refreshing and session state.

client/components/pages/admin/ImpersonateUser.vue (1)

30-31: Improved token handling with expiration time.

The change correctly updates the token storage to include the expiration time instead of a static boolean value. This improvement aligns with backend changes and provides better token lifecycle management.

api/app/Http/Controllers/Auth/LoginController.php (1)

33-41: Excellent implementation of the "Remember me" feature.

The implementation correctly sets a custom token TTL based on the remember flag from the request. This allows for longer-lived sessions when users check the "Remember me" option, improving user experience for frequent visitors.

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

154-154: Properly passing the remember flag to the authentication service.

The login method now correctly passes the remember flag to the authentication service, allowing for longer sessions when requested by the user.


137-146: ⚠️ 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)
 },
api/config/jwt.php (2)

104-104: Updated default token lifetime to 7 days.

The default JWT TTL has been increased from 1 hour to 7 days. This is a significant change that improves user experience by reducing login frequency but should be balanced with security considerations.


106-116: Added extended token lifetime for "Remember me" functionality.

The new configuration properly implements a longer TTL (30 days) for remembered sessions. This allows for persistent logins while maintaining the security capability to revoke tokens if needed.

client/stores/auth.js (3)

24-28: Verify the fallback expiration logic when stopping impersonation.

Using a default 24-hour expiration for the admin token might inadvertently keep an admin token active if they close their browser. Consider a shorter duration or prompting the admin to confirm they want to continue with that token.


48-51: Handle SSR gracefully.

import.meta.client checks if the context is client-side. This is valid in Vite-based builds. Confirm server-side logic is not inadvertently triggered, or ensure an alternative approach on SSR (e.g., server cookies).


87-90: Confirm partial logout behavior when clearing the token.

The code only sets token to null by clearing the cookie, but does not remove admin_token. If both tokens co-exist, verify whether you also need to clear the admin token. If not, it may lead to unexpected impersonation states post-logout.

api/app/Console/Commands/Tax/GenerateTaxExport.php (3)

147-190: Handle partial refunds rather than fully refunded.

Currently, the code checks for $invoice->charge->refunded. However, partial refunds may keep refunded=false while adjusting the total. Ensure partial refund amounts do not get reported as net revenue.


297-340: Revisit defaulting to FR for tax.

Defaulting to France might lead to incorrect tax application if large numbers of invoices lack sufficient info. Consider logging a distinct warning each time this default is used, or building in a fallback approach to prompt manual data correction.


341-372: Verify currency conversions and partial taxes.

  • Ensure you properly account for currency rate differences if the invoice is processed in non-USD/EUR.
  • Confirm usage of $invoice->charge->balance_transaction->amount is always in the same currency.
client/pages/oauth/callback.vue (2)

42-68: Good refactoring of the callback handling!

The conversion to async/await and the simplified flow make this much more maintainable than before. The clear separation between new and existing user paths is also a nice improvement.


58-58: Verify that window.close() works reliably

Some browsers restrict window.close() to only work with windows that were opened programmatically via window.open(). Consider adding a fallback redirect if closing fails.

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

237-253: Good simplification of the registration logic

The use of the auth composable and cleaner error handling improves the code quality. This approach is more maintainable and follows better separation of concerns.


249-249: Verify redirect after error behavior

The redirect() method is called after both successful and failed registration attempts. Confirm that this is the intended behavior - typically you might only want to redirect after success.


254-266: Good implementation of the redirect logic

This method cleanly handles different registration scenarios (quick registration, invitations, and standard flows) with appropriate notifications and redirects.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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)
},

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 4

♻️ Duplicate comments (1)
client/components/pages/auth/components/RegisterForm.vue (1)

230-234: ⚠️ Potential issue

Function reference inconsistency in event listener cleanup

The event listener removal won't work because you're using a new anonymous function rather than referencing the same function that was added.

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

And update the addEventListener call:

-  mounted() {
-    document.addEventListener('quick-login-complete', () => {
-      this.redirect()
-    })
+  mounted() {
+    this.handleQuickLogin = () => this.redirect()
+    document.addEventListener('quick-login-complete', this.handleQuickLogin)
🧹 Nitpick comments (9)
client/composables/useAuth.js (4)

1-6: Consider adding error handling and default initial states for stores.

Although the store references appear valid, if useAuthStore, useWorkspacesStore, or useFormsStore throw an error or are uninitialized, the composable might fail silently. Adding a try/catch block or default object handling would help ensure robustness.


46-53: Allow passing a “remember me” or expiration parameter explicitly.

loginWithCredentials currently assumes a simple login scenario without specifying cookie expiration or long-lived tokens. If you intend to support “Remember Me” functionality, consider adding a parameter to this function, passing it into the call to authenticateUser or authStore.setToken.

const loginWithCredentials = async (form, remember = false) => {
  const { token } = await form.submit('post', '/login')
  return authenticateUser({
    token,
    source: 'credentials',
+   expiresIn: remember ? 60 * 60 * 24 * 7 : undefined // example 7 days
  })
}

58-69: Handle potential callback errors more gracefully.

When calling /oauth/{provider}/callback, if the server returns an error (e.g. invalid code), the current code may unhandledly throw. Consider catching these errors to provide a better user experience or fallback.


103-108: Ensure usage clarifies composable responsibilities.

Exposing loginWithCredentials, handleSocialCallback, and registerUser from useAuth is helpful. For maintainability, consider documenting these signature expectations (e.g., required form structure, error handling approach) so that other components know precisely how to consume them.

client/stores/auth.js (1)

62-63: Confirm logout logic for no-user scenario.

When setUser is called with null, the code forcibly sets the token to null with maxAge = 0. Ensure the rest of the code (like analytics or reliant services) gracefully handles a user no longer being present.

api/app/Console/Commands/Tax/GenerateTaxExport.php (3)

67-69: Offer concurrency or scheduling advice.

Although starting a timer is helpful, consider scheduling or chunked parallel execution if invoice volumes grow large. This could reduce runtime and memory usage.


192-207: Validate potential rate-limit exposures.

Though Stripe’s API can handle the request rate, consider a retry logic pattern for improved resiliency if Stripe temporarily throttles or encounters network hiccups. Relying on a single catch might omit certain transient errors.


220-246: Improve final output for clarity.

The displayed counters are useful. Consider adding:

  • A ratio of processed vs. total.
  • A separate line item for partial refunds (if tracked).
  • Potential generation of a summary CSV or JSON.
client/pages/oauth/callback.vue (1)

64-66: Consider adding fallback error handling

The current error handling assumes error.response._data.message will always be available. If the error structure is different (network error, unexpected response format), this might throw another exception.

-    useAlert().error(error.response._data.message)
+    const errorMessage = error.response?._data?.message || 'An error occurred during authentication'
+    useAlert().error(errorMessage)
🛑 Comments failed to post (4)
client/composables/useAuth.js (2)

7-41: 🛠️ Refactor suggestion

Wrap parallel data fetching with error handling.

In authenticateUser, the code simultaneously fetches user data and workspaces with Promise.all. If either request fails, the function may throw unhandled errors. Consider:

  1. Wrapping the concurrent calls in a try/catch to manage partial failures or offline scenarios.
  2. Providing user feedback or fallback states (e.g., redirect to login if fetching user data fails).
 const authenticateUser = async ({ token, source, isNewUser = false }) => {
+  try {
     authStore.setToken(token)
     const [userData, workspaces] = await Promise.all([
       opnFetch("user"),
       fetchAllWorkspaces()
     ])
     ...
+  } catch (error) {
+    console.error("Failed to authenticate user:", error)
+    // Possibly redirect or reset the state
+    throw error
+  }
 }

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


74-101: 🛠️ Refactor suggestion

Validate registration response and potential partial failures.

After registration and login, the code assumes both requests succeed. Network or server errors in either step may leave the user in an inconsistent state. It might be beneficial to short-circuit if the initial /register call fails.

const registerUser = async (form) => {
  try {
    const data = await form.submit('post', '/register')
    const { token } = await form.submit('post', '/login')
    ...
  } catch (error) {
    useAlert().error("Failed to complete registration or login. " + error.message)
    throw error
  }
  ...
}

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

client/stores/auth.js (1)

30-41: 🛠️ Refactor suggestion

Review cookie security settings.

setToken(token, expiresIn) sets no additional cookie flags like secure or sameSite. This can be a security risk if the site is accessed over HTTP or from multiple subdomains. Consider setting secure cookie options if your environment strictly uses HTTPS.

 setToken(token, expiresIn) {
   const cookieOptions = {}
   if (expiresIn) {
     cookieOptions.maxAge = expiresIn
   }
+  cookieOptions.secure = true
+  cookieOptions.sameSite = 'strict'
   this.setCookie("token", token, cookieOptions)
   this.token = token
 }
📝 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.

    setToken(token, expiresIn) {
      // Set cookie with expiration if provided
      const cookieOptions = {}
      
      if (expiresIn) {
        // expiresIn is in seconds, maxAge also needs to be in seconds
        cookieOptions.maxAge = expiresIn
      }
      cookieOptions.secure = true
      cookieOptions.sameSite = 'strict'
      
      this.setCookie("token", token, cookieOptions)
      this.token = token
    },
api/app/Console/Commands/Tax/GenerateTaxExport.php (1)

125-146: 🛠️ Refactor suggestion

Consider memory usage when accumulating invoices.

Storing all invoices in $processedInvoices can be memory-intensive if there are thousands of invoices. Consider streaming the results to a file or database incrementally instead of storing them all in an array.

Copy link
Owner

@JhumanJ JhumanJ left a comment

Choose a reason for hiding this comment

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

Modal should not be closable, there should be a logout button which closes it and redirect to login page

JhumanJ

This comment was marked as duplicate.

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