Skip to content

CODEBUN

  • Home
  • Automation
    • Selenium Tutorial
    • Selenium Web Driver With Java
    • Selenium Web Driver With C#
    • Katalon studio
    • Puppeteer and Jest
  • Development
    • Java Tutorial
    • JSP Tutorial
    • Servlet Tutorial
    • Spring Tutorial
    • Hibernate Tutorial
    • Spring Boot with ReactJS
    • Angular JS
    • JS and HTML
    • C# Tutorial
    • ReactJS Tutorial
    • MERN Stack Development
    • Java web application Development tutorial
    • Database Tutorial
    • Android Tutorial
  • Projects
    • Java Projects
    • Spring Boot Projects
    • Project In Java
    • Project In Hibernate
    • Project in spring
    • Java web application Development tutorial
    • UML Diagrams
    • PHP Project
  • Programs
    • Java program
    • VB Program
    • C# Program
  • Interview Q&A
    • Placement Q&A
      • Computer || Programming
      • Maths
      • Reasoning
      • English
    • C Interview Questions and Answer
    • Data Structure Q & A
    • Operating System Interview Q&A
    • HTML and CSS Q&A
  • Downloads
Menu
  • Home
  • Automation
    • Selenium Tutorial
    • Selenium Web Driver With Java
    • Selenium Web Driver With C#
    • Katalon studio
    • Puppeteer and Jest
  • Development
    • Java Tutorial
    • JSP Tutorial
    • Servlet Tutorial
    • Spring Tutorial
    • Hibernate Tutorial
    • Spring Boot with ReactJS
    • Angular JS
    • JS and HTML
    • C# Tutorial
    • ReactJS Tutorial
    • MERN Stack Development
    • Java web application Development tutorial
    • Database Tutorial
    • Android Tutorial
  • Projects
    • Java Projects
    • Spring Boot Projects
    • Project In Java
    • Project In Hibernate
    • Project in spring
    • Java web application Development tutorial
    • UML Diagrams
    • PHP Project
  • Programs
    • Java program
    • VB Program
    • C# Program
  • Interview Q&A
    • Placement Q&A
      • Computer || Programming
      • Maths
      • Reasoning
      • English
    • C Interview Questions and Answer
    • Data Structure Q & A
    • Operating System Interview Q&A
    • HTML and CSS Q&A
  • Downloads
Search
Close this search box.
Search

Login and Registration in NodeJS, ExpressJS and mongoDB.

  • Bhupendra Patidar
  • January 13, 2018
  • MERN

Login and registration in NodeJS, Express with MongoDB. In this tutorial, we are performing the login and registration using the MERN stack. MongoDB as a database express js as a server tool and node js as a javascript framework.

The sessions will be created and managed using the express-session library. And to secure the user’s password we will use the Passport library.

Folder Structure:-

Libraries used

  • Express
  • Ejs
  • Body-parser
  • Express-session
  • Mongoose
  • Passport
  • Passport-local
  • Passport-local-mongoose

Login and registration in NodeJS with MongoDB

Step 1: Make Folder for the project and Setting up a server port

  • Create a folder named ‘AUTHENTICATION’
  • Open the terminal and cd into the AUTHENTICATION folder and hit command
PS D:\work\Codebun\Authentication>npm init
  • Install libraries using npm install library names
PS D:\work\Codebun\Authentication>npm install express

Create a file as app.js and require Express and ejs library.

Package JSON file

{
  "name": "authentication",
  "version": "1.0.0",
  "description": "User Login",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Hrushikesh",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "ejs": "^3.1.3",
    "express": "^4.17.1",
    "express-session": "^1.17.1",
    "mongoose": "^5.9.18",
    "passport": "^0.4.1",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^6.0.1"
  }
}

App.js

const express  =  require('express'),  
      app = express(),
//Listen On Server
app.listen(process.env.PORT ||3000,function (err) {
    if(err){
       console.log(err);
    }else {
    console.log("Server Started At Port 3000");  }});

Step 2: Setting up Pages using EJS

  • SetUp home page add links to login, register, and logout
  • The setting form on Login and Register
  • Setting up a user profile page.

Home Page

<h1> Home Page</h1>
<p><ul>
  <li><a href="/login">Login</a></li>
  <li><a href="/register">Register</a></li>
  <li><a href="/logout">Logout</a></li>
</ul></p>

Login Page

<h1>
    Login Page
</h1>
<form action="/login" method="POST">
    <label for="username">UserName</label>
    <input type="text" placeholder="username" id="xyz" name="username">
    <label for="password">Password</label>
    <input type="password" id="password" name="password">
    <button>Login</button>
</form>
<ul>
    <li><a href="/">Home</a></li>
    <li><a href="/register">SignUp</a></li>
</ul>

Registration Page

<h1>
    SignUp Page
</h1>
<form action="/register" method="POST">
    <label for="username">UserName</label>
    <input type="text" id="username" name="username">
    <label for="password">Password</label>
    <input type="password" id="password" name="password">
    <label for="phone">Mobile No:-</label>
    <input type="text" name="phone" id="phone">
    <label for="telephone">TelePhone No:-</label>
    <input type="text" name="telephone" id="telephone">
    <button>Submit</button>
</form>
<ul>
    <li><a href="/">Home</a></li>
    <li><a href="/login">login</a></li>
</ul>

User profile

<h1>
    User Profile
</h1>
<p>
    After Login the user will reach here.
</p>
<ul>
    <li><a href="/">Home</a></li>
    <li><a href="/logout">Logout</a></li>
