Open In App
Related Articles

How to reset / change password in Node.js with Passport.js ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Resetting/ Changing passwords with Passport.js is a bit complex process but In this article, you will learn to do this in a very easy and understandable way.

Syntax:

requiredUser.changePassword(oldpassword, 
    newpassword, callback function)

where the requiredUser is the user whose password we want to change.

Approach: We are going to use the passport changePassword method which takes two arguments and a callback function, the first argument is the old password and the second argument is the new password.

requiredUser.changePassword(oldpassword, 
    newpassword, function(err) {
    
})

Implementation: Below is the step-by-step implementation of the above approach.

Let’s create a simple Node.js application that uses the passport to register users and save their data inside MongoDB using mongoose. You can use whatever you want to store users’ data like MySQL or a simple array. In this article, we are going to use MongoDB.

Inside this Application, we have created a changepassword route that takes input values from users such as username, old password, and new password.

Step 1: Initializes NPM: Create and Locate your project folder in the terminal & type the command

npm init -y

It initializes our node application & makes a package.json file.

Step 2: Install Dependencies: Locate your root project directory into the terminal and type the command

npm install express body-parser mongoose passport passportLocalMongoose

To install Express, Body Parser, Mongoose, Passport, and Passport Local Mongoose as dependencies inside your project.

Step 3: Create Server File: Create an ‘app.js’ file, inside this file require all Module, and create a constant ‘app’ for creating an instance of the express module, then use mongoose to connect with the local MongoDB database.

const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require("mongoose");
const passport = require("passport");
const passportLocalMongoose 
    = require("passport-local-mongoose");

const app = express();

mongoose.connect(
"mongodb://localhost:27017/passport-forget", {
   useNewUrlParser: true
});

Step 4: Now Initialise the passport, create a user schema, use passportLocalMongoose as a plugin to user schema, and create User constant which is used to create an instance of User and save it inside the MongoDB database.

app.use(passport.initialize());
const userSchema = new mongoose.Schema({
   username: String,
   password: String,
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);

Step 5: Now, let’s serialize and deserialize the user using the passport module.

passport.use(User.createStrategy());
passport.serializeUser(function (user, done) {
  done(null, user.id);
});
passport.deserializeUser(function (id, done) {
  User.findById(id, function (err, user) {
      done(err, user);
  });
});

Step 6: Create a register route for registering users and changepassword route that takes input values from users such as username, old password, and new password. 

app.get('/register', function (req, res) {
   res.sendFile('register.html', {
       root: __dirname
   });
});

app.get('/changepassword', function (req, res) {
   res.sendFile('changepassword.html', {
       root: __dirname
   });
});

Step 7: Now, create a register route for registering the user by using the passport register method which takes two-parameter, username and password, and a callback that throws an error or success message.

app.post('/register', function (req, res) {
   User.register({
       username: req.body.username
   }, req.body.password, function (err) {
       if (err) {
           res.send(err);
       } else {
           res.send('successfully registered')
       }
   });
});

Step 8: As we already see in the approach part we have to use first find the user which password we want to change, then use changePassword with the two-parameter, old password and the new password, and a callback which sends an error if there is any or send success message.

app.post('/changepassword', function (req, res) {
   User.findByUsername(req.body.username, (err, user) => {
       if (err) {
           res.send(err);
       } else {
           user.changePassword(req.body.oldpassword, 
           req.body.newpassword, function (err) {
               if (err) {
                   res.send(err);
               } else {
                   res.send('successfully change password')
               }
           });
       }
   });
});

Complete Code:

app.js

Javascript

const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require("mongoose");
const passport = require("passport");
const passportLocalMongoose 
    = require("passport-local-mongoose");
  
mongoose.connect(
    useNewUrlParser: true
});
  
const app = express()
  
app.use(passport.initialize());
  
const userSchema = new mongoose.Schema({
    username: String,
    password: String,
});
  
userSchema.plugin(passportLocalMongoose);
  
const User = new mongoose.model("User", userSchema);
  
passport.use(User.createStrategy());
  
passport.serializeUser(function (user, done) {
    done(null, user.id);
});
  
passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});
  
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}))
  
app.get('/register', function (req, res) {
    res.sendFile('register.html', {
        root: __dirname
    });
});
  
app.get('/changepassword', function (req, res) {
    res.sendFile('changepassword.html', {
        root: __dirname
    });
});
  
app.post('/register', function (req, res) {
    User.register({
        username: req.body.username
    }, req.body.password, function (err) {
        if (err) {
            res.send(err);
        } else {
            res.send('successfully registered')
        }
    });
});
  
app.post('/changepassword', function (req, res) {
    User.findByUsername(req.body.username, (err, user) => {
        if (err) {
            res.send(err);
        } else {
            user.changePassword(req.body.oldpassword, 
            req.body.newpassword, function (err) {
                if (err) {
                    res.send(err);
                } else {
                    res.send('successfully change password')
                }
            });
        }
    });
});
  
  
app.listen(3000);

                    

register.html

HTML

<!DOCTYPE html>
<html lang="en">
    
<head>
    <title>Document</title>
</head>
<body>
    <form action="/register" method="post">
        <input type="text" 
            placeholder="Username" name="username">
        <input type="password" 
            placeholder="Password" name="password">
        <button type="submit">Register</button>
    </form>
</body>
    
</html>

                    

changepassword.html

HTML

<!DOCTYPE html>
<html lang="en">
    
<head>
    <title>Document</title>
</head>
    
<body>
    <form action="/changepassword" method="post">
        <input type="text" placeholder="Username"
            name="username">
        <input type="password" 
            placeholder="Old Password" 
            name="oldpassword">
        <input type="password" 
            placeholder="New Password" 
            name="newpassword">
        <button type="submit">
              Change Password
         </button>
    </form>
</body>
    
</html>

                    

Output:

 



Last Updated : 20 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads