Forgot Password Email Notification Using Node js

Introduction
 
Before starting the code you need an account in send grid which will send the notification to your mail. Generally we use email notifications for forget passwords in your applications. You can follow the below steps to get the task done and if you have any queries please leave a comment below.
 
Step 1

We require a few modules from npm to send the notification through the mail.
  • npm install formidable
  • npm install crypto 
  • npm install async
  • npm install nodemailer
Step 2

In my router.js file the following code will be present  
  1. app.route('/forgotpasswordResponse')  
  2. .post(userCtrl.forgotpasswordResponse);  
When I run my services and hit the above Url  from postman it will take you to the forgotpasswordResponse method. We are using post method in postman where we need to pass Email id as parameter
 
Step 3

In forgotpasswordResponse my code is somthing like this, 
  1. exports.forgotpasswordResponse = function(req, res, next) {  
  2.   
  3.     var input=req.body;  
  4.     //console.log(input);  
  5.     async.waterfall([  
  6.         function(done) {  
  7.             crypto.randomBytes(20, function(err, buf) {  
  8.                 var token = buf.toString('hex');  
  9.                 done(err, token);  
  10.             });  
  11.         },  
  12.         function(token, done) {  
  13.             MongoClient.connect(url, function(err, db){   
  14.                 var dbo = db.db("Here is your DB Name");  
  15.                 //console.log(req.body.Email);  
  16.                 var query = { Email : req.body.Email };  
  17.                 dbo.collection('CLC_User').find(query).toArray(function(err,result){  
  18.                     if(result.length == 0){  
  19.                         req.flash('error''No account with that email address exists.');  
  20.                     }  
  21.                     var myquery = { Email: result[0].Email };  
  22.                     var newvalues = { $set: {resetPasswordToken: token, resetPasswordExpires: Date.now() + 3600000 }};  
  23.                     dbo.collection("CLC_User").updateOne(myquery, newvalues, function(err, res) {  
  24.                         if (err) throw err;  
  25.                         console.log("1 document updated");  
  26.                     });  
  27.                       
  28.   
  29.                    // console.log(result[0].Email);  
  30.                     done(err, token, result);  
  31.                 });  
  32.             });  
  33.         },  
  34.         function(token, result, done,Username,password) {  
  35.             var emailVal = result[0].Email;  
  36.             console.log(emailVal);  
  37.             var Username="";  
  38.             var password="";  
  39.             MongoClient.connect(url, function(err, db){   
  40.             var dbo = db.db("Here willbe your db name");  
  41.             dbo.collection('Accountsettings').find().toArray(function(err,result){  
  42.                 if (err) throw err;  
  43.                 Username=result[0].UserName;  
  44.                 password=result[0].Password;  
  45.                // console.log(Username);  
  46.                // console.log(password);  
  47.                    // res.json({status : 'success', message : 'Records found', result : result});  
  48.               
  49.   
  50.             // console.log(Username);  
  51.             var smtpTransport = nodemailer.createTransport({  
  52.                 service: 'SendGrid',  
  53.                 auth: {  
  54.                   user: Username,  
  55.                   pass: password  
  56.                 }  
  57.               });  
  58.   
  59.             const mailOptions = {  
  60.                 to: emailVal,  
  61.                 from: 'passwordreset@demo.com',  
  62.                 subject: 'Node.js Password Reset',  
  63.                 text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +  
  64.                     'Please click on the following link, or paste this into your browser to complete the process:\n\n' +  
  65.                     'http://' + req.headers.host + '/reset/' + token + '\n\n' +  
  66.                     'If you did not request this, please ignore this email and your password will remain unchanged.\n'  
  67.             };  
  68.             smtpTransport.sendMail(mailOptions, function(err) {                 
  69.                 console.log("HI:"+emailVal);  
  70.                 res.json({status : 'success', message : 'An e-mail has been sent to ' + emailVal + ' with further instructions.'});              
  71.                 done(err, 'done');  
  72.             });  
  73.         })  
  74.         });  
  75.         }  
  76.           
  77.     ], function(err) {  
  78.         if (err) return next(err);  
  79.           
  80.     });  
  81. }  
In my case  I am using waterfall methologie for this method with will execute acyn in method,

In the above code initially I am updating the collection with resetPasswordToken and resetPasswordExpires using email id and getting my send  grid credentials from db form  Accountsettings collections. If you can observe in mailOptions text "req.headers.host" will be the link which will get in you mail with token.
 
Step 4

When you click on Url which you got in the email it will redirect you to another page to set the password.

Again we need to go to route.js and the code will be some thing like this. It will take to html page which we can reset the password, 
  1. app.route('/reset/:token')  
  2. .get(Resetpassword.resetpasswordResponse);   
This time I am passing the token which I stored in db as "resetPasswordToken". Now it will take you to resetpasswordResponse method and the code is below,
  1. exports.resetpasswordResponse = function(req, res) {  
  2.     console.log("welcome");  
  3.     MongoClient.connect(url, function(err, db){  
  4.         var dbo = db.db("Here is you db");  
  5.         dbo.collection('CLC_User').findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {  
  6.             if (!user) {  
  7.                 res.json({message: 'Password reset token is invalid or has expired.'});  
  8.             }else{  
  9.                 console.log("coming");  
  10.                 fs.readFile("api/Controllers/resetpassword.html"function (error, data) {  
  11.                     console.log("its working");  
  12.                     if (error) {  
  13.                         console.log(error);  
  14.                         res.writeHead(404);  
  15.                         res.write('Contents you are looking are Not Found');  
  16.                     } else {  
  17.                         //res.writeHead(200, { 'Content-Type': 'text/html' });  
  18.                         res.write(data);  
  19.                     }  
  20.                     res.end();  
  21.                 });  
  22.             }  
  23.         });  
  24.     });  
  25. }  
Your html code in resetpassword.html will be like this,
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <title>Reset Password</title>  
  5. <script src="https://code.jquery.com/jquery-1.12.4.js"></script>  
  6. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
  7. </head>  
  8. <body>  
  9.     <h4 class="postdata" style="text-align:center;"></h4>  
  10.     <div class="main-agileits">  
  11.         <h2 class="sub-head">Reset Password</h2>  
  12.         <div class="sub-main">      
  13.             <form method="post">  
  14.                 <span class="senddata"></span><br><br>  
  15.                       
  16.                 <input placeholder="Enter Password" name="password" class="password" type="password" required=""><br><br>  
  17.   
  18.                 <input placeholder="Confirm Password" name="confirmpassword" class="confirmpassword" type="password" required=""><br><br>  
  19.                   
  20.                 <input type="submit" name ="submit" value="RESET PASSWORD">  
  21.                   
  22.             </form>  
  23.         </div>  
  24.     </div>  
  25. </body>  
  26. </html>  
  27.   
  28.   
  29. <script type="text/javascript">  
  30.   
  31. $( document ).ready(function() {  
  32.     $("input[name='submit']").on("click"function(){  
  33.         $(".senddata").html("");  
  34.         var url = window.location.href;  
  35.         var password = $('.password').val();  
  36.         var confirmpassword = $('.confirmpassword').val();  
  37.   
  38.         if( password == confirmpassword){  
  39.             $.post(url,{Password : password},function(result,status){  
  40.             var msg = result.status;  
  41.             var msgdata = result.message;  
  42.             if(msg == "success"){  
  43.                 $(".postdata").html(msgdata);  
  44.                 $(".main-agileits").css("display","none")  
  45.             }else{  
  46.                 return false;  
  47.             }  
  48.         });  
  49.         }else{  
  50.             $(".senddata").html("Passwords did not match");  
  51.         }         
  52.         return false;  
  53.     });  
  54.       
  55. });  
  56.   
  57. </script> 
 the next step is send the Email notification after changing the password.The code is
 
  1. app.route('/reset/:token')  
  2.   .post(setpassword.setpasswordResponsemail);  
 
 
  1. exports.setpasswordResponsemail = function(req, res) {  
  2.     async.waterfall([  
  3.         function(done) {  
  4.             MongoClient.connect(url, function(err, db){  
  5.                 var dbo = db.db("Your Db name goes here");   
  6.                 dbo.collection('CLC_User').findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {  
  7.                     if (!user) {  
  8.                         res.json({message: 'Password reset token is invalid or has expired.'});  
  9.                     }  
  10.                     //console.log(user);  
  11.                     var myquery = { resetPasswordToken: req.params.token };  
  12.                     var newvalues = { $set: {Password: req.body.Password,resetPasswordToken: undefined, resetPasswordExpires: undefined, modifiedDate : Date(Date.now()) }};  
  13.                     dbo.collection("CLC_User").updateOne(myquery, newvalues, function(err, result) {  
  14.                         if (err) throw err;  
  15.                         //console.log("result ======" + result);  
  16.                         console.log("1 document updated");  
  17.                     });  
  18.                     done(err, user);  
  19.                 });  
  20.             });  
  21.         },  
  22.         function(user, done) {  
  23.             MongoClient.connect(url, function(err, db){   
  24.                 var dbo = db.db("Your db name goes here");  
  25.                 var Username="";  
  26.                 var password="";  
  27.                 dbo.collection('Accountsettings').find().toArray(function(err,result){  
  28.                     if (err) throw err;  
  29.                     Username=result[0].UserName;  
  30.                     password=result[0].Password;  
  31.                 })  
  32.             })  
  33.             var smtpTransport = nodemailer.createTransport({  
  34.                 service: 'SendGrid',  
  35.                 auth: {  
  36.                     user: Username,  
  37.                     pass: password  
  38.                 }  
  39.             });  
  40.             var mailOptions = {  
  41.                 to: user.Email,  
  42.                 from: 'passwordreset@demo.com',  
  43.                 subject: 'Your password has been changed',  
  44.                 text: 'Hello,\n\n' +  
  45.                     'This is a confirmation that the password for your account ' + user.Email + ' has just been changed.\n'  
  46.             };  
  47.             smtpTransport.sendMail(mailOptions, function(err) {  
  48.                 res.json({status : 'success', message : 'Success! Your password has been changed.'});  
  49.                 done(err);  
  50.             });  
  51.         }  
  52.     ], function(err) {  
  53.         if (err) return err;  
  54.     });  

 
 
Note

Hope this code will help someone who really needs  it. Thank you.