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 contact us backend #1325

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
56 changes: 6 additions & 50 deletions controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,84 +10,40 @@ exports.signupController = async (req, res) => {
try {
const { name, email, password } = req.body;

if (name.length < 5) {
res
.status(400)
.json({ error: "invalid name!!!! Name should be atleast 5 char long" });
return;
}

if (!emailValidator.validate(email)) {
res.status(400).json({ error: "invalid email!!!!" });
return;
}
// validate password as--> Min 8 char, one upper case,one lowercase,one digit

const passwordSchema = new passwordValidator();
passwordSchema
.is()
.min(8) // Minimum length 8
.is()
.max(100) // Maximum length 100
.has()
.uppercase() // Must have uppercase letters
.has()
.lowercase() // Must have lowercase letters
.has()
.digits(1); // Must have at least 1 digits

if (!passwordSchema.validate(password)) {
res.status(400).json({
error:
"Password Should be of atleast 8 char long and should contain 1 upper case, 1 lower case and 1 digit",
});
return;
}

const emailExists = await userModel.find({ email });

if (emailExists.length > 0) {
console.log(emailExists);
//email already exists
res.status(409).json({ error: "Email already exists" });
return res.status(409).json({ error: "Email already exists" });
} else {
const user = await userModel.create({ name, email, password });
this.sendToken(user, res);
}
} catch (error) {
console.log("Error: " + error);
res.status(404).json({ error: "Something Went Wrong!!! Try Again" });
res.status(500).json({ error: "Something went wrong! Try again." });
}
};

exports.loginController = async (req, res) => {
try {
const { email, password } = req.body;
if (!emailValidator.validate(email)) {
res.status(400).json({ error: "invalid email!!!!" });
return;
}

const user_list = await userModel.find({ email });

if (user_list.length === 0) {
res.status(400).json({ error: "No such Email Exists!!!!" });
return;
return res.status(400).json({ error: "No such Email Exists!" });
} else {
//email is in our DB..let's check for matching password
const user = user_list[0];
const matched = await user.matchPassword(password);

if (!matched) {
//invalid-password
res.status(400).json({ error: "Invalid Password" });
return;
return res.status(400).json({ error: "Invalid Password" });
} else {
//if matched..get the tokens
this.sendToken(user, res);
}
}
} catch (error) {
console.log("Error: " + error);
res.status(500).json({ error: "Someting Went Wrong!!! Try Again" });
res.status(500).json({ error: "Something went wrong! Try again." });
}
};
60 changes: 60 additions & 0 deletions controllers/contactusController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// routes/feedback.js
const nodemailer = require("nodemailer");
const contactUs = require("../models/contactUs");

exports.contactusController = async (req, res) => {
const { firstName, lastName, email, phoneNumber, feedback } = req.body;

try {
// Save the feedback to the database
const newFeedback = new contactUs({
firstName,
lastName,
email,
phoneNumber,
feedback,
});

await newFeedback.save();

// Send a thank-you email
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});

const mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject: "Thank you for your feedback!",
text: `Dear ${firstName},

Thank you for your valuable feedback!

Here is a copy of what you submitted:
----------------------------------------
Feedback: ${feedback}

Best regards,
Imagine AI
`,
};

await transporter.sendMail(mailOptions);

res
.status(200)
.json({
message: "Feedback submitted successfully and mail sent to the mail id",
newFeedback,
});
} catch (error) {
console.error("Error submitting feedback:", error);
res
.status(500)
.json({ error: "An error occurred while submitting the feedback" });
}
};
17 changes: 14 additions & 3 deletions controllers/feedbackController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const nodemailer = require("nodemailer");

