Login form using Node.js and MongoDB - GeeksforGeeks

17 Jan, 2022
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
Embedded 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  
javascript
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 pageapp.get("/", function (req, res) {    res.render("home");}); // Showing secret pageapp.get("/secret", isLoggedIn, function (req, res) {    res.render("secret");}); // Showing register formapp.get("/register", function (req, res) {    res.render("register");}); // Handling user signupapp.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 formapp.get("/login", function (req, res) {    res.render("login");}); //Handling user loginapp.post("/login", passport.authenticate("local", {    successRedirect: "/secret",    failureRedirect: "/login"}), function (req, res) {}); //Handling user logoutapp.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!");});
Filename: home.ejs  
html
<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>
Filename: login.ejs  
html
<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>
Filename: register.ejs  
html
<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>
Filename: secret.ejs  
html
<h1>This is secrect page</h1> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQ5PdxXFw4u3BRG4166i7Nbkx0VyGGNt0hWc3loNeD7GIL4nbbo&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>
Steps to run the program: 
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 initialising .json file.
Run index.js file using below command:
nodemon app.js
OR If you don’t have nodemon installed you can run:
node app.js
Now go to your browser and type the following URL:
http://localhost:3000/
First you will need to signup then only you can login into the app.  
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.
adnanirshad158
saurabh1990aror
MongoDB
Mongoose
Node.js-Misc
MongoDB
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Spring Boot JpaRepository with Example
Aggregation in MongoDB
How to build a basic CRUD app with Node.js and ReactJS ?
Mongoose Populate() Method
MongoDB - Check the existence of the fields in the specified collection
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js