DEV Community

Cover image for Forgot password in node js using mongodb
CoderLegion
CoderLegion

Posted on • Updated on • Originally published at kodlogs.com

Forgot password in node js using mongodb

In this article, we'll proceed to the SignUp application. In this part, I'll expound on failed to remember passwords, sending messages with nodemailer, and reset passwords. In the event that you prepared, we should start!

As a matter of first importance, in the past part, I utilized mailgun, not nodemailer. However, when I looked about sending email strategies, I see nodemailer and wanna use it only for the distinction.

For reset secret word, we need a String variable in the User model. I make a Date variable as well, yet I don't utilize it so you can pass it. The String variable is named resetPasswordToken. We need a bundle called crypto, we'll require it on top.

In the User model, we'll make a strategy named getResetPasswordToken, in this factor:

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



**bold**

Presently, we need to hash token and set to resetPasswordToken field, set terminate and return resetToken. The entire code about getResetPasswordToken is here: 

For getting sends I will utilize mailgun, make a record and get a few definitions. 

We'll make a middleware named sendEmail. In this, we need nodemailer, so we'll stop the worker and introduce nodemailer with: 

npm introduce nodemailer 
We'll require it, top of middleware. 
On the nodemailer site, we'll duplicate these codes: 
I change a few sections as I need. In createTransport, you can see host, port and auth are unique in relation to the site. For these, we'll go to .env record and make SMTP_HOST, SMTP_PORT, SMTP_EMAIL, SMTP_PASSWORD. In mailgun, we can see these parts, I don't share them obviously. 

Presently, we need a strategy named forgotPassword. With this strategy, we'll take an email and send a solicitation.



Enter fullscreen mode Exit fullscreen mode

const client = anticipate User.findOne({ email: req.body.email });





In the event that the client doesn't exist, we'll make a blunder. These are like my past articles, so I don't clarify.



Enter fullscreen mode Exit fullscreen mode

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




With this, we have two factors in the data set, they will annihilate when we reset the secret key. 

We'll make a message like this: 

'You are accepting this email since you (or another person) has mentioned the reset of a secret word. Kindly make a PUT solicitation to: \n\n ${resetUrl}' 

So when messages are gone, this will clarify why it has gone. 

Presently, we make an attempt get. 

attempt {await sendEmail({email: user.email,subject: 'Secret word reset token',message})res.status(200).json({ achievement: valid, data:'Email sent' });} get (mistake) {console.log(err);user.getResetPasswordToken = undefined;user.resetPasswordExpire = undefined;await user.save({ validateBeforeSave: bogus })return next(new ErrorResponse('Email couldn't be sent', 500))} 

This strategy is done, at long last, we'll make the resetPassword work. We'll get hashed token with: 

const resetPasswordToken = crypto.createHash('sha256').update(req.params.resetToken).digest('hex'); 
We'll make a client, and utilize the findOne technique. In this: 

const client = anticipate User.findOne({resetPasswordToken,resetPasswordExpire: { $gt: Date.now() }}); 
On the off chance that the client not exists, we'll make a mistake. Presently, we need to set another secret key, and obliterate resetPasswordToken and resetPasswordExpire, at that point save the client and sendTokenResponse:



Enter fullscreen mode Exit fullscreen mode

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



In courses/auth.js, we'll require forgotPassword and resetPassword capacities and use them down in the getMe work:


Enter fullscreen mode Exit fullscreen mode

router.post('/forgotPassword', forgotPassword);

router.put('/resetPassword/:resetToken', resetPassword);



Hope you liked the post then like, share and comment.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)