8000 fix: Base invite email related issues by pranavxc · Pull Request #9907 · nocodb/nocodb · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix: Base invite email related issues #9907

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

Merged
merged 2 commits into from
Nov 28, 2024
Merged

Conversation

pranavxc
Copy link
Member

Change Summary

Change type

  • feat: (new feature for the user, not a new feature for build script)
  • fix: (bug fix for the user, not a fix to a build script)
  • docs: (changes to the documentation)
  • style: (formatting, missing semi colons, etc; no production code change)
  • refactor: (refactoring production code, eg. renaming a variable)
  • test: (adding missing tests, refactoring tests; no production code change)
  • chore: (updating grunt tasks etc; no production code change)

Test/ Verification

Provide summary of changes.

Additional information / screenshots (optional)

Anything for maintainers to be made aware of

@dosubot dosubot bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Nov 28, 2024
Copy link
Contributor
coderabbitai bot commented Nov 28, 2024
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications to the BaseUsersService class within the base-users.service.ts file. A new Logger instance is introduced for enhanced logging, and the sendInviteEmail method's signature is updated to accept a parameter object. The email sending logic is refined to include email configuration checks and improved error handling using the logger. The overall control flow remains unchanged, but the email handling process is optimized, particularly regarding error reporting and the management of the baseName parameter.

Changes

File Path Change Summary
packages/nocodb/src/services/base-users/... - Introduced Logger instance for improved logging.
- Updated sendInviteEmail method signature to accept an object with multiple parameters.
- Enhanced email sending logic with email configuration checks.
- Improved error handling using the logger, logging both message and stack trace.
- Adjusted handling of baseName and streamlined email count checks.
packages/nocodb/src/services/base-users/ui/... - Updated email template in invite.ts to include dynamic baseName and roles.
packages/nocodb/src/services/base-users/ui/... - Added new email template org-invite.ts for organization invitations.
packages/nocodb/src/services/org-users.service.ts - Refactored userAdd and userInviteResend methods to pass parameters as objects.

Assessment against linked issues

