diff --git a/controllers/login.contollers.js b/controllers/login.contollers.js index c431b5a..daf654f 100644 --- a/controllers/login.contollers.js +++ b/controllers/login.contollers.js @@ -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; @@ -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' }); } @@ -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({ @@ -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(); } }; @@ -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'); @@ -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' }); } @@ -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({ @@ -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(); } }; diff --git a/middleware/auth/tokencreation.js b/middleware/auth/tokencreation.js index c2d0ed5..8962959 100644 --- a/middleware/auth/tokencreation.js +++ b/middleware/auth/tokencreation.js @@ -113,7 +113,7 @@ async function forgotmailtoken(data) { savedToken.token = token; - await savedToken.save(); + await savedToken.save(); console.log('Updated Token:', savedToken); diff --git a/middleware/mail/mail.js b/middleware/mail/mail.js index d3e3f77..341dcd0 100644 --- a/middleware/mail/mail.js +++ b/middleware/mail/mail.js @@ -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'); @@ -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'); @@ -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);