Login form using Node.js and MongoDB – GeeksforGeeks

Follow these simple steps to learn how to create a login form using Node.js and MongoDB. Login form allows users to login to the website after they have created their account using the signup form.

We will be using the following technologies:

Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features.It makes it easier to organize your application’s functionality with middle ware and routing; it adds helpful utilities to Node.js’s HTTP objects;it facilitates the rendering of dynamic HTTP objects.

mongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format). 

Passport is authentication middleware for Node. js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

Steps to create project and install required module:

Step 1: Start the project using the following command in your project folder

npm init

Step 2: Install the required modules using following command

npm install express
npm install ejs
npm install mongoose
npm install body-parser
npm install express-session
npm install passport passport-local 
npm install passport-local-mongoose 

Step 3: Create two folders inside the project directory using the following command

mkdir model
mkdir views

Step 4: Create another file named app.js inside project directory

touch app.js

Step 5: Navigate inside model folder and create a file User.js which will contain our Schema

cd model
touch User.js

Step 6: Navigate inside views folder and create the following ejs files

cd views
touch home.ejs
touch login.ejs
touch secret.ejs
touch register.ejs

Step 7: Run the following command to ensure all modules are loaded 

npm install

After following the above mentioned steps your project structure should look like:

The package.json file should look like:

{
  "name": "express",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body": "^5.1.0",
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "mongoose": "^6.9.1",
    "parser": "^0.1.4",
    "passport": "^0.6.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^7.1.2"
  },
  "description": ""
}

Add the following code in App.js and User.js file

javascript




  

var express = require("express"),

    mongoose = require("mongoose"),

    passport = require("passport"),

    bodyParser = require("body-parser"),

    LocalStrategy = require("passport-local"),

    passportLocalMongoose = 

        require("passport-local-mongoose")

const User = require("./model/User");

var app = express();

  

mongoose.connect("mongodb://localhost/27017");

  

app.set("view engine", "ejs");

app.use(bodyParser.urlencoded({ extended: true }));

app.use(require("express-session")({

    secret: "Rusty is a dog",

    resave: false,

    saveUninitialized: false

}));

  

app.use(passport.initialize());

app.use(passport.session());

  

passport.use(new LocalStrategy(User.authenticate()));

passport.serializeUser(User.serializeUser());

passport.deserializeUser(User.deserializeUser());

  

  

app.get("/", function (req, res) {

    res.render("home");

});

  

app.get("/secret", isLoggedIn, function (req, res) {

    res.render("secret");

});

  

app.get("/register", function (req, res) {

    res.render("register");

});

  

app.post("/register", async (req, res) => {

    const user = await User.create({

      username: req.body.username,

      password: req.body.password

    });

    

    return res.status(200).json(user);

  });

  

app.get("/login", function (req, res) {

    res.render("login");

});

  

app.post("/login", async function(req, res){

    try {

        

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

        if (user) {

          

          const result = req.body.password === user.password;

          if (result) {

            res.render("secret");

          } else {

            res.status(400).json({ error: "password doesn't match" });

          }

        } else {

          res.status(400).json({ error: "User doesn't exist" });

        }

      } catch (error) {

        res.status(400).json({ error });

      }

});

  

app.get("/logout", function (req, res) {

    req.logout(function(err) {

        if (err) { return next(err); }

        res.redirect('/');

      });

});

  

  

  

function isLoggedIn(req, res, next) {

    if (req.isAuthenticated()) return next();

    res.redirect("/login");

}

  

var port = process.env.PORT || 3000;

app.listen(port, function () {

    console.log("Server Has Started!");

});



Javascript




  

const mongoose = require('mongoose')

const Schema = mongoose.Schema

const passportLocalMongoose = require('passport-local-mongoose');

var User = new Schema({

    username: {

        type: String

    },

    password: {

        type: String

    }

})

  

User.plugin(passportLocalMongoose);

  

module.exports = mongoose.model('User', User)



Add the following codes in the folder of views 

html




// home.ejs

<h1>This is home page</h1>

  

<li><a href="/register">Sign up!!</a></li>

<li><a href="/login">Login</a></li>

<li><a href="/logout">Logout</a></li>



HTML




// login.ejs

<h1>login</h1>

  

<form action="/login" method="POST">

    <input type="text" name="username"

        placeholder="username">

    <input type="password" name="password" 

        placeholder="password">

    <button>login</button>

</form>

  

<h1>This is home page</h1>

  

<li><a href="/register">Sign up!!</a></li>

<li><a href="/login">Login</a></li>

<li><a href="/logout">Logout</a></li>



HTML




// register.ejs

  

<h1> Sign up form </h1>

  

<form action="/register" method="POST">

    <input type="text" name="username" 

        placeholder="username">

    <input type="password" name="password" 

        placeholder="password">

    <button>Submit</button>

</form>

  

<h1>This is home page</h1>

  

<li><a href="/register">Sign up!!</a></li>

<li><a href="/login">Login</a></li>

<li><a href="/logout">Logout</a></li>



HTML




// secret.ejs

  

<h1>This is secret page</h1>

  

<img src=

"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210420155809/gfg-new-logo.png">

  

<h1>This is home page</h1>

  

<li><a href="/register">Sign up!!</a></li>

<li><a href="/login">Login</a></li>

<li><a href="/logout">Logout</a></li>



Steps to run the application

Step 1:To run the above code you should first have the mongoose server running

If you do not have the mongoose folder setup follow this article

After setting up mongoDB start the server using following command

mongod

Step 2: Type the following command in terminal of your project directory

node app.js

Step 3: Open your web browser and type the following address in the URL bar

http://localhost:3000/

Output:

Login form using Node.js and MongoDB

My Personal Notes

arrow_drop_up