Objective Addressed Explanation
Ensure invitation email is sent only once (#8460)

Possibly related PRs

  • fix: sanitise workspace/base name in invite email #8470: This PR sanitizes the baseName property in the BaseUsersService, which is directly related to the changes made in the sendInviteEmail method where the handling of baseName is adjusted.
  • fix: Email invitation bug #8505: This PR addresses a bug in the email invitation functionality, which is relevant to the modifications in the sendInviteEmail method that enhance error handling and logging for email sending.
  • fix: tweak invite and verify e-mail templates #8529: This PR updates the email templates for invitations, which connects to the overall functionality of sending invite emails in the BaseUsersService.
  • Nc fix/email template #9477: This PR includes updates to the email template syntax in invite.ts, which aligns with the changes made in the main PR regarding email content.
  • Nc fix/add to fav bug followup #9599: This follow-up PR continues to refine the user management logic in BaseUsersService, which is closely related to the modifications in the main PR.

Suggested labels

size:M, 👮 Scope : Auth, lgtm

Suggested reviewers

  • mertmit
  • dstala

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.

@dosubot dosubot bot added the 🐛 Type: Bug Something is broken or incorrect unexpectedly. label Nov 28, 2024
@pranavxc pranavxc force-pushed the fix/8460-duplicate-mail branch from 535a9c8 to 504d852 Compare November 28, 2024 02:48
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: 0

🧹 Outside diff range and nitpick comments (2)
packages/nocodb/src/services/base-users/base-users.service.ts (2)

438-448: Add JSDoc documentation for the sendInviteEmail method

While the new method signature with object parameters improves maintainability, adding JSDoc documentation would enhance code clarity and help other developers understand the purpose and usage of each parameter.

Example documentation:

/**
 * Sends an invitation email to a user
 * @param {Object} params - The parameters for sending the invite email
 * @param {string} params.email - The recipient's email address
 * @param {string} params.token - The invitation token
 * @param {NcRequest} params.req - The request object
 * @param {string} params.baseName - The name of the base
 * @returns {Promise<boolean>} Returns true if email was sent successfully
 * @throws {Error} If email configuration is invalid or sending fails
 */

464-464: Consider removing unnecessary fallback

Since baseName is now a required parameter in the method signature, the fallback to req.body?.baseName appears unnecessary and could be removed.

-            baseName: sanitiseEmailContent(baseName || req.body?.baseName),
+            baseName: sanitiseEmailContent(baseName),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ead832b and 504d852.

📒 Files selected for processing (1)
  • packages/nocodb/src/services/base-users/base-users.service.ts (7 hunks)
🔇 Additional comments (5)
packages/nocodb/src/services/base-users/base-users.service.ts (5)

29-29: LGTM: Good addition of structured logging

The addition of a Logger instance improves error tracking and debugging capabilities.


176-195: LGTM: Fixed duplicate email issue

The modified logic properly handles email sending status and differentiates between single and multiple user invites, addressing the duplicate email issue mentioned in #8460.


Line range hint 198-203: LGTM: Enhanced error handling

The error handling is improved with proper logging and differentiated handling for single vs multiple user scenarios.


477-480: LGTM: Comprehensive error logging

The enhanced error logging provides better visibility into email configuration issues and includes stack traces for debugging.


176-195: Verify the complete invite flow

While the changes look good, let's verify that there are no remaining scenarios where duplicate emails could be sent.

Also applies to: 438-480

✅ Verification successful

Based on the shell script results, I can now provide a final verification response:

Invite flow verification completed - No duplicate email concerns

The code changes have properly addressed the duplicate email scenario. Here's the verification summary:

  • The invite token generation is properly synchronized with email sending in both base-users.service.ts and org-users.service.ts
  • The email sending logic in base-users.service.ts has proper conditional handling:
    • For single email: Sends email and returns token only if sending fails
    • For multiple emails: Sends emails without returning tokens
  • No other parts of the codebase attempt to send duplicate invite emails for the same token
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for all email sending calls in the codebase to ensure no duplicate sends

# Look for email sending patterns
echo "Checking for email sending patterns..."
rg "mailSend|sendInviteEmail" -A 5

# Look for invite token generation to trace the invite flow
echo "Checking invite token generation..."
rg "invite_token.*=.*uuidv4\(\)" -A 10

Length of output: 16136

@pranavxc pranavxc marked this pull request as draft November 28, 2024 02:56
Copy link
Contributor
github-actions bot commented Nov 28, 2024

Uffizzi Preview deployment-58645 was deleted.

…late

Signed-off-by: Pranav C <pranavxc@gmail.com>
@pranavxc pranavxc force-pushed the fix/8460-duplicate-mail branch from 504d852 to efd1f7a Compare November 28, 2024 03:10
Signed-off-by: Pranav C <pranavxc@gmail.com>
@pranavxc pranavxc marked this pull request as ready for review November 28, 2024 03:55
@dosubot dosubot bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Nov 28, 2024
@pranavxc pranavxc changed the title fix: Base invite related issues fix: Base invite email related issues Nov 28, 2024
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: 0

🧹 Outside diff range and nitpick comments (4)
packages/nocodb/src/services/org-users.service.ts (1)

164-182: LGTM! The email sending logic effectively prevents duplicate invites.

The implementation correctly handles both single and batch invites with appropriate error handling. The email is sent exactly once per user, addressing the duplicate email issue mentioned in #8460.

Consider enhancing the error logging for the batch invite case:

 } catch (e) {
-  console.log(e);
+  console.error('Failed to invite user:', email, e);
   if (emails.length === 1) {
     throw e;
   } else {
packages/nocodb/src/services/base-users/base-users.service.ts (3)

179-185: Add email configuration check before attempting to send

Consider checking for email configuration before attempting to send the invite email to fail fast and provide better error messages.

+ const emailAdapter = await NcPluginMgrv2.emailAdapter();
+ if (!emailAdapter) {
+   return { invite_token, email };
+ }
  const mailSendStatus = await this.sendInviteEmail({
    email,
    token: invite_token,
    req: param.req,
    baseName: base.title,
    roles: param.baseUser.roles || 'editor',
  });

Line range hint 476-481: Update email subject to reflect invitation context

The current subject "Verify email" doesn't accurately reflect that this is an invitation email. Consider updating it to be more specific.

- subject: 'Verify email',
+ subject: `Invitation to ${sanitiseEmailContent(baseName || req.body?.baseName)}`,

494-497: Improve error handling specificity

The current error handling logs all errors the same way. Consider categorizing errors:

  1. Configuration errors (e.g., missing SMTP settings)
  2. Network errors
  3. Template rendering errors
  } catch (e) {
+   if (e.code === 'ECONNREFUSED') {
+     this.logger.error('Email server connection failed:', e.message);
+     throw new Error('Failed to connect to email server. Please check your SMTP settings.');
+   } else if (e instanceof Error && e.message.includes('Template')) {
+     this.logger.error('Template rendering failed:', e.message);
+     throw new Error('Failed to render email template. Please check template syntax.');
+   } else {
      this.logger.warn(
        'Warning : `mailSend` failed, Please re-configure emailClient configuration.',
      );
      this.logger.error(e.message, e.stack);
      throw e;
+   }
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 504d852 and a0857b4.

📒 Files selected for processing (4)
  • packages/nocodb/src/services/base-users/base-users.service.ts (8 hunks)
  • packages/nocodb/src/services/base-users/ui/emailTemplates/invite.ts (2 hunks)
  • packages/nocodb/src/services/base-users/ui/emailTemplates/org-invite.ts (1 hunks)
  • packages/nocodb/src/services/org-users.service.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/nocodb/src/services/base-users/ui/emailTemplates/org-invite.ts
🔇 Additional comments (7)
packages/nocodb/src/services/org-users.service.ts (1)

241-247: LGTM! The resend invitation logic is correct and consistent.

The implementation ensures a single email is sent with the updated token, and all necessary parameters (including roles) are properly passed.

packages/nocodb/src/services/base-users/ui/emailTemplates/invite.ts (2)

6-6: LGTM! Enhanced email personalization.

The changes improve the email's clarity by:

  • Using a personalized title with the base name
  • Adding a descriptive preheader that includes both role and base name

Also applies to: 104-104


6-6: ⚠️ Potential issue

Ensure proper HTML escaping for user-provided content.

The template uses user-provided content (baseName and roles) directly in HTML. Ensure these values are properly escaped to prevent XSS attacks.

Let's verify the escaping implementation:

Consider using EJS's built-in escape syntax <%- %> instead of <%= %> for these variables:

-    <title><%= baseName %> - Invite</title>
+    <title><%- baseName %> - Invite</title>
-      style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">You have been invited to become "<%= roles -%>" of the NocoDB base "<%= baseName %>".</span>
+      style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">You have been invited to become "<%- roles %>" of the NocoDB base "<%- baseName %>".</span>

Also applies to: 104-104

✅ Verification successful

Let me gather more information about the email template rendering and sanitization.


Let me check how EJS handles HTML escaping by default and if there are any configuration settings for it.


Let me check for the sanitiseEmailContent function since it appears to be used for sanitizing the content.


Let me check for the sanitiseEmailContent function implementation.


HTML content is properly escaped and sanitized.

The template variables are properly sanitized before being used in the HTML template:

  1. The baseName and roles values are passed through sanitiseEmailContent() which:

    • HTML encodes special characters using numeric character references (&#xxx;)
    • Wraps dots and URL separators in <span> tags to prevent URL injection
    • Handles <>&;?#,'"$ and other special characters
  2. The EJS template uses <%= which HTML escapes content by default

The implementation provides adequate protection against XSS attacks through proper sanitization and encoding of user-provided content.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if HTML escaping is implemented for EJS templates

# Look for EJS configuration or escaping utilities
rg -A 3 "configureEjs|escape|sanitize|xss" 

# Check if the BaseUsersService sanitizes these values
ast-grep --pattern 'class BaseUsersService {
  $$$
  sendInviteEmail($$$) {
    $$$
  }
  $$$
}'

Length of output: 155876


Script:

#!/bin/bash
# Check if there's any HTML escaping/sanitization in the email template rendering
rg -A 3 "renderEmailTemplate|compileTemplate|ejs\.render" 

# Look for any HTML escaping utilities
rg -A 3 "escape|sanitize|xss" packages/nocodb/src/services/base-users/ui/emailTemplates/

Length of output: 2760


Script:

#!/bin/bash
# Look for EJS configuration or initialization
rg -A 3 "ejs\.(configure|renderFile|compile)" 

# Check if there's any global EJS setup or middleware
rg -A 3 "app\.set.*ejs|app\.engine.*ejs"

# Look for any HTML escaping configuration in the base users service
ast-grep --pattern 'ejs.render($_, {
  $$$
})'

