Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions controllers/login.contollers.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ const registerUser = async (req, res) => {

// Function to user set the password
const createuserandPassword = async (req, res) => {
let session;
try {
console.log('createuserandPassword function called');
const { email, password, name, phoneNo ,isFaculty} = req.body;
Expand Down Expand Up @@ -224,11 +225,15 @@ const registerUser = async (req, res) => {
const rollNo = match[1]; // Capture the part before @ as roll number

console.log('Extracted roll number:', rollNo);

session = await mongoose.startSession();
session.startTransaction();

// Check if user already exists
const existingUser = await User.findOne({ email });
if (existingUser) {
console.log('Email already exists:', email);
await session.abortTransaction();
return res.status(400).json({ message: 'Email already exists' });
}

Expand All @@ -237,21 +242,22 @@ const registerUser = async (req, res) => {
const hashedPassword = await bcrypt.hash(password, 10);
console.log('Password hashed successfully');

const formattedName = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
console.log('Formatted name:', formattedName);

const formattedName = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
console.log('Formatted name:', formattedName);
console.log('Creating new user with email:', email);
const newUser = new User({
email,
password: hashedPassword,
name: formattedName,
name: formattedName,
rollNo,
phoneNo,
isFaculty,
});

console.log('Saving new user to the database');
await newUser.save();
await newUser.save({ session });
await session.commitTransaction();
console.log('User saved successfully:', newUser);

return res.status(201).json({
Expand All @@ -265,8 +271,11 @@ const registerUser = async (req, res) => {
});

} catch (error) {
if (session) await session.abortTransaction();
console.error('Error in setPassword:', error);
return res.status(500).json({ message: 'Server error' });
} finally {
if (session) session.endSession();
}
};

Expand Down Expand Up @@ -314,6 +323,7 @@ const registerUser = async (req, res) => {

// Function to reset user password
const resetPassword = async (req, res) => {
let session;
try {
const { password, email } = req.body;
console.log('resetPassword');
Expand All @@ -325,10 +335,14 @@ const registerUser = async (req, res) => {
console.log('Missing email or password');
return res.status(400).json({ message: 'Email and password are required' });
}

session = await mongoose.startSession();
session.startTransaction();

const existingUser = await User.findOne({ email });
if (!existingUser) {
console.log('Email does not exist');
await session.abortTransaction();
return res.status(400).json({ message: 'Email does not exist' });
}

Expand All @@ -339,7 +353,8 @@ const registerUser = async (req, res) => {
existingUser.password = hashedPassword;


await existingUser.save();
await existingUser.save({ session });
await session.commitTransaction();
console.log('Password updated successfully:', existingUser);

return res.status(200).json({
Expand All @@ -351,8 +366,11 @@ const registerUser = async (req, res) => {
}
});
} catch (error) {
if (session) await session.abortTransaction();
console.error('Error in resetPassword:', error);
return res.status(500).json({ message: 'Server error' });
} finally {
if (session) session.endSession();
}
};

Expand Down
2 changes: 1 addition & 1 deletion middleware/auth/tokencreation.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ async function forgotmailtoken(data) {


savedToken.token = token;
await savedToken.save();
await savedToken.save();


console.log('Updated Token:', savedToken);
Expand Down
105 changes: 62 additions & 43 deletions middleware/mail/mail.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require('dotenv').config();
const nodemailer = require('nodemailer');
const mongoose = require('mongoose');
const { TEMPLATE_WELCOME_MAIL, TEMPLATE_RESET_MAIL, TEMPLATE_ADMIN_WELCOME_MAIL } = require('./mail_temp');
const { registermailtoken, forgotmailtoken } = require('../auth/tokencreation');
const { USER_NOTIFY_MAIL_TEMPLATE, USER_ACCEPT_MAIL_TEMPLATE, USER_REJECT_MAIL_TEMPLATE, USER_REMINDER_MAIL_TEMPLATE, USER_DELAY_MAIL_TEMPLATE, USER_RE_NOTIFY_MAIL_TEMPLATE, USER_RE_ACCEPT_MAIL_TEMPLATE, USER_RE_REJECT_MAIL_TEMPLATE, USER_RETURN_MAIL_TEMPLATE, USER_COLLECT_MAIL_TEMPLATE } = require('./user_mail_temp');
Expand All @@ -20,29 +21,37 @@ const transporter = nodemailer.createTransport({
const sendregisterEmail = async (email, name, phoneNo, isFaculty, type) => {
try {
console.log("sendregisterEmail");

const tokenData = { email, name, phoneNo, isFaculty };
const token = await registermailtoken(tokenData, type);
console.log(token);

const verificationUrl = `${process.env.STATIC_URL}/auth/password?token=${token}&type=register`;

const htmlContent = type === 'admin'
? TEMPLATE_ADMIN_WELCOME_MAIL(name, verificationUrl)
: TEMPLATE_WELCOME_MAIL(name, verificationUrl);

const mailOptions = {
from: process.env.EMAIL_FROM,
to: email,
subject: 'Amudalab Equipment Management – Verify Your Account',
text: `Hello ${name},\n\nWelcome! Click the link below to verify your email and set your password:\n\n${verificationUrl}`,
html: htmlContent,
};


await transporter.sendMail(mailOptions);
console.log("Register email sent successfully ✅");

const session = await mongoose.startSession();
session.startTransaction();
try {
const tokenData = { email, name, phoneNo, isFaculty };
const token = await registermailtoken(tokenData, type);
console.log(token);

const verificationUrl = `${process.env.STATIC_URL}/auth/password?token=${token}&type=register`;

const htmlContent = type === 'admin'
? TEMPLATE_ADMIN_WELCOME_MAIL(name, verificationUrl)
: TEMPLATE_WELCOME_MAIL(name, verificationUrl);

const mailOptions = {
from: process.env.EMAIL_FROM,
to: email,
subject: 'Amudalab Equipment Management – Verify Your Account',
text: `Hello ${name},\n\nWelcome! Click the link below to verify your email and set your password:\n\n${verificationUrl}`,
html: htmlContent,
};


await transporter.sendMail(mailOptions);
console.log("Register email sent successfully ✅");
await session.commitTransaction();
session.endSession();
} catch (error) {
await session.abortTransaction();
session.endSession();
throw error;
}
} catch (error) {
console.error("Error sending register email ❌:", error.response || error);
throw new Error('Error sending register email');
Expand All @@ -53,26 +62,36 @@ const sendregisterEmail = async (email, name, phoneNo, isFaculty, type) => {
const sendforgotEmail = async (email, name) => {
try {
console.log("sendforgotEmail");

const tokenData = { email, name };
const token = await forgotmailtoken(tokenData);
console.log(token);

const verificationUrl = `${process.env.STATIC_URL}/auth/password?token=${token}&type=forgot`;

const htmlContent = TEMPLATE_RESET_MAIL(name, verificationUrl);

const mailOptions = {
from: process.env.EMAIL_FROM,
to: email,
subject: 'Amuda-lab- Reset Your Password',
text: `Hello ${name},\n\nClick the link below to reset your password:\n\n${verificationUrl}`,
html: htmlContent,
};


await transporter.sendMail(mailOptions);
console.log("Forgot password email sent successfully ✅");
const session = await mongoose.startSession();
session.startTransaction();
try {

const tokenData = { email, name };
const token = await forgotmailtoken(tokenData);
console.log(token);

const verificationUrl = `${process.env.STATIC_URL}/auth/password?token=${token}&type=forgot`;

const htmlContent = TEMPLATE_RESET_MAIL(name, verificationUrl);

const mailOptions = {
from: process.env.EMAIL_FROM,
to: email,
subject: 'Amuda-lab- Reset Your Password',
text: `Hello ${name},\n\nClick the link below to reset your password:\n\n${verificationUrl}`,
html: htmlContent,
};


await transporter.sendMail(mailOptions);
console.log("Forgot password email sent successfully ✅");
await session.commitTransaction();
session.endSession();
} catch (error) {
await session.abortTransaction();
session.endSession();
throw error;
}

} catch (error) {
console.error("Error sending forgot password email ❌:", error.response || error);
Expand Down