</ul>

Step 3: Setting Up GET routes

  • Set Up the view engine to ejs.
  • Set the GET function to set up get routes for Home page, log in, Signup and User profile.
app.set("view engine","ejs");
//=======================
//      R O U T E S
//=======================
app.get("/", (req,res) =>{
    res.render("home");
})
app.get("/userprofile" ,(req,res) =>{
    res.render("userprofile");
})
//Auth Routes
app.get("/login",(req,res)=>{
    res.render("login");
});
app.get("/register",(req,res)=>{
    res.render("register");
});

Step 4: Setting Up Database and express session

  • Getting the mongoose Library
PS D:\work\Codebun\Authentication>npm install mongoose
  • Getting the express libraries
PS D:\work\Codebun\Authentication>npm install express-session
  • Connecting to the DATABASE.
  • Make a file name user.js in Models directory and import mongoose.
  • setup user Schema like user name, password, mobile number, and telephone number.
  • export the schema using module.exports
const mongoose = require("mongoose");
//In app.js
mongoose.connect("mongodb://localhost/auth_demo");
app.use(require("express-session")({
secret:"Any normal Word",//decode or encode session
    resave: false,          
    saveUninitialized:false    
}));

UserSchema

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const UserSchema = new mongoose.Schema({
    username:String,
    password:String,
    phone:Number,
    telephone:Number
}) ;
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User",UserSchema);

Step 5: Setting Up Passport and Strategy For signup

  • Importing remaining Libraries and Schema
  • Importing All passport related Routes
  • Initialize passport to use LocalStrategy
  • Creating Post routes for Login, Logout and Register
  • Creating MiddleWare
const express               =  require('express'),
      app                   =  express(),
      mongoose              =  require("mongoose"),
      passport              =  require("passport"),
      bodyParser            =  require("body-parser"),
      LocalStrategy         =  require("passport-local"),
      passportLocalMongoose =  require("passport-local-mongoose"),
      User                  =  require("./models/user");


//Connecting database
mongoose.connect("mongodb://localhost/auth_demo");

app.use(require("express-session")({
    secret:"Any normal Word",       //decode or encode session
    resave: false,          
    saveUninitialized:false    
}));

passport.serializeUser(User.serializeUser());       //session encoding
passport.deserializeUser(User.deserializeUser());   //session decoding
passport.use(new LocalStrategy(User.authenticate()));
app.set("view engine","ejs");
app.use(bodyParser.urlencoded(
      { extended:true }
))
app.use(passport.initialize());
app.use(passport.session());

//=======================
//      R O U T E S
//=======================

app.get("/", (req,res) =>{
    res.render("home");
})

app.get("/userprofile",isLoggedIn ,(req,res) =>{
    res.render("userprofile");
})
//Auth Routes
app.get("/login",(req,res)=>{
    res.render("login");
});

app.post("/login",passport.authenticate("local",{
    successRedirect:"/userprofile",
    failureRedirect:"/login"
}),function (req, res){

});

app.get("/register",(req,res)=>{
    res.render("register");
});

app.post("/register",(req,res)=>{
    
    User.register(new User({username: req.body.username,phone:req.body.phone,telephone: req.body.telephone}),req.body.password,function(err,user){
        if(err){
            console.log(err);
            res.render("register");
        }
    passport.authenticate("local")(req,res,function(){
        res.redirect("/login");
    })    
    })
})

app.get("/logout",(req,res)=>{
    req.logout();
    res.redirect("/");
});

function isLoggedIn(req,res,next) {
    if(req.isAuthenticated()){
        return next();
    }
    res.redirect("/login");
}


//Listen On Server


app.listen(process.env.PORT ||3000,function (err) {
    if(err){
        console.log(err);
    }else {
        console.log("Server Started At Port 3000");
    }
      
});

DEMO

How to convert JSON data in HTML table

 

It is this type of data that is usually packaged today in game Poki projects in order to increase the effectiveness of the implementation and storage of information at a subconscious level.

PrevPreviousHow to convert JSON Data Dynamically to HTML Table using jQuery
NextWebpack tutorial || How to configure Webpack.config.js.Next

Recent Post

How to Explain Your Automation Testing Project in an Interview

December 1, 2024

Automation Testing Interview Questions for Wait in Selenium C Sharp

December 1, 2024

Automation Task: Extracting Product Names and Ratings with Selenium in C#

November 25, 2024

Space Booking Project in java using JSP and Servlet with source code

November 23, 2024

Design Test Automation Framework using Java, Selenium, TestNG, POM

August 1, 2024

Bug Reporting Project using Spring Boot, Hibernate, JPA and Mysql

July 8, 2024

Cannot find the declaration of element ‘project’ in Pom.xml

May 8, 2024

Failed to configure a DataSource: ‘url’ attribute is not specified

May 8, 2024

Solve “Non-resolvable parent POM” Error in pom.xml with Spring Boot 3

May 8, 2024

JSP and Servlet Project Configuration Tutorial

May 2, 2024

CODEBUN

  • jcodebun@gmail.com
  • +91 8827363777
Facebook Twitter Youtube

Automation

  • Who We Are?
  • Services And Plan
  • Contact Us
  • Privacy Policy
  • Terms And Conditions
  • Internship

Programs

  • Java program
  • VB Program
  • C# Program

Automation

  • Selenium Tutorial
  • Selenium Web Driver With Java
  • Selenium Web Driver With C#
  • Katalon studio
  • Puppeteer and Jest