Skip to content

Commit

Permalink
Send Email
Browse files Browse the repository at this point in the history
  • Loading branch information
Belchenkov committed Jan 25, 2020
1 parent 45b7355 commit 2ac7b34
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
31 changes: 28 additions & 3 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const User = require('../models/User');
const ErrorResponse = require('../utils/errorResponse');
const asyncHandler = require('../middleware/async');
const sendEmail = require('../utils/sendEmail');

// @desc Register User
// @route POST /api/v1/auth/register
Expand Down Expand Up @@ -62,13 +63,37 @@ exports.getMe = asyncHandler(async (req, res, next) => {
exports.forgotPassword = asyncHandler(async (req, res, next) => {
const user = await User.findOne({ email: req.body.email });

if (!user)
return next(new ErrorResponse('There is no user with that email', 404));
if (!user) return next(new ErrorResponse('There is no user with that email', 404));

// Get reset token
const resetToken = user.getResetPasswordToken();

await user.save({ validateBeforeSave: false });
//await user.save({ validateBeforeSave: false });

// Create reset url
const resetUrl = `${req.protocol}://${req.get(
'host'
)}/api/v1/auth/resetpassword/${resetToken}`;

const message = `You are receiving this email because you (or someone else) has requested the reset of a password. Please make a PUT request to: \n\n ${resetUrl}`;

try {
await sendEmail({
email: user.email,
subject: 'Password reset token',
message
});

res.status(200).json({ success: true, data: 'Email sent' });
} catch (err) {
console.log(err);
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;

await user.save({ validateBeforeSave: false });

return next(new ErrorResponse('Email could not be sent', 500));
}

res.status(200).json({
success: true,
Expand Down
12 changes: 5 additions & 7 deletions utils/sendEmail.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,16 @@ const sendEmail = async (options) => {
}
});

// send mail with defined transport object
let message = {
const message = {
from: `${process.env.FROM_NAME} <${process.env.FROM_EMAIL}>`,
to: options.email,
subject: options.subject,
text: options.message
};

console.log("Message sent: %s", info.messageId);
// Message sent: <[email protected]>
const info = await transporter.sendMail(message);

// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
console.log("Message sent: %s", info.messageId);
};

module.exports = sendEmail;

0 comments on commit 2ac7b34

Please sign in to comment.