Implement Reset Password in Node.js with 4 step

Implement Reset Password in Node.js with 4 step

When we send the forgot password email, you can Reset Password with Node.js easy

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

app.route('/forgotpasswordResponse')  
.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,

exports.forgotpasswordResponse = function(req, res, next) {  
  
    var input=req.body;  
    //console.log(input);  
    async.waterfall([  
        function(done) {  
            crypto.randomBytes(20, function(err, buf) {  
                var token = buf.toString('hex');  
                done(err, token);  
            });  
        },  
        function(token, done) {  
            MongoClient.connect(url, function(err, db){   
                var dbo = db.db("Here is your DB Name");  
                //console.log(req.body.Email);  
                var query = { Email : req.body.Email };  
                dbo.collection('CLC_User').find(query).toArray(function(err,result){  
                    if(result.length == 0){  
                        req.flash('error', 'No account with that email address exists.');  
                    }  
                    var myquery = { Email: result[0].Email };  
                    var newvalues = { $set: {resetPasswordToken: token, resetPasswordExpires: Date.now() + 3600000 }};  
                    dbo.collection("CLC_User").updateOne(myquery, newvalues, function(err, res) {  
                        if (err) throw err;  
                        console.log("1 document updated");  
                    });  
                      
  
                   // console.log(result[0].Email);  
                    done(err, token, result);  
                });  
            });  
        },  
        function(token, result, done,Username,password) {  
            var emailVal = result[0].Email;  
            console.log(emailVal);  
            var Username="";  
            var password="";  
            MongoClient.connect(url, function(err, db){   
            var dbo = db.db("Here willbe your db name");  
            dbo.collection('Accountsettings').find().toArray(function(err,result){  
                if (err) throw err;  
                Username=result[0].UserName;  
                password=result[0].Password;  
               // console.log(Username);  
               // console.log(password);  
                   // res.json({status : 'success', message : 'Records found', result : result});  
              
  
            // console.log(Username);  
            var smtpTransport = nodemailer.createTransport({  
                service: 'SendGrid',  
                auth: {  
                  user: Username,  
                  pass: password  
                }  
              });  
  
            const mailOptions = {  
                to: emailVal,  
                from: '[email protected]',  
                subject: 'Node.js Password Reset',  
                text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +  
                    'Please click on the following link, or paste this into your browser to complete the process:\n\n' +  
                    'http://' + req.headers.host + '/reset/' + token + '\n\n' +  
                    'If you did not request this, please ignore this email and your password will remain unchanged.\n'  
            };  
            smtpTransport.sendMail(mailOptions, function(err) {                 
                console.log("HI:"+emailVal);  
                res.json({status : 'success', message : 'An e-mail has been sent to ' + emailVal + ' with further instructions.'});              
                done(err, 'done');  
            });  
        })  
        });  
        }  
          
    ], function(err) {  
        if (err) return next(err);  
          
    });  
}  

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,

app.route('/reset/:token')  
.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,

exports.resetpasswordResponse = function(req, res) {  
    console.log("welcome");  
    MongoClient.connect(url, function(err, db){  
        var dbo = db.db("Here is you db");  
        dbo.collection('CLC_User').findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {  
            if (!user) {  
                res.json({message: 'Password reset token is invalid or has expired.'});  
            }else{  
                console.log("coming");  
                fs.readFile("api/Controllers/resetpassword.html", function (error, data) {  
                    console.log("its working");  
                    if (error) {  
                        console.log(error);  
                        res.writeHead(404);  
                        res.write('Contents you are looking are Not Found');  
                    } else {  
                        //res.writeHead(200, { 'Content-Type': 'text/html' });  
                        res.write(data);  
                    }  
                    res.end();  
                });  
            }  
        });  
    });  
}  

Your html code in resetpassword.html will be like this,

<!DOCTYPE html>  
<html>  
<head>  
<title>Reset Password</title>  
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>  
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
</head>  
<body>  
    <h4 class="postdata" style="text-align:center;"></h4>  
    <div class="main-agileits">  
        <h2 class="sub-head">Reset Password</h2>  
        <div class="sub-main">      
            <form method="post">  
                <span class="senddata"></span><br><br>  
                      
                <input placeholder="Enter Password" name="password" class="password" type="password" required=""><br><br>  
  
                <input placeholder="Confirm Password" name="confirmpassword" class="confirmpassword" type="password" required=""><br><br>  
                  
                <input type="submit" name ="submit" value="RESET PASSWORD">  
                  
            </form>  
        </div>  
    </div>  
</body>  
</html>  
  
  
<script type="text/javascript">  
  
$( document ).ready(function() {  
    $("input[name='submit']").on("click", function(){  
        $(".senddata").html("");  
        var url = window.location.href;  
        var password = $('.password').val();  
        var confirmpassword = $('.confirmpassword').val();  
  
        if( password == confirmpassword){  
            $.post(url,{Password : password},function(result,status){  
            var msg = result.status;  
            var msgdata = result.message;  
            if(msg == "success"){  
                $(".postdata").html(msgdata);  
                $(".main-agileits").css("display","none")  
            }else{  
                return false;  
            }  
        });  
        }else{  
            $(".senddata").html("Passwords did not match");  
        }         
        return false;  
    });  
      
});  
  
</script> 

The next step is send the Email notification after changing the password.The code is

app.route('/reset/:token')  
  .post(setpassword.setpasswordResponsemail);  
exports.setpasswordResponsemail = function(req, res) {  
    async.waterfall([  
        function(done) {  
            MongoClient.connect(url, function(err, db){  
                var dbo = db.db("Your Db name goes here");   
                dbo.collection('CLC_User').findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {  
                    if (!user) {  
                        res.json({message: 'Password reset token is invalid or has expired.'});  
                    }  
                    //console.log(user);  
                    var myquery = { resetPasswordToken: req.params.token };  
                    var newvalues = { $set: {Password: req.body.Password,resetPasswordToken: undefined, resetPasswordExpires: undefined, modifiedDate : Date(Date.now()) }};  
                    dbo.collection("CLC_User").updateOne(myquery, newvalues, function(err, result) {  
                        if (err) throw err;  
                        //console.log("result ======" + result);  
                        console.log("1 document updated");  
                    });  
                    done(err, user);  
                });  
            });  
        },  
        function(user, done) {  
            MongoClient.connect(url, function(err, db){   
                var dbo = db.db("Your db name goes here");  
                var Username="";  
                var password="";  
                dbo.collection('Accountsettings').find().toArray(function(err,result){  
                    if (err) throw err;  
                    Username=result[0].UserName;  
                    password=result[0].Password;  
                })  
            })  
            var smtpTransport = nodemailer.createTransport({  
                service: 'SendGrid',  
                auth: {  
                    user: Username,  
                    pass: password  
                }  
            });  
            var mailOptions = {  
                to: user.Email,  
                from: '[email protected]',  
                subject: 'Your password has been changed',  
                text: 'Hello,\n\n' +  
                    'This is a confirmation that the password for your account ' + user.Email + ' has just been changed.\n'  
            };  
            smtpTransport.sendMail(mailOptions, function(err) {  
                res.json({status : 'success', message : 'Success! Your password has been changed.'});  
                done(err);  
            });  
        }  
    ], function(err) {  
        if (err) return err;  
    });  
} 

I hope you enjoyed this tutorial and found it helpful. If you have any questions, or suggestions on what we should cover next, please let us know in the comments below. Thank you !

Hashing Passwords with Node.js and NPM Bcrypt Library

Hashing Passwords with Node.js and NPM Bcrypt Library

In this tutorial, we will learn to use NPM bcryptjs library to hash and compare the passwords in Node.js

In this tutorial, we will learn to use NPM bcryptjs library to hash and compare the passwords in Node.

To create a secure application, it is always considered a safe practice not to store a user’s password in the database in plain text format. If not in plain text format, then what else we can do?

Here is the solution, generate a hash (complex string and numbers) and store that hash in the database. You can decipher your hashed password later by using the comparing method.

Let’s assume if there was a breach in your database, and all your stored passwords were leaked. Then, you are at significant risk, and password hashing is the best one-way encryption technique to secure the passwords.

In this method, you do not store users’ passwords in the database in its original form. Instead, a password is stored in a complex combination of text and unique characters; this is known as a password hash method.

A hacker can not easily decipher an adequately hashed password. Hackers will get frustrated because it will take lots of time and effort to decrypt the password.

In this tutorial, we will learn how to install and correctly hash a password in node.js.

We will take the help of the NPM BcryptJs package, and it is a widely used encryption module available nowadays via NPM.

Before we begin, you must have Node.js configured in your machine. If not, then you can check out how to install Node in your system tutorial.

Install bcryptjs Npm Module

To get started i assume you already have a Node.js project setup along with Express, and MongoDB.

Run one of the command based on your package manage.

# npm
npm install bcryptjs --save

# yarn
yarn add bcryptjs

Now, once bcryptjs successfully installed. We are ready to go ahead!

Hash A Password with Bcrytp Js

To get started with hashing the password we need node server configuration. In the app.js file, we imported express, bodyParser, mongoose and bcrytpjs module. We defined the MongoDB database connection, user schema and two REST APIs for registering and signing in the user.

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');

// Express APIs
const api = require('./routes/auth.routes');

// MongoDB conection
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/nodedb", {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('Database connected')
},
    error => {
        console.log("Database can't be connected: " + error)
    }
)

// Express settings
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cors());

app.use('/api', api)

// Define PORT
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
    console.log('Connected to port ' + port)
})

// Express error handling
app.use((req, res, next) => {
    setImmediate(() => {
        next(new Error('Something went wrong'));
    });
});

app.use(function (err, req, res, next) {
    console.error(err.message);
    if (!err.statusCode) err.statusCode = 500;
    res.status(err.statusCode).send(err.message);
});

Hashing a password is very simple, the first argument in the bcrypt.hashSync() method is the password which we are getting from req.body middleware. The second argument is the number of rounds which we set to 10 to generate a salt.

// routes/auth.routes.js

const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const router = express.Router();
const userSchema = require("../models/User");

// Sign-up
router.post("/signup", (req, res, next) => {
    bcrypt.hash(req.body.password, 10).then((hash) => {
        const user = new userSchema({
            name: req.body.name,
            email: req.body.email,
            password: hash
        });
        user.save().then((response) => {
            res.status(201).json({
                message: "User successfully created!",
                result: response
            });
        }).catch(error => {
            res.status(500).json({
                error: error
            });
        });
    });
});

So we are hashing the password when the user makes the signup call after that we are creating a user instance and saving the user data along with the password in the MongoDB database.

Verify or Compare The Password with Bcrypt

When the user logs in the app, API will check the if the email exists in the database with the help of userSchema.findOne() method. Then, we will validate the stored password with the help of bcrypt.compareSync() method. It takes two passwords as an argument stored password and user-entered password.

// routes/auth.routes.js

const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const router = express.Router();
const userSchema = require("../models/User");

// Sign-in
router.post("/signin", (req, res, next) => {
    let getUser;
    userSchema.findOne({
        email: req.body.email
    }).then(user => {
        if (!user) {
            return res.status(401).json({
                message: "Authentication failed"
            });
        }
        return bcrypt.compare(req.body.password, user.password);
    }).then(response => {
        if (!response) {
            return res.status(401).json({
                message: "Authentication failed"
            });
        }
    }).catch(err => {
        return res.status(401).json({
            message: "Authentication failed"
        });
    });
});
Conclusion

We have seen how to store the password in the database securely by making the REST API call with Node/Express.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node

How to Install Node.js with npm on Debian 10

How to Install Node.js with npm on Debian 10

Install Node.js with npm on Debian 10 In this tutorial, we are going to learn how to install Node.js with npm on Debian 10

Table of Contents

Install Node.js with npm on Debian 10

In this tutorial, we are going to learn how to install Node.js with npm on Debian 10. Node.js is the opensource JavaScript Run-time environment for server-side execution of JavaScript code. Node.js built on Chrome’s V8 JavaScript engine so it can be used to build different types of server-side applications.

Where npm stands for Node Package Manager which is the default package manager for Node.js. npm is the world’s largest software registry for Node.js packages with thousands of packages available.

In this tutorial we will install Node.js in following two ways:

  1. Install Node.js and npm using Debian repository
  2. Install Node.js and npm using nvm
  3. Install Node.js from the NodeSource repository.

1. Install Node.js and npm using Debian repository

First, Update Debian apt package manager index by running the following command.

sudo apt update

Install Node.js from Debian global repository by typing

sudo apt install node

Confirm the installation of Node.js by typing

node --version

Install npm by running following command

sudo apt install npm

Confirm the installation of npm by typing

npm --version

2. Install Node.js and npm using nvm

NVM stands for Node Version Manager which is used to manage multiple Node.js versions. If you want to install or uninstall different versions of Node.js then NVM is there for you.

First, we will install NVM (Node Package Manager) on your system. So download the NVM installation script running the following command.

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

Check nvm version and confirm installation typing

node --version

Now install Node.js by using the following command.

nvm install node

Verify Node.js installation by typing

node --version

The output should be:

Output

v10.14.0

You can install multiple versions of Node.js. To do so type the following:

nvm install 8.14
nvm install --lts
nvm install 11.3

To list all the versions installed run following command.

nvm ls

You can change the current default version of Node.js by using the following command.

nvm use 8.14

To uninstall a Node.js version type following command

nvm uninstall 11.14

Install Node.js from NodeSource Repository

NodeSource company provides enterprise-grade node support also maintains the repository containing the latest version of Node.js.

To enable the NodeSource repository on your system run following command.

curl -sL https://deb.nodesource.com/setup_10.x | sudo bash -

NOTE: The latest LTS version of Node.js is 10.x if you want to install 8.x version then just replace setup_10.x with setup_8.x

Now install Node.js and npm package typing.

sudo apt install nodejs

Verify installation of Node.js and npm running following command

node --version
npm --version

Install Development Tools

Now install some packages needed for development by running following command

sudo apt install gcc g++ make

Uninstall Node.js and npm

Uninstall Node.js use following command

sudo apt remove nodejs npm
sudo apt autoremove

To uninstall node.js version using nvm type following command

nvm uninstall 10.14

Conclusion

You have successfully learned how to install Node.js with npm on Debian 10. If you have any queries don’t forget to comment below.