Login form using Node JS and MongoDB
Follow these simple steps to learn how to create a login form using Node.js and MongoDB. Node JS login form allows users to log in to the website after they have created their account using the signup form.
We will be using the following technologies:
It 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 middleware and routing; it adds helpful utilities to Node.js’s HTTP objects; it facilitates the rendering of dynamic HTTP objects.
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 the storage and retrieval of data. This format of storage is called BSON ( similar to JSON format).
Passport:
It 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 supports authentication using a username and password, Facebook, Twitter, and more.
Steps to Create Project and Install Modules:
Step 1: Start the project using the following command in your project folder
npm init
Step 2: Install the required modules using the following command
npm i express ejs mongoose body-parser express-session
npm i passport passport-local
npm i 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 i
Project Structure:
The updated dependencies in package.json file.
"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"
}
Example: Add the following code in App.js and User.js file
Javascript
// Filename - App.js const 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" ); let 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()); //===================== // 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" , async (req, res) => { const user = await User.create({ username: req.body.username, password: req.body.password }); return res.status(200).json(user); }); //Showing login form app.get( "/login" , function (req, res) { res.render( "login" ); }); //Handling user login app.post( "/login" , async function (req, res){ try { // check if the user exists const user = await User.findOne({ username: req.body.username }); if (user) { //check if password matches 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 }); } }); //Handling user logout 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" ); } let port = process.env.PORT || 3000; app.listen(port, function () { console.log( "Server Has Started!" ); }); |
Javascript
// Filename - model/User.js 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
// Filename - views/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
// Filename - views/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
// Filename - views/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
// Filename - views/secret.ejs < h1 >This is secret page</ h1 > < img src = "https://media.w3wiki.net/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: