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

Add feat/ContactUs-form branch #381

Conversation

PriyanshuValiya
Copy link

@PriyanshuValiya PriyanshuValiya commented Oct 22, 2024

Page Preview..

Screenshot 2024-10-22 144942

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a contact form on the Contact Us page, allowing users to submit inquiries.
    • Added a new menu item "CONTACTUS" in the navigation bar.
  • Bug Fixes

    • Corrected the import path for error handling middleware to ensure proper functionality.
  • Documentation

    • Updated routing to include the new Contact Us page and removed the Help and Support page.
  • Chores

    • Added a new dependency for enhanced UI icons in the project.

Copy link

vercel bot commented Oct 22, 2024

@PriyanshuValiya is attempting to deploy a commit to the bunty's projects Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Warning

Rate limit exceeded

@PriyanshuValiya has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 24 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 1f8f7e3 and 6426ecd.

Walkthrough

The changes introduced in this pull request include the implementation of a contact form handling feature using the Zod library for validation and Nodemailer for email transmission. A new Express router for the /contactus endpoint has been created, which connects to the createContactUs function for processing submissions. Additionally, modifications were made to improve error handling in the router setup and to update the frontend with a new ContactUs component, enhancing user interaction and form submission capabilities.

Changes

File Change Summary
backend/controller/contact.controller.js Added createContactUs(req, res) method for handling contact form submissions with validation using Zod and email sending via Nodemailer.
backend/index.js Corrected import path for errorMiddleware to ensure proper middleware referencing.
backend/routes/contactUsRouter.js Introduced a new router for handling POST requests to /contactus, utilizing the createContactUs function.
backend/routes/index.js Implemented safeRequire function for improved error handling when loading routers, consolidated existing try-catch blocks, and added contactUsRouter.
frontend/package.json Added new dependency "lucide-react": "^0.453.0" to the project.
frontend/src/components/Pages/ContactUs.jsx Created a new React component for the contact form with client-side validation and API submission capabilities.
frontend/src/components/Shared/Navbar.jsx Added a new menu item "CONTACTUS" to the navigation options and updated the handleLogout function.
frontend/src/router/index.jsx Added route for the ContactUs component at /contactus and removed the route for HelpAndSupport.

Possibly related PRs

Suggested labels

enhancement, level2, gssoc-ext, hacktoberfest accepted

Suggested reviewers

  • RamakrushnaBiswal

🐰 In the meadow, a form does bloom,
With fields for your thoughts, dispelling the gloom.
A click on "SEND," your message takes flight,
Through wires and waves, it travels the night.
So hop on this change, let your voice be heard,
For every small whisper can change the world! 🌼


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

Thank you for submitting your pull request! 🙌 We'll review it as soon as possible. In the meantime, please ensure that your changes align with our CONTRIBUTING.md. If there are any specific instructions or feedback regarding your PR, we'll provide them here. Thanks again for your contribution! 😊

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

🧹 Outside diff range and nitpick comments (9)
backend/routes/contactUsRouter.js (2)

5-5: LGTM: Route definition is correct. Consider adding a comment.

The route definition is concise and follows Express.js conventions. To improve code readability and maintainability, consider adding a brief comment describing the purpose of this route.

Example:

// Handle POST requests for contact form submissions
router.post("/contactus", createContactUs);

1-7: Overall: Well-structured router file. Consider additional enhancements.

The contactUsRouter.js file is concise, focused, and follows Express.js best practices. It correctly sets up a route for handling contact form submissions. To further improve the file:

  1. Consider adding input validation middleware if not already handled in the controller.
  2. Implement error handling middleware for this specific route if needed.
  3. If there are any authentication or authorization requirements for this route, ensure they are applied.
backend/routes/index.js (3)

8-17: LGTM: Excellent error handling for module imports.

The safeRequire utility function is a great addition. It provides consistent error handling for module imports and uses the Winston logger effectively. The fallback function ensures graceful error responses.

Consider adding more context to the error log by including the fallbackMessage:

-    logger.error(`Error loading ${modulePath}:`, error);
+    logger.error(`Error loading ${modulePath} (${fallbackMessage}):`, error);

This will make it easier to identify which functionality is affected when reviewing logs.


20-22: LGTM: Consistent use of safeRequire for router imports.

The updates to router imports using safeRequire improve error handling and consistency across the application. The addition of the contact router is noted.

Consider grouping all router imports together for better readability. For example:

const routers = {
  feedback: safeRequire("./feedbackRouter", "Feedback functionality is currently unavailable"),
  contactUs: safeRequire("./contactUsRouter", "Contact Us functionality is currently unavailable"),
  event: safeRequire("./eventRouter", "Event functionality is currently unavailable"),
  admin: safeRequire("./adminRouter", "Admin functionality is currently unavailable"),
  user: safeRequire("./customerRouter", "User functionality is currently unavailable"),
  reservation: safeRequire("./reservationRouter", "Reservation functionality is currently unavailable"),
  newsletter: safeRequire("./newsletterRoute", "Newsletter functionality is currently unavailable"),
  forgot: safeRequire("./forgotRouter", "Forgot password functionality is currently unavailable")
};

Then use them like router.use("/admin", routers.admin);. This would make the code more maintainable and easier to read.

Also applies to: 37-37, 39-42


30-30: Consider updating the endpoints list for completeness.

While adding the Feedback endpoint to the root route response is good for API discoverability, the list is not comprehensive. It's missing several endpoints that are defined in the router.

Consider updating the endpoints object to include all available endpoints:

endpoints: {
  Reservation: "/reservation",
  Feedback: "/feedback",
  Event: "/event",
  Admin: "/admin",
  User: "/user",
  Newsletter: "/newsletter",
  ForgotPassword: "/forgot",
  Contact: "/contact"
},

This will provide a more accurate representation of your API's capabilities.

frontend/src/router/index.jsx (1)

43-43: LGTM: New route for ContactUs page.

The new route for the ContactUs page is correctly implemented and follows the existing pattern in the file.

For consistency with other routes, consider moving this route up to be grouped with other page routes (e.g., after the "/about" route).

frontend/src/components/Shared/Navbar.jsx (1)

22-22: LGTM! Consider adding an aria-label for accessibility.

The addition of the "CONTACTUS" menu item is consistent with the existing structure and aligns with the PR objectives.

For improved accessibility, consider adding an aria-label to the Link component when rendering this menu item. For example:

<Link
  to={item.path}
  className={`${baseTextColorClass} ${hoverTextColorClass}`}
  aria-label={item.name === 'CONTACTUS' ? 'Contact Us page' : item.name}
>
  {item.name}
</Link>
backend/controller/contact.controller.js (2)

5-5: Fix typos in the comment.

There are typos in the comment on line 5. It should read "Data required from .env file: EMAIL_USER, EMAIL_PASS."

Apply this diff to correct the comment:

-// data require form .env file : EMAIL_USER, EMAIL_PASS
+// Data required from .env file: EMAIL_USER, EMAIL_PASS

14-14: Remove the unused variable info.

The variable info declared on line 14 is not used anywhere in the code. Removing it will clean up the code.

Apply this diff to remove the unused variable:

-const info = { messageId: "23DCS141" };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 81cc864 and 56f7052.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (9)
  • backend/config/oauth.config.js (1 hunks)
  • backend/controller/contact.controller.js (1 hunks)
  • backend/index.js (1 hunks)
  • backend/routes/contactUsRouter.js (1 hunks)
  • backend/routes/index.js (1 hunks)
  • frontend/package.json (1 hunks)
  • frontend/src/components/Pages/ContactUs.jsx (1 hunks)
  • frontend/src/components/Shared/Navbar.jsx (1 hunks)
  • frontend/src/router/index.jsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • backend/config/oauth.config.js
🧰 Additional context used
🔇 Additional comments (10)
backend/routes/contactUsRouter.js (2)

1-3: LGTM: Imports and router setup are correct.

The import statements and router setup follow best practices. The comment confirming the correct controller path is helpful for maintainability.


7-7: LGTM: Router export is correct.

The router is properly exported using CommonJS syntax, which is appropriate for Node.js applications.

frontend/package.json (1)

27-27: LGTM! Verify usage of the new dependency.

The addition of the "lucide-react" dependency is appropriate and aligns with the changes mentioned in the PR summary. This library likely provides icons or UI components that will be used in the new ContactUs form.

To ensure this dependency is being utilized effectively, please run the following script to check its usage across the project:

This will help confirm that the new dependency is being used appropriately in the project, particularly in the new ContactUs component.

backend/index.js (1)

Line range hint 1-67: Acknowledge good practices in server setup

While reviewing the changes, I noticed several good practices in the existing code:

  1. Proper use of environment variables for configuration.
  2. CORS configuration with specific allowed origins.
  3. Consistent use of logging throughout the file.
  4. Inclusion of a health check endpoint.
  5. Correct placement of error handling middleware at the end of the middleware chain.

These practices contribute to a robust and maintainable server setup. Keep up the good work!

backend/routes/index.js (3)

2-2: LGTM: Good addition of structured logging.

The import of the Winston logger is a positive change. It introduces structured logging to the application, which will improve debugging and log management.


1-44: Overall assessment: Good improvements to error handling and routing.

The changes to this file enhance the application's robustness through improved error handling and the addition of new functionality. The safeRequire utility function is a particularly good addition, providing consistent error handling for module imports.

Key points:

  1. Improved error handling for module imports.
  2. Addition of structured logging with Winston.
  3. Consistent use of safeRequire for all router imports.
  4. Addition of new contact functionality.

The suggestions provided are minor and aimed at improving code organization, readability, and API documentation. Overall, these changes represent a significant improvement to the routing setup of the application.


43-43: LGTM: New contact functionality added.

The addition of the contact router is a good enhancement to the application's functionality.

To ensure this new functionality is properly implemented and documented, could you provide more information about the contactUsRouter? Specifically:

  1. What endpoints does it expose?
  2. What kind of data does it handle?
  3. Is there any documentation or API specs for this new functionality?

You can run the following command to inspect the contactUsRouter:

This will help ensure that the new functionality is properly integrated and follows the project's standards.

✅ Verification successful

Contact Functionality Verified

The contactUsRouter and createContactUs function are properly implemented and adhere to the project's standards.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Inspect the contactUsRouter implementation
cat backend/routes/contactUsRouter.js

Length of output: 280


Script:

#!/bin/bash
# Description: Inspect the createContactUs function in contact.controller.js
cat backend/controller/contact.controller.js

Length of output: 1948

frontend/src/router/index.jsx (2)

24-24: LGTM: Import statement for ContactUs component.

The import statement for the ContactUs component is correctly placed and follows the existing pattern in the file.


24-24: Verify the implementation of the ContactUs component.

The changes to add the ContactUs page to the routing structure are well-implemented and enhance the application's functionality. To ensure a smooth user experience, please verify that the ContactUs component is fully implemented and tested.

Run the following script to check the implementation of the ContactUs component:

Also applies to: 43-43

✅ Verification successful

---


ContactUs Component Implemented Correctly

The ContactUs component has been successfully located and verified. No TODO comments were found, indicating that the component's implementation is complete.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of the ContactUs component

# Test: Check if the ContactUs component file exists
fd -t f "ContactUs.jsx" src/components/Pages

# Test: Check the content of the ContactUs component
cat $(fd -t f "ContactUs.jsx" src/components/Pages)

# Test: Check for any TODO comments in the ContactUs component
rg "TODO" $(fd -t f "ContactUs.jsx" src/components/Pages)

Length of output: 476


Script:

#!/bin/bash
# Description: Locate the ContactUs.jsx component and verify its implementation

# Find the path to ContactUs.jsx
CONTACTUS_PATH=$(fd -t f "ContactUs.jsx")

# Check if the ContactUs.jsx file was found
if [ -z "$CONTACTUS_PATH" ]; then
  echo "ContactUs.jsx not found in the repository."
  exit 1
fi

# Display the path of ContactUs.jsx
echo "ContactUs.jsx found at: $CONTACTUS_PATH"

# Display the content of ContactUs.jsx
cat "$CONTACTUS_PATH"

# Check for any TODO comments in ContactUs.jsx
rg "TODO" "$CONTACTUS_PATH"

Length of output: 6326


Script:

#!/bin/bash
# Description: Locate the ContactUs.jsx component anywhere in the repository and verify its implementation

# Find the path to ContactUs.jsx
CONTACTUS_PATH=$(fd -t f "ContactUs.jsx")

# Check if the ContactUs.jsx file was found
if [ -z "$CONTACTUS_PATH" ]; then
  echo "ContactUs.jsx not found in the repository."
  exit 1
fi

# Display the path(s) of ContactUs.jsx
echo "ContactUs.jsx found at:"
echo "$CONTACTUS_PATH"

# Iterate through each found ContactUs.jsx file
while IFS= read -r file; do
  echo "----- Content of $file -----"
  cat "$file"
  echo "----- Checking for TODO comments in $file -----"
  rg "TODO" "$file"
done <<< "$CONTACTUS_PATH"

Length of output: 6701

frontend/src/components/Shared/Navbar.jsx (1)

Line range hint 1-238: Verify the setup of the ContactUs page and route.

The addition of the "CONTACTUS" menu item looks good. To ensure full functionality:

  1. Confirm that a corresponding route for "/contactus" has been added in the router configuration.
  2. Verify that a ContactUs component or page has been created and is correctly linked to this route.

Run the following script to check for the ContactUs route and component:

✅ Verification successful

Please verify the setup of the ContactUs route and component by running the following scripts:


Please verify that the /contactus route is correctly defined and renders the ContactUs component by running the following scripts:


Please verify that the /contactus route correctly renders the ContactUs component by running the following scripts:


Please verify that the /contactus route correctly renders the ContactUs component by running the following scripts:


ContactUs route and component are correctly set up.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the setup of ContactUs route and component

# Check for ContactUs route in the router configuration
echo "Checking for ContactUs route:"
rg -n "path: '/contactus'" src/

# Check for ContactUs component
echo "Checking for ContactUs component:"
fd -e jsx -e js ContactUs src/

Length of output: 355


Script:

#!/bin/bash
# Description: Verify the setup of ContactUs route and component across the entire repository

# Check for ContactUs route in the router configuration
echo "Checking for ContactUs route:"
rg -n "path: '/contactus'" .

# Check for ContactUs component
echo "Checking for ContactUs component:"
fd -e jsx -e js ContactUs .

Length of output: 350


Script:

#!/bin/bash
# Description: Verify that the /contactus route is defined and renders the ContactUs component

# Search for Route definitions with path '/contactus'
echo "Searching for Route definitions with path '/contactus':"
rg -n "path\s*=\s*['\"]/contactus['\"]" .

# Verify that these Route definitions render the ContactUs component
echo "Verifying that the '/contactus' route renders the ContactUs component:"
rg -n "element\s*=\s*{<ContactUs \/>}" .

Length of output: 595


Script:

#!/bin/bash
# Description: Verify that the /contactus route is defined and renders the ContactUs component

# Search for Route definitions with path '/contactus'
echo "Searching for Route definitions with path '/contactus':"
rg -n "path\s*=\s*['\"]/contactus['\"]" .

# Verify that these Route definitions render the ContactUs component
echo "Verifying that the '/contactus' route renders the ContactUs component:"
rg -n "element\s*=\s*{<ContactUs\s*/>}" .

Length of output: 597


Script:

#!/bin/bash
# Description: Verify that the /contactus route is defined and renders the ContactUs component

# Search for Route definitions with path '/contactus'
echo "Searching for Route definitions with path '/contactus':"
rg -n "path\s*=\s*['\"]/contactus['\"]" .

# Verify that these Route definitions render the ContactUs component
echo "Verifying that the '/contactus' route renders the ContactUs component:"
rg -n "element\s*=\s*{\s*<ContactUs\s*/>\s*}" .

Length of output: 609

backend/index.js Outdated
@@ -3,7 +3,7 @@ require("dotenv").config();
const cors = require("cors");
const mongoose = require("mongoose");
const logger = require("./config/logger");
const errorMiddleware = require("./middlewares/errorMiddleware"); // Corrected typo
const errorMiddleware = require("../backend/middlewares/errrorMiddleware"); // Corrected typo
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Fix typo in error middleware filename and import path

The error middleware file is incorrectly named with an extra 'r', which can lead to confusion and potential issues.

  • Rename backend/middlewares/errrorMiddleware.js to backend/middlewares/errorMiddleware.js.

  • Update the import statement in backend/index.js accordingly:

    - const errorMiddleware = require("../backend/middlewares/errrorMiddleware"); // Corrected typo
    + const errorMiddleware = require("../backend/middlewares/errorMiddleware"); // Corrected typo
🔗 Analysis chain

Fix typo in error middleware import path

The import statement for the error middleware contains a typo in the file name. While attempting to correct a previous issue, a new typo has been introduced.

Please apply the following change:

- const errorMiddleware = require("../backend/middlewares/errrorMiddleware"); // Corrected typo
+ const errorMiddleware = require("../backend/middlewares/errorMiddleware"); // Corrected typo

Also, please verify that this is indeed the correct path to the error middleware file. The change from ./ to ../backend/ suggests a significant change in the project structure. Ensure that this path is correct relative to the location of index.js.

To verify the correct path of the error middleware file, run the following command:

This will help confirm the correct location of the file and ensure that the import statement is accurate.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Locate the error middleware file and verify its path

# Test: Search for the error middleware file
fd errorMiddleware.js

Length of output: 23


Script:

#!/bin/bash
# Description: Locate the incorrectly named error middleware file to verify the typo

# Test: Search for the incorrectly spelled error middleware file
fd errrorMiddleware.js

Length of output: 64

const validation = contactSchema.safeParse(req.body);

if (!validation.success) {
console.log("Error at validation");
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

Use console.error for logging errors.

Using console.error instead of console.log for logging errors provides better semantic meaning and can help in error monitoring.

Apply this diff to update the logging statements:

 // In validation failure
-    console.log("Error at validation");
+    console.error("Error at validation");

 // In sendMail error handling
-      return console.log("Error occurred: " + error.message);
+      console.error("Error occurred: " + error.message);

 // In catch block
-    console.log(`Error at transport: ${err}`);
+    console.error(`Error at transport: ${err}`);

Also applies to: 54-54, 64-64

});

const mailOptions = {
from: mail,
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

Avoid setting 'from' to a user-provided email to prevent spoofing.

Setting the from field to a user-provided email address (mail) can lead to email spoofing and may cause the email to be rejected or marked as spam. Use a verified email address for the from field and set replyTo to the user's email address.

Apply this diff to fix the issue:

 const mailOptions = {
-  from: mail,
+  from: process.env.EMAIL_USER,
+  replyTo: mail,
   to: process.env.EMAIL_USER,
   subject: subject,
   text: message,
 };

This ensures that the email is sent from a trusted address while allowing you to reply to the user's email.

📝 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
from: mail,
from: process.env.EMAIL_USER,
replyTo: mail,
to: process.env.EMAIL_USER,

Comment on lines 39 to 41
tls: {
rejectUnauthorized: false, // Disable strict SSL verification
},
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

Enable SSL verification in transporter configuration.

Disabling SSL verification by setting rejectUnauthorized: false can expose the application to security risks like man-in-the-middle attacks. It's best to enable SSL verification unless there's a specific reason not to.

Apply this diff to enable SSL verification:

     tls: {
-      rejectUnauthorized: false, // Disable strict SSL verification
+      // Removed to enable strict SSL verification
     },

If the tls configuration is not required, you can remove it entirely.

📝 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
tls: {
rejectUnauthorized: false, // Disable strict SSL verification
},
tls: {
// Removed to enable strict SSL verification
},

Comment on lines 20 to 24
console.log("Error at validation");
return res.status(400).json({
status: "error",
errors: "contactSchema is not validate",
});
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

Improve error handling and messages on validation failure.

The error message "contactSchema is not validate" is grammatically incorrect. Additionally, consider providing detailed validation errors to the client for better clarity.

Apply this diff to fix the error message and include validation details:

     console.log("Error at validation");
     return res.status(400).json({
       status: "error",
-      errors: "contactSchema is not validate",
+      errors: validation.error.errors,
     });

This change returns the specific validation errors provided by Zod, helping the client understand what went wrong.

📝 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
console.log("Error at validation");
return res.status(400).json({
status: "error",
errors: "contactSchema is not validate",
});
console.log("Error at validation");
return res.status(400).json({
status: "error",
errors: validation.error.errors,
});

Comment on lines 52 to 57
transporter.sendMail(mailOptions, (error, mailOptions) => {
if (error) {
return console.log("Error occurred: " + error.message);
}

});
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

Handle errors in transporter.sendMail and send appropriate responses.

Currently, if sendMail fails, the error is only logged, and the client still receives a 200 OK response. To properly inform the client of the failure, send an error response when sending the email fails.

Apply this diff to handle errors and send appropriate responses:

 // Send mail with defined transport object
 transporter.sendMail(mailOptions, (error, info) => {
   if (error) {
-    return console.log("Error occurred: " + error.message);
+    console.error("Error occurred: " + error.message);
+    return res.status(500).json({
+      status: "error",
+      message: "There was an error sending your message. Please try again later.",
+    });
   }
-
+  res.status(200).json({
+    status: "success",
+    message: "Your contact request has been successfully received.",
+  });
 });
-
-res.status(200).json({
-  status: "success",
-  message: "Your contact request has been successfully received.",
-});

This change moves the success response inside the callback after the email is sent successfully and sends an error response if there's a failure.

📝 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
transporter.sendMail(mailOptions, (error, mailOptions) => {
if (error) {
return console.log("Error occurred: " + error.message);
}
});
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error("Error occurred: " + error.message);
return res.status(500).json({
status: "error",
message: "There was an error sending your message. Please try again later.",
});
}
res.status(200).json({
status: "success",
message: "Your contact request has been successfully received.",
});
});

const info = { messageId: "23DCS141" };

const createContactUs = async (req, res) => {
const validation = contactSchema.safeParse(req.body);
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Environment variables EMAIL_USER and EMAIL_PASS are not set.

Please set EMAIL_USER and EMAIL_PASS in your deployment environment to prevent authentication issues.

🔗 Analysis chain

Ensure environment variables are loaded correctly.

While you have require("dotenv").config(); at the top, it's important to ensure that the environment variables EMAIL_USER and EMAIL_PASS are properly loaded and handled in case they're missing.

Run the following script to check if the environment variables are set:

Ensure that these variables are set in your deployment environment to prevent authentication errors.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that EMAIL_USER and EMAIL_PASS are defined in the environment.

# Check for EMAIL_USER
if [ -z "$EMAIL_USER" ]; then
  echo "Environment variable EMAIL_USER is not set."
else
  echo "Environment variable EMAIL_USER is set."
fi

# Check for EMAIL_PASS
if [ -z "$EMAIL_PASS" ]; then
  echo "Environment variable EMAIL_PASS is not set."
else
  echo "Environment variable EMAIL_PASS is set."
fi

Length of output: 225

<form onSubmit={handleSubmit} className="space-y-4">
<div>
<input
type="mail"
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

Correct the input type for the email field.

The type attribute for the email input should be "email" instead of "mail" to enable proper email validation.

Apply this diff to fix the input type:

-           type="mail"
+           type="email"
📝 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
type="mail"
type="email"


// Basic client-side validation for security
if (!mail || !subject || !message) {
setError('All fields are required, including the rating.');
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

Update error message to reflect actual fields.

The error message mentions "including the rating," but there is no rating field in the form. Please update the message to accurately reflect the required fields.

Apply this diff to correct the error message:

-         setError('All fields are required, including the rating.');
+         setError('All fields are required.');
📝 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
setError('All fields are required, including the rating.');
setError('All fields are required.');

Comment on lines 44 to 50
const response = await fetch(`${API_URL}/api/contact/contactus`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail, subject, message }),
});
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

Add response status check after the fetch request.

Currently, the code assumes that the fetch request is always successful. It's good practice to check the response status and handle errors accordingly.

Apply this diff to check the response status:

           const response = await fetch(`${API_URL}/api/contact/contactus`, {
             method: 'POST',
             headers: {
               'Content-Type': 'application/json',
             },
             body: JSON.stringify({ mail, subject, message }),
           });
+          if (!response.ok) {
+            throw new Error('Network response was not ok');
+          }
           setSubmitted(true);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const response = await fetch(`${API_URL}/api/contact/contactus`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail, subject, message }),
});
const response = await fetch(`${API_URL}/api/contact/contactus`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mail, subject, message }),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}

Copy link
Author

@PriyanshuValiya PriyanshuValiya left a comment

Choose a reason for hiding this comment

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

Changed Some Files

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

🧹 Outside diff range and nitpick comments (3)
backend/controller/contact.controller.js (1)

62-69: Consider more specific error handling.

While the current error handling is functional, consider catching specific errors to provide more accurate error messages.

Apply this diff to improve error handling:

- } catch (err) {
+ } catch (err) {
+   let errorMessage = "There was an error sending your message. Please try again later.";
+   if (err.code === 'EAUTH') {
+     errorMessage = "Email authentication failed. Please contact support.";
+   } else if (err.code === 'ECONNECTION') {
+     errorMessage = "Connection to email server failed. Please try again later.";
+   }
    console.error(`Error at transport: ${err}`);
    res.status(500).json({
      status: "error",
-     message:
-       "There was an error sending your message. Please try again later.",
+     message: errorMessage,
    });
🧰 Tools
🪛 Biome

[error] 62-62: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 62-69: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.

(lint/complexity/noUselessLoneBlockStatements)

frontend/src/components/Pages/ContactUs.jsx (2)

57-62: Increase success message display duration.

The current 3-second timeout for the success message might be too short for users to read. Consider increasing it to 5 seconds.

-      }, 3000);
+      }, 5000);

30-69: Implement security measures.

Consider adding the following security enhancements:

  1. Rate limiting to prevent form spam
  2. CSRF protection
  3. Captcha or similar anti-bot measures

Example implementation of rate limiting using a simple cooldown:

const COOLDOWN_PERIOD = 60000; // 1 minute
const [lastSubmissionTime, setLastSubmissionTime] = useState(0);

const handleSubmit = async (e) => {
  e.preventDefault();
  
  const now = Date.now();
  if (now - lastSubmissionTime < COOLDOWN_PERIOD) {
    setError('Please wait a moment before submitting again.');
    return;
  }
  
  setLastSubmissionTime(now);
  // ... rest of the submission logic
};
🧰 Tools
🪛 Biome

[error] 53-53: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 53-54: This code is unreachable

... because this statement will throw an exception beforehand

(lint/correctness/noUnreachable)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 56f7052 and 1f8f7e3.

📒 Files selected for processing (6)
  • backend/controller/contact.controller.js (1 hunks)
  • backend/index.js (1 hunks)
  • frontend/package.json (1 hunks)
  • frontend/src/components/Pages/ContactUs.jsx (1 hunks)
  • frontend/src/components/Shared/Navbar.jsx (1 hunks)
  • frontend/src/router/index.jsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • backend/index.js
  • frontend/package.json
  • frontend/src/components/Shared/Navbar.jsx
  • frontend/src/router/index.jsx
🧰 Additional context used
🪛 Biome
backend/controller/contact.controller.js

[error] 43-44: Expected a property, a shorthand property, a getter, a setter, or a method but instead found '+'.

Expected a property, a shorthand property, a getter, a setter, or a method here.

(parse)


[error] 44-44: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 48-48: Expected a catch clause but instead found ';'.

Expected a catch clause here.

(parse)


[error] 62-62: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 69-70: Expected a statement but instead found '}'.

Expected a statement here.

(parse)


[error] 62-69: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.

(lint/complexity/noUselessLoneBlockStatements)

frontend/src/components/Pages/ContactUs.jsx

[error] 53-53: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 53-54: This code is unreachable

... because this statement will throw an exception beforehand

(lint/correctness/noUnreachable)

🔇 Additional comments (3)
backend/controller/contact.controller.js (3)

1-10: LGTM! Well-structured schema definition.

The Zod schema implementation provides good validation rules for the contact form fields.


15-21: Improve validation error handling.

The current implementation doesn't provide detailed validation errors to the client.

Apply this diff to improve error handling:

    console.error("Error at validation");
    return res.status(400).json({
      status: "error",
-     errors: "contactSchema is not validate",
+     errors: validation.error.errors,
    });

25-39: Security concerns in transport configuration.

  1. The commented TLS configuration suggests SSL verification might be disabled in some environments.
  2. Environment variables need proper validation.

Let's verify the environment variables:

#!/bin/bash
# Check for required environment variables in .env files
fd -t f "^\.env" -x grep -l "EMAIL_USER\|EMAIL_PASS" {} \;

Comment on lines 51 to 61
transporter.sendMail(mailOptions, (error, mailOptions) => {
if (error) {
return console.error("Error occurred: " + error.message);
}

});

res.status(200).json({
status: "success",
message: "Your contact request has been successfully received.",
});
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 race condition in email sending logic.

The success response is sent regardless of whether the email was successfully sent or not, creating a race condition.

Apply this diff to fix the issue:

    // Send mail with defined transport object
-   transporter.sendMail(mailOptions, (error, mailOptions) => {
-     if (error) {
-       return console.error("Error occurred: " + error.message);
-     }
-
-   });
-
-   res.status(200).json({
-     status: "success",
-     message: "Your contact request has been successfully received.",
-   });
+   await new Promise((resolve, reject) => {
+     transporter.sendMail(mailOptions, (error, info) => {
+       if (error) {
+         console.error("Error occurred: " + error.message);
+         reject(error);
+       }
+       resolve(info);
+     });
+   });
+   
+   res.status(200).json({
+     status: "success",
+     message: "Your contact request has been successfully received.",
+   });
📝 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
transporter.sendMail(mailOptions, (error, mailOptions) => {
if (error) {
return console.error("Error occurred: " + error.message);
}
});
res.status(200).json({
status: "success",
message: "Your contact request has been successfully received.",
});
await new Promise((resolve, reject) => {
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error("Error occurred: " + error.message);
reject(error);
}
resolve(info);
});
});
res.status(200).json({
status: "success",
message: "Your contact request has been successfully received.",
});