exports.feedbackController = async (req, res) => {
const { name, email, feedback } = req.body;

let transporter = nodemailer.createTransport({
service: "gmail",
auth: {
Expand All @@ -19,9 +20,19 @@ exports.feedbackController = async (req, res) => {

try {
await transporter.sendMail(mailOptions);
res.status(200).send("Feedback sent successfully");
res.status(200).json({ message: "Feedback sent successfully" });
} catch (error) {
res.status(500).send("Error sending feedback");
console.log(error.message);
console.error("Error sending feedback:", {
message: error.message,
stack: error.stack,
additionalInfo: {
user: email,
feedback: feedback,
},
});

res
.status(500)
.json({ error: "Error sending feedback. Please try again later." });
}
};
38 changes: 38 additions & 0 deletions controllers/subscribeController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const nodemailer = require("nodemailer");

const subscribeToEmail = async (req, res) => {
const { email } = req.body;

let transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});

let mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject: "Thank you for subscribing to IMAGINE AI!",
text: "Thank you for subscribing to our platform!",
html: "<h1>Thank you!</h1><p>You have successfully subscribed to our platform.</p>",
};

try {
await transporter.sendMail(mailOptions);
console.log(`Email sent successfully to ${email}`);
res.status(200).send("Subscription successful. Thank you email sent!");
} catch (error) {
console.error("Error sending email: ", {
message: error.message,
stack: error.stack,
recipientEmail: email,
});
res.status(500).send("Error sending email.");
}
};

module.exports = {
subscribeToEmail,
};
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ app.get("/file", (req, res) => {
app.use("/openai", require("./routes/openaiRoutes"));
app.use("/auth", require("./routes/auth.js"));
app.use("/send-feedback", require("./routes/feedback.js"));
app.use("/subscribe", require("./routes/subscribe.js"));
app.use("/contact-us", require("./routes/contactUs.js"));
app.use(viewRoutes);

app.listen(process.env.PORT, () =>
Expand Down
33 changes: 33 additions & 0 deletions middlewares/authValidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const { check, validationResult } = require("express-validator");

// Signup validation rules
exports.signupValidation = [
check("name")
.isLength({ min: 5 })
.withMessage("Name must be at least 5 characters long"),
check("email").isEmail().withMessage("Invalid email format"),
check("password")
.isLength({ min: 8 })
.withMessage("Password must be at least 8 characters long")
.matches(/[A-Z]/)
.withMessage("Password must contain at least one uppercase letter")
.matches(/[a-z]/)
.withMessage("Password must contain at least one lowercase letter")
.matches(/\d/)
.withMessage("Password must contain at least one digit"),
];

// Login validation rules
exports.loginValidation = [
check("email").isEmail().withMessage("Invalid email format"),
check("password").exists().withMessage("Password is required"),
];

// Middleware to check for validation errors
exports.validate = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
};
17 changes: 17 additions & 0 deletions middlewares/emailValidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const { check, validationResult } = require("express-validator");

exports.emailValidation = [
check("email")
.isEmail()
.withMessage("Please provide a valid email address.")
.matches(/^[^\s@]+@gmail\.com$/i)
.withMessage("Only Gmail addresses are allowed."),
];

exports.validate = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
};
19 changes: 19 additions & 0 deletions middlewares/feedbackValidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { check, validationResult } = require("express-validator");

exports.feedbackValidation = [
check("name")
.isLength({ min: 3 })
.withMessage("Name must be at least 3 characters long"),
check("email").isEmail().withMessage("Please provide a valid email"),
check("feedback")
.isLength({ min: 10 })
.withMessage("Feedback must be at least 10 characters long"),
];

exports.validate = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
};
33 changes: 33 additions & 0 deletions models/contactUs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// models/Feedback.js
const mongoose = require("mongoose");

const contactUsSchema = new mongoose.Schema({
firstName: {
type: String,
required: true,
minlength: 3,
},
lastName: {
type: String,
required: true,
minlength: 3,
},
email: {
type: String,
required: true,
match: /.+\@.+\..+/,
},
phoneNumber: {
type: String,
required: true,
match: /^[+]*[0-9]{10,15}$/,
},
feedback: {
type: String,
required: true,
minlength: 10,
maxlength: 50,
},
});

module.exports = mongoose.model("ContactUs", contactUsSchema);
Loading