I've been trying to generate a token to reset a user's password and send the user an email with the link to use that token.
This is the function forgotPassword defined in the class authController:
//forgot password => /api/v1/password/forgot
exports.forgotPassword = catchAsynErrors(async(req, res, next) => {
const user = await User.findOne({ email: req.body.email });
if(!user){
return next(new ErrorHandler('User not found with this email', 404));
}
//get reset token
const resetToken = user.getResetPasswordToken();
await user.save({validateBeforeSave: false});
// create reset password url
const resetUrl = `${req.protocol}://${req.get('host')}/api/v1/password/reset/${resetToken}`;
const message = `Your password reset token:\n\n${resetUrl}\n\n If you have not requested this email, please ignore it.`
try {
await sendEmail({
email: user.email,
subject: 'ShopIt password recovery',
message
})
res.status(200).json({
success: true,
message: `Email sent to: ${user.email}`
})
} catch (error) {
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;
await user.save({validateBeforeSave: false});
return next(new ErrorHandler(error.message, 500))
}
})
Then, the function getResetPasswordToken defined in the model class user:
// generate password reset token
userSchema.methods.getResetPasswordToken = function() {
//generate token
const resetToken = crypto.randomBytes(20).toString('hex');
//hash and set to resetPasswordToken
this.resetPasswordToken = crypto.createHash('sha256').update(resetToken).digest('hex')
// set token expiration date
this.resetPasswordExpire = Date.now() + 30 * 60 * 1000
return resetToken
}
Upon sending a POST request via Postman to the URL http://localhost:4000/api/v1/password/forgot with the following JSON body,
{
"email": "example@email.com"
}
I get this response:
{
"success": false,
error": {
"statusCode": 500
},
"errMessage": "getaddrinfo ENOTFOUND smpt.mailtrap.io",
"stack": "Error: getaddrinfo ENOTFOUND smpt.mailtrap.io\n at D:\\pruebas de programación\\Proyectazo\\backend\\controllers\\authController.js:93:21\n at processTicksAndRejections (node:internal/process/task_queues:96:5)"
}
I have seen suggestions that this could be a DNS error, but I have already tried manually setting up an IPv4 address like 192.168.1.45 and my DNS servers set to 1.1.1.1 and 1.0.0.1, and the internet worked normally but I kept getting the same error, so I set my network configuration back to DHCP. I also tried emailing both real and fake email addresses and it made no difference.
Any ideas?