import { motion } from 'framer-motion';
import { useInView } from 'react-intersection-observer';
import chess from '../../assets/img/chess.gif';
import { FaStar } from 'react-icons/fa6';
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

Remove unused import FaStar.

The FaStar component from react-icons is imported but never used in the code.

-import { FaStar } from 'react-icons/fa6';
📝 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
import { FaStar } from 'react-icons/fa6';

const [subject, setSubject] = useState('');
const [message, setMessage] = useState('');
const [submitted, setSubmitted] = useState(false);
const [hover, setHover] = useState(null);
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

Remove unused state variable hover.

The hover state and its setter are declared but never used in the component.

-const [hover, setHover] = useState(null);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [hover, setHover] = useState(null);

Comment on lines 52 to 54
if (!response.ok) {
+ throw new Error('Network response was not ok');
+ }
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 syntax error in error handling.

The throw statement has incorrect syntax and makes the following code unreachable.

      if (!response.ok) {
-        throw new Error('Network response was not ok');
-     }
+        throw new Error(`Network response was not ok: ${response.status}`);
+      }
📝 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
if (!response.ok) {
+ throw new Error('Network response was not ok');
+ }
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.status}`);
}
🧰 Tools
🪛 Biome

[error] 53-53: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 53-54: This code is unreachable

... because this statement will throw an exception beforehand

(lint/correctness/noUnreachable)

Comment on lines 102 to 111
<input
type="email"
id="mail"
value={mail}
placeholder="Email ID"
onChange={(e) => setMail(e.target.value)}
required
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-[#004D43] focus:border-[#004D43]"
/>
</div>
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

Improve form accessibility.

Add proper labels and ARIA attributes for better accessibility.

 <div>
+  <label htmlFor="mail" className="sr-only">Email Address</label>
   <input
     type="email"
     id="mail"
     value={mail}
     placeholder="Email ID"
+    aria-label="Email Address"
     onChange={(e) => setMail(e.target.value)}
     required
     className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-[#004D43] focus:border-[#004D43]"
   />
 </div>
📝 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
<input
type="email"
id="mail"
value={mail}
placeholder="Email ID"
onChange={(e) => setMail(e.target.value)}
required
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-[#004D43] focus:border-[#004D43]"
/>
</div>
<div>
<label htmlFor="mail" className="sr-only">Email Address</label>
<input
type="email"
id="mail"
value={mail}
placeholder="Email ID"
aria-label="Email Address"
onChange={(e) => setMail(e.target.value)}
required
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-[#004D43] focus:border-[#004D43]"
/>
</div>

Comment on lines 33 to 37
// Basic client-side validation for security
if (!mail || !subject || !message) {
setError('All fields are required.');
return;
}
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

Enhance input validation.

The current validation only checks for empty fields. Consider adding more robust validation:

  1. Email format validation
  2. Maximum length checks
  3. Input sanitization
-    if (!mail || !subject || !message) {
-      setError('All fields are required.');
-      return;
-    }
+    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+    if (!mail || !subject || !message) {
+      setError('All fields are required.');
+      return;
+    }
+    if (!emailRegex.test(mail)) {
+      setError('Please enter a valid email address.');
+      return;
+    }
+    if (subject.length > 100) {
+      setError('Subject must be less than 100 characters.');
+      return;
+    }
+    if (message.length > 1000) {
+      setError('Message must be less than 1000 characters.');
+      return;
+    }
📝 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
// Basic client-side validation for security
if (!mail || !subject || !message) {
setError('All fields are required.');
return;
}
// Basic client-side validation for security
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!mail || !subject || !message) {
setError('All fields are required.');
return;
}
if (!emailRegex.test(mail)) {
setError('Please enter a valid email address.');
return;
}
if (subject.length > 100) {
setError('Subject must be less than 100 characters.');
return;
}
if (message.length > 1000) {
setError('Message must be less than 1000 characters.');
return;
}

Copy link
Author

@PriyanshuValiya PriyanshuValiya left a comment

Choose a reason for hiding this comment

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

Some changes were done.

@PriyanshuValiya PriyanshuValiya marked this pull request as draft October 24, 2024 14:50
@PriyanshuValiya PriyanshuValiya closed this by deleting the head repository Oct 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant