Forgot Password in SignUp Application with NodeJs and MongoDB(Part 4)

Serap Baysal
Apr 11 · 3 min read

In this article, we’ll continue to SignUp application. In this part, I’ll write about forgot password, sending email with nodemailer and reset password. If you ready, let’s begin!

First of all, in previous part I used mailgun, not nodemailer. But when I searched about sending email methods, I see nodemailer and wanna use it just for diffrence.

For reset password, we need a String variable in User model. I create a Date variable too, but I don’t use it so you can pass it. The String variable named resetPasswordToken. We need package called crypto, we’ll require it in top.

In User model, we’ll create a method named getResetPasswordToken, in this variable:

const resetToken = crypto.randomBytes(20).toString('hex');

Now, we need to hash token and set to resetPasswordToken field, set expire and return resetToken. The whole code about getResetPasswordToken is here:

getResetPasswordToken

For catching mails I will use mailgun, create an account and get some definitions.

We’ll create a middleware named sendEmail. In this, we need nodemailer, so we’ll stop server and install nodemailer with:

npm install nodemailer

We’ll require it, top of middleware.

In nodemailer website, we’ll copy these codes:

nodemailer

I change some parts as I want. In createTransport, you can see host, port and auth are diffrent from website. For these, we’ll go to .env file and create SMTP_HOST, SMTP_PORT, SMTP_EMAIL, SMTP_PASSWORD. In mailgun, we can see this parts, I don’t share them of course.

Now, we need a method named forgotPassword. With this method, we’ll take an email and send a request.

const user = await User.findOne({ email: req.body.email });

If user is not exists, we’ll create an error. These are similar to my previous articles, so I don’t explain.

const resetToken = user.getResetPasswordToken();await user.save({ validateBeforeSave: false})

With this, we have two variable in database, they will destroy when we reset password.

We’ll create a message like this:

`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}`

So when emails gone, this will explain why it gone.

Now, we create a try catch.

try {await sendEmail({email: user.email,subject: 'Password reset token',message})res.status(200).json({ success: true, data:'Email sent' });} catch (error) {console.log(err);user.getResetPasswordToken = undefined;user.resetPasswordExpire = undefined;await user.save({ validateBeforeSave: false })return next(new ErrorResponse('Email could not be sent', 500))}

This method done, finally we’ll create resetPassword function. We ‘ll get hashed token with:

const resetPasswordToken = crypto.createHash('sha256').update(req.params.resetToken).digest('hex');

We’ll create an user, and use findOne method. In this:

const user = await User.findOne({resetPasswordToken,resetPasswordExpire: { $gt: Date.now() }});

If user not exists, we’ll create an error. Now, we need set new password, and destroy resetPasswordToken and resetPasswordExpire, then save user and sendTokenResponse:

user.password = req.body.password;user.resetPasswordToken = undefined;user.resetPasswordExpire = undefined;await user.save();const id = user.getId();sendTokenResponse(user, 200, res, id);

forgotPassword looks like:

forgotPassword

resetPassword looks like:

resetPassword

In routes/auth.js, we’ll require forgotPassword and resetPassword functions and use it down in getMe function:

router.post(‘/forgotPassword’, forgotPassword);
router.put(‘/resetPassword/:resetToken’, resetPassword);

Finally, in Postman, we’ll create a Post request, like

http://localhost:5000/forgotPassword

and send an email exists and look that mail box, you can see an email. Then we’ll go back Postman, write:

http://localhost:5000/resetPassword/:resetToken

and send put request, you’ll see user data, token and id.

That’s it! This artical finished, thanks for reading!

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To stay up to date on other topics, follow us on LinkedIn. https://www.linkedin.com/company/nerdfortech

Serap Baysal

Written by

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To stay up to date on other topics, follow us on LinkedIn. https://www.linkedin.com/company/nerdfortech

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store