Login form using Node.js and MongoDB

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.

Installation of modules:

  • $ npm install ejs

    Embeded javaScript lets you generate HTML markup with plain JavaScript.

  • $ npm install express --save

    Express is a module framework for Node that you can use for applications.

  • $ npm install mongoose

    Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.



  • $ npm install body-parser --save

    Body-parser allows express to read the body and then parse that into a JSON object that we can understand.

  • npm install express-session --save

    Express.js uses a cookie to store a session id.

  • npm install passport passport-local --save
    npm install passport-local-mongoose --save

    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.

Filename: app.js

filter_none

edit
close

play_arrow

link
brightness_4
code

var express = require("express"),
    mongoose = require("mongoose"),
    passport = require("passport"),
    bodyParser = require("body-parser"),
    LocalStrategy = require("passport-local"),
    passportLocalMongoose = 
        require("passport-local-mongoose"),
    User = require("./models/user");
  
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect("mongodb://localhost/auth_demo_app");
  
var app = express();
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());
  
//=====================
// ROUTES
//=====================
  
// Showing home page
app.get("/", function (req, res) {
    res.render("home");
});
  
// Showing secret page
app.get("/secret", isLoggedIn, function (req, res) {
    res.render("secret");
});
  
// Showing register form
app.get("/register", function (req, res) {
    res.render("register");
});
  
// Handling user signup
app.post("/register", function (req, res) {
    var username = req.body.username
    var password = req.body.password
    User.register(new User({ username: username }),
            password, function (err, user) {
        if (err) {
            console.log(err);
            return res.render("register");
        }
  
        passport.authenticate("local")(
            req, res, function () {
            res.render("secret");
        });
    });
});
  
//Showing login form
app.get("/login", function (req, res) {
    res.render("login");
});
  
//Handling user login
app.post("/login", passport.authenticate("local", {
    successRedirect: "/secret",
    failureRedirect: "/login"
}), function (req, res) {
});
  
//Handling user logout 
app.get("/logout", function (req, res) {
    req.logout();
    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!");
});

chevron_right


Filename: home.ejs

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Filename: login.ejs

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Filename: register.ejs

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Filename: secret.ejs

filter_none

edit
close

play_arrow

link
brightness_4
code

<h1>This is secrect page</h1>
  
images?q=tbn%3AANd9GcQ5PdxXFw4u3BRG4166i7Nbk
x0VyGGNt0hWc3loNeD7GIL4nbbo&usqp=CAU">
  
<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>

chevron_right


Steps to run the program:

  1. The project structure will look like this:

    And the content of views directory will look like this:

    Rest files will be the created after you run npm init for initialiasing .json file.
  2. Run index.js file using below command:
    nodemon app.js

    OR If you don’t have nodemon installed you can run:

    node app.js

  3. Now go to your browser and type the following URL:
    http://localhost:3000/

  4. First you will need to signup then only you can login into the app.
  5. Now you have successfully signup, Now this is login form as shown below:

    This login form will take you to the Secret page as shown below:

So this is how you can create login form using Node.js and MongoDB.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.