Advertisement
Guest User

Example of using Nodemailer in NodeJS

a guest
Dec 13th, 2019
370
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // @desc    Forgot password
  2. // @route   POST /api/v1/auth/forgotpassword
  3. // @access  Public
  4. // @status  DONE
  5. exports.forgotPassword = asyncHandler(async (req, res, next) => {
  6.  
  7.   const user = await User.findOne({ email: req.body.email }); // Does the email submitted match with a user in the system?
  8.   if (!user) {
  9.     return next(new ErrorResponse('There is not user with that email', 404)); // Does not exists? Then thrown an error
  10.   }
  11.  
  12.   // Get userId
  13.   const userId = user.id; // YOU DONT NEED THE USERID. If you decide to delete this, make sure to delete it from the const resetURL also.
  14.  
  15.   // Get reset token
  16.   const resetToken = user.getResetPasswordToken(); // THIS IS AFUNCTION LOCATED IN YOUR MODEL USING MONGOOSE. SEE BELOW
  17.  
  18.   // user.password = undefined;
  19.   await user.save({ validateBeforeSave: false });
  20.  
  21.   // Create reset url
  22.   const resetUrl = `${req.protocol}://${req.get(
  23.     'host'
  24.   )}/auth/resetpassword/${userId}/${resetToken}`;
  25.  
  26.   const message = `You are receiving this email because you have requested the reset of a password. Please make a PUT request to: \n\n <a href="${resetUrl}">Reset Password</a> `;
  27.  
  28.   try {
  29.     await sendEmail({ // sendEmail is a function that you can call as many times as you want. SEE BELOW
  30.       email: user.email,
  31.       subject: 'Password reset token',
  32.       message
  33.     });
  34.  
  35.     res.status(200).json({ success: true, data: 'Email sent', user });
  36.   } catch (err) {
  37.     console.log(err);
  38.     user.resetPasswordToken = undefined;
  39.     user.resetPasswordExpire = undefined;
  40.  
  41.     await user.save({ validateBeforeSave: false });
  42.  
  43.     return next(new ErrorResponse('Email could not be sent', 500)); // YOU CAN HANGLE ERRORS HOWEVER YOU WANT. YOU MIGHT DELETE THIS AS IT WILL SHOW YOU AN ERROR(--PROBABLY--).
  44.   }
  45. });
  46.  
  47. /*
  48. * THIS IS A HELPER FILE CONTAINING A FUNCTION THAT YOU CAN CALL FROM ANY OF YOUR ROUTES.
  49. */
  50. const nodemailer = require('nodemailer');
  51.  
  52. const sendEmail = async options => {
  53.   const transporter = nodemailer.createTransport({
  54.     host: process.env.SMTP_HOST, // YOU GET ALL OF THIS FROM E-MAIL SERVER
  55.     port: process.env.SMTP_PORT, // YOU GET ALL OF THIS FROM E-MAIL SERVER
  56.     auth: {
  57.       user: process.env.SMTP_EMAIL, // YOU GET ALL OF THIS FROM E-MAIL SERVER
  58.       pass: process.env.SMTP_PASSWORD // YOU GET ALL OF THIS FROM E-MAIL SERVER
  59.     }
  60.   });
  61.  
  62.   const message = {
  63.     from: `${process.env.FROM_NAME} <${process.env.FROM_EMAIL}>`,
  64.     to: options.email,
  65.     subject: options.subject,
  66.     text: options.message,
  67.     html: options.message
  68.   };
  69.  
  70.   const info = await transporter.sendMail(message);
  71.  
  72.   console.log('Message sent: %s', info.messageId);
  73. };
  74.  
  75. module.exports = sendEmail;
  76.  
  77. /*
  78. * FUNCTION TO GET A GENERATE TOKEN LOCATED IN MODEL - you need CRYPTO in order to make it work.
  79. */
  80. UserSchema.methods.getResetPasswordToken = function() {
  81.   // Generate token
  82.   const resetToken = crypto.randomBytes(20).toString('hex');
  83.  
  84.   // Hash token and set to resetPasswordToken field
  85.   this.resetPasswordToken = crypto
  86.     .createHash('sha256')
  87.     .update(resetToken)
  88.     .digest('hex');
  89.  
  90.   // Set expire
  91.   this.resetPasswordExpire = Date.now() + 10 * 60 * 1000;
  92.  
  93.   return resetToken;
  94. };
  95.  
  96. /*
  97. * THIS IS THE ROUTE TO USE WITH THE URL SENT IN THE EMAIL.
  98. * AGAIN YOU DON'T NEED USERID -- OPTIONAL
  99. * EXAMPLE OF ROUTE IN FRONT END: /auth/resetpassword/:userid/:resettoken
  100. */
  101. exports.resetPassword = asyncHandler(async (req, res, next) => {
  102.   // Get hashed token
  103.   const resetPasswordToken = crypto
  104.     .createHash('sha256')
  105.     .update(req.params.resettoken)
  106.     .digest('hex');
  107.  
  108.   const user = await User.findOne({
  109.     _id: req.params.userid,
  110.     resetPasswordToken,
  111.     resetPasswordExpire: { $gt: Date.now() }
  112.   });
  113.  
  114.   if (!user) {
  115.     return next(new ErrorResponse('Invalid token', 400));
  116.   }
  117.  
  118.   // Set new password
  119.   user.password = req.body.password;
  120.   user.resetPasswordToken = undefined;
  121.   user.resetPasswordExpire = undefined;
  122.  
  123.   await user.save();
  124.  
  125.   res
  126.     .status(200)
  127.     .json({ success: true, data: 'New password has been created', user });
  128.   // sendTokenResponse(user, 200, res);
  129. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement