How to perform Login And Logout in NodeJS, ExpressJS, and MongoDB. Login logout example in MERN.
This Login And Logout example in NodeJS and ExpressJS System are StepUp on the passport Library of nodeJS. The user Enter the username name and password. ExpressJS Create a session and find a similar username and password and allow the user to gain access. If Those details do not match then the Express doesn’t create a session and ask the user to log in again.
Login and Logout in NodeJs, ExpressJS, and MongoDB
Step 1 Setting Server and Library
- Use the Command line to install used libraries.
PS D:\work\Codebun\Authentication-validation> npm install express ejs mongoose body-parser
- Define the express app.
- Setup server to listen on certain ports.
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"), session = require("express-session"), User = require("./models/user"); app.listen(process.env.PORT ||3000,function (err) { if(err){ console.log(err); }else { console.log("Server Started At Port 3000"); } });
STEP 2 Configuration of database
- Creating a database and connection.
- Setting Up schema of the user.
- Exporting the schema.
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 3 Setting Pages
- Setting EJS pages and routes of HTML.
- Creating a home page.
- Creating a Login form and User profile.
HOME PAGE
<h1> Home Page </h1> <p> <ul> <li><a href="/login">Login</a></li> <li><a href="/register">Register</a></li> <%if(currentUser){%> <li><a href="/logout">Logout</a></li> <%}%> </ul> </p>
LOGIN FORM
<h1> Login Page </h1> <form action="/login" method="POST"> <label for="username">UserName</label> <input type="text" placeholder="username" required id="xyz" name="username"> <label for="password">Password</label> <input type="password" id="password" required name="password"> <button>Login</button> </form> <ul> <li><a href="/">Home</a></li> <li><a href="/register">SignUp</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 4 Configuration of passport Library
- Setting the Passport Library.
- Setting Sessions using express-sessions.
- Creating middleware ( isloggedin() ).
- Connecting to the DATABASE.
//Connecting database mongoose.connect("mongodb://localhost/auth_demo"); app.use(session({ secret:"Any normal Word", //decode or encode session resave: false, saveUninitialized:false, cookie:{ maxAge: 2*60*1000 } })); 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()); //current User app.use(function (req, res,next){ res.locals.currentUser = req.user; next(); }) //MIDDLEWARE function isLoggedIn(req,res,next) { if(req.isAuthenticated()){ return next(); } res.redirect("/login"); }
SETTING ROUTES
- Setting Up Index Route
- Creating login get and post routes
- Creating The Register get and post routes
- Creating the Logout route
//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("/"); });
Login Logic
app.post("/login",passport.authenticate("local",{ successRedirect:"/userprofile", failureRedirect:"/login" }),function (req, res){ });
Logout Logic
app.get("/logout",(req,res)=>{ req.logout(); res.redirect("/"); });