Length of output: 3418


Script:

#!/bin/bash
# Look for the sanitiseEmailContent function definition
rg -A 5 "sanitiseEmailContent|sanitizeEmailContent" 

# Also check for any email content sanitization utilities
ast-grep --pattern 'function sanitiseEmailContent($_) {
  $$$
}'

Length of output: 132838


Script:

#!/bin/bash
# Look for the sanitiseEmailContent function implementation
rg -A 5 "export const sanitiseEmailContent" packages/nocodb/src/utils/emailUtils.ts

# Also check for any encode function used in sanitiseEmailContent
rg -A 5 "encode" packages/nocodb/src/utils/emailUtils.ts

Length of output: 812

packages/nocodb/src/services/base-users/base-users.service.ts (4)

1-1: LGTM: Good addition of structured logging

The addition of NestJS Logger will help with better error tracking and debugging.

Also applies to: 29-29


176-189: LGTM: Fixed duplicate email issue

The logic now properly handles email sending status and returns the invite token only when email sending fails, addressing the duplicate email issue mentioned in #8460.


Line range hint 405-429: LGTM: Improved error handling in invite resend

Good improvements:

  1. Added proper retrieval of user roles
  2. Added email plugin configuration check before attempting to send

443-457: LGTM: Improved type safety with proper parameter typing

The refactoring improves code maintainability by using a properly typed parameter object instead of individual parameters.

@dosubot dosubot bot added the lgtm This PR has been approved by a maintainer label Nov 28, 2024
@pranavxc pranavxc merged commit eeb6795 into develop Nov 28, 2024
40 of 63 checks passed
@pranavxc pranavxc deleted the fix/8460-duplicate-mail branch November 28, 2024 05:00
@coderabbitai coderabbitai bot mentioned this pull request Dec 21, 2024
7 tasks
@coderabbitai coderabbitai bot mentioned this pull request Jan 8, 2025
7 tasks
This was referenced Jan 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files. 🐛 Type: Bug Something is broken or incorrect unexpectedly.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

🐛 Bug: Initial invitation e-mail is sent twice
2 participants
0