Login using Passport module in Node js

In this tutorial, we will learn the login logic. So the User register can log in to their particular User profile. We will create a user profile page as soon as any registered user logs in they will be redirected to the user profile.

Note:- The code will be merged with the code in the previous tutorial.

Setting Up Login form

In the views directory create a file named login.ejs

  1. Set up a basic HTML page with a heading of  “Login Page”.
  2. Then set a form asking for username and password.
  3. The action of the form is set to /login as the form will be sent to /login route.
  4. The method is set to the “post” as the information will be sending to the route.

Code:- Login Page

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

In the same views, directory create another file called as userprofile.ejs

  1. Basic HTML page with the heading  User Profile
  2. A success message for the user after login or any other content
  3. Provide the links to the home page and logout(Note:- Logout Logic will be in next tutorial)

Code:- User Profile page

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

Middleware

As the user profile page to load the user must be logged in but if the route is not protected then anyone can access through the link. Hence to protect the route we will write a custom function which will act as middleware to protect the route.

  1. Create the function named as isLoggedIn() (Note:- Name of function can be anything we are following the convention of CamelCase )
  2. Pass on the three basic parameters i.e request, response and next
  3. Using conditional statement check the user is authenticated or not.
  4. isAuthenticated()  is a pre-defined function of passport library which ill check the authenticity of a user. If that user is ever registered and is currently logged in or not. If true then use next() function.
  5. Else redirect the user to login page again.

Code:- isLoggedIn function

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

Setting Up Routes and Login Logic.

  • Set the get request for the User Profile page using app.get function, use the middleware we created to protect the route.
  • Set a similar get request for the login form. This will redirect to the login form where the user can log in
  • Write a post route for the login where all the logic is used to verify the user.
    app.get("/userprofile",isLoggedIn ,(req,res) =>{
        res.render("userprofile");
    })
    //Login
    app.get("/login",(req,res)=>{
        res.render("login");
    });
    
    app.post("/login",passport.authenticate("local",{
        successRedirect:"/userprofile",
        failureRedirect:"/login"
    }),function (req, res){
    
    });

Login Logic:-  The pre-defined function of the passport authenticate is used to verify the username and password submitted by a user and is check across the database and if the username and password matched than create a session and success redirect to the user profile and if they didn’t match than the failure redirect to login page again.

App js code:- The code is merged with the code of User registration tutorial.

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");


//Connecting database
mongoose.connect("mongodb://localhost/auth_demo",{
    useNewUrlParser: true,
    useUnifiedTopology:true,
    useCreateIndex:true
});

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());

//=======================
//      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");
    })    
    })
})

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

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