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

Server log out after delete #306

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

Conversation

elie222
Copy link
Owner

@elie222 elie222 commented Jan 12, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added ability to cancel batch loading operations
    • Dynamic user count display on welcome upgrade page
  • Bug Fixes

    • Improved error handling for account deletion process
    • Graceful handling of missing user authentication in webhook section
  • Chores

    • Removed debug console logging from authentication page
    • Streamlined sign-out process after account deletion
  • Performance

    • Enhanced user experience with more robust error notifications

Copy link

vercel bot commented Jan 12, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
inbox-zero ✅ Ready (Inspect) Visit Preview Jan 12, 2025 10:55am

Copy link
Contributor

coderabbitai bot commented Jan 12, 2025

Walkthrough

This pull request introduces several modifications across different components of the web application. The changes primarily focus on enhancing error handling, user experience, and configuration management. Key updates include adding a cancellable batch loading mechanism in the StatLoaderProvider, improving account deletion flow with better toast notifications, dynamically sourcing user count, and streamlining authentication-related processes. The modifications aim to make the application more robust and flexible while maintaining the existing core functionality.

Changes

File Change Summary
apps/web/app/(app)/settings/DeleteSection.tsx Updated account deletion process with improved error handling and toast notifications
apps/web/app/(app)/settings/WebhookSection.tsx Modified error handling to return null instead of throwing an error when userId is not present
apps/web/app/(landing)/login/page.tsx Removed console log for session user information
apps/web/app/(landing)/welcome-upgrade/page.tsx Replaced hardcoded user count with dynamic import from configuration
apps/web/app/api/auth/[...nextauth]/auth.ts Added signOut export to authentication module
apps/web/providers/StatLoaderProvider.tsx Introduced batch loading cancellation mechanism with onCancelLoadBatch method
apps/web/utils/actions/user.ts Added sign-out process after account deletion and minor error logging formatting

Sequence Diagram

sequenceDiagram
    participant User
    participant DeleteSection
    participant deleteAccountAction
    participant AuthModule
    
    User->>DeleteSection: Initiate Account Deletion
    DeleteSection->>deleteAccountAction: Call Deletion Action
    deleteAccountAction-->>DeleteSection: Return Result
    alt Deletion Successful
        DeleteSection->>AuthModule: Sign Out
        DeleteSection->>User: Show Success Toast
    else Deletion Failed
        DeleteSection->>User: Show Error Toast
    end
Loading

Possibly related PRs

Poem

🐰 A Rabbit's Deletion Dance 🗑️

With toast and promise, we delete with grace,
No errors shall halt our digital trace.
Webhooks whisper, user count gleams bright,
Our code now dances with newfound might!
Hop, hop, hurrah for clean and clear! 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

🧹 Nitpick comments (1)
apps/web/providers/StatLoaderProvider.tsx (1)

84-91: Consider adding a loading state reset

The batch loading cancellation is implemented correctly. However, consider resetting the isLoading state when cancellation occurs to ensure UI consistency.

 const onLoadBatch = useCallback(
   async (options: { loadBefore: boolean; showToast: boolean }) => {
     const batchSize = 50;
     for (let i = 0; i < batchSize; i++) {
-      if (stopLoading) break;
+      if (stopLoading) {
+        setIsLoading(false);
+        break;
+      }
       console.log("Loading batch", i);
       await onLoad({
         ...options,
         showToast: options.showToast && i === batchSize - 1,
       });
     }
     setStopLoading(false);
   },
   [onLoad, stopLoading],
 );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d976f30 and ec0d144.

📒 Files selected for processing (7)
  • apps/web/app/(app)/settings/DeleteSection.tsx (2 hunks)
  • apps/web/app/(app)/settings/WebhookSection.tsx (1 hunks)
  • apps/web/app/(landing)/login/page.tsx (0 hunks)
  • apps/web/app/(landing)/welcome-upgrade/page.tsx (2 hunks)
  • apps/web/app/api/auth/[...nextauth]/auth.ts (1 hunks)
  • apps/web/providers/StatLoaderProvider.tsx (3 hunks)
  • apps/web/utils/actions/user.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/app/(landing)/login/page.tsx
🔇 Additional comments (10)
apps/web/app/api/auth/[...nextauth]/auth.ts (1)

12-12: LGTM! Export of signOut function aligns with PR objective.

The addition of the signOut export enables proper user session cleanup after account deletion.

apps/web/app/(app)/settings/WebhookSection.tsx (1)

11-11: LGTM! Improved error handling for unauthenticated state.

Gracefully returning null instead of throwing an error is a better approach, especially for handling post-deletion states where the user session may be invalid.

apps/web/app/(landing)/welcome-upgrade/page.tsx (1)

7-7: Verify the relationship with PR objective.

While the change to use a dynamic userCount from config improves maintainability, it seems unrelated to the PR's objective of implementing server logout after account deletion. Consider splitting this change into a separate PR for better change tracking.

Also applies to: 22-22

apps/web/app/(app)/settings/DeleteSection.tsx (1)

11-12: LGTM! Added necessary imports and hooks.

The addition of isActionError and useStatLoader provides proper error handling and stat loading management capabilities.

Also applies to: 15-15

apps/web/providers/StatLoaderProvider.tsx (4)

26-26: LGTM: Context type and default value updates

The new onCancelLoadBatch method is properly typed and initialized with a no-op function as the default value.

Also applies to: 33-33


69-69: LGTM: State management for cancellation

The stopLoading state is correctly initialized as a boolean flag.


96-98: LGTM: Cancel handler implementation

The cancel handler is correctly implemented with proper dependency management using useCallback.


101-103: LGTM: Context provider value update

The provider value is correctly updated to include the new onCancelLoadBatch method.

apps/web/utils/actions/user.ts (2)

6-6: LGTM: Import addition

The signOut function is correctly imported alongside the existing auth import.


69-69: LGTM: Error logging improvement

The error logging format is improved for better readability.

Comment on lines +51 to +63
toast.promise(
async () => {
onCancelLoadBatch();
const result = await deleteAccountAction();
await logOut("/");
if (isActionError(result)) throw new Error(result.error);
},
{
loading: "Deleting account...",
success: "Account deleted!",
error: (err) => `Error deleting account: ${err.message}`,
},
);
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

Consider potential race conditions in the deletion flow.

The current implementation has a good flow with proper user feedback through toasts. However, there's a potential race condition between account deletion and logout. If the deletion succeeds but logout fails, the user might be left in an inconsistent state.

Consider wrapping both operations in a single try-catch:

 toast.promise(
   async () => {
     onCancelLoadBatch();
-    const result = await deleteAccountAction();
-    await logOut("/");
-    if (isActionError(result)) throw new Error(result.error);
+    try {
+      const result = await deleteAccountAction();
+      if (isActionError(result)) throw new Error(result.error);
+      await logOut("/");
+    } catch (error) {
+      // If deletion succeeded but logout failed, we should still consider it a success
+      // as the account is deleted and the user can manually logout
+      if (error.message.includes("deletion successful")) {
+        console.error("Account deleted but logout failed:", error);
+        return;
+      }
+      throw error;
+    }
   },
   {
     loading: "Deleting account...",
     success: "Account deleted!",
     error: (err) => `Error deleting account: ${err.message}`,
   },
 );

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

Comment on lines +73 to +76
try {
await signOut();
} catch (error) {}

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

Critical: Reorder signOut after user deletion

The current implementation calls signOut() before deleting the user from the database. This could lead to an inconsistent state if the database deletion fails. Consider moving the signOut call after the successful user deletion.

Also, the empty catch block should at least log the error to help with debugging.

-    try {
-      await signOut();
-    } catch (error) {}
-
     await prisma.user.delete({ where: { email: session.user.email } });
+
+    try {
+      await signOut();
+    } catch (error) {
+      console.error("Error during sign out after account deletion:", error);
+      // Don't rethrow as the account is already deleted
+    }

Also applies to: 78-78

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