Logout using Passport module in Node js

In this tutorial, we will learn about the logout logic. We will also use ejs(embedded javaScript) for the conditional displaying of the options.

Current User Logic

  • Create a function and use it to determine the currently logged in user.
  • As the logged-in information is stored in the body.
  • It is passed to the local information of the user which can be used for the conditional displaying.

Code:-

app.use(function (req, res,next){
    res.locals.currentUser = req.user;
    next();
})

Home page Upgrade.

  • Bring the code of home page from Register tutorial
  • The Logout option is must be only active when the user is already logged in.
  • To add conditions in displaying we use ejs. The syntax <%  //javascript code   %> carries javaScript code then we can use the conditional  if-else statement to display option.
  • If the current user is true that we made in above function then only the logout link/option must be active and if it’s false then login and register must be active.

Code:-

<h1>
    Home Page
</h1>
<p>
    <ul>
       <%if(!currentUser){%>
        <li><a href="/login">Login</a></li>
        <li><a href="/register">Register</a></li>
        <%}%>
        <%else{%>
        <li><a href="/logout">Logout</a></li>
        <%}%>
    </ul>
</p>

Logout Route and Logic

  • Set the get request route for the logout. As the only work is to send the information
  •  Send a callback function which consists of request and response
  • Use the request.logout() function to end the session and log the user out.
  • Redirect the user to the home page displaying login and register options.

Code:-

app.get("/logout",(req,res)=>{
    req.logout();
    res.redirect("/");
});

App.js

After the logout logic merge the code with the code base of the previous two tutorials as they contain the user registration and user login. This completes the User Authentication using the Passport library and the whole code looks like this when merged.

code:-

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

//current User
app.use(function (req, res,next){
    res.locals.currentUser = req.user;
    next();
})

//=======================
//      R O U T E S
//=======================

app.get("/", (req,res) =>{
    res.render("home");
})

app.get("/userprofile",isLoggedIn ,(req,res) =>{
    res.render("userprofile");
})
//Auth Routes
//Login
app.get("/login",(req,res)=>{
    res.render("login");
});

app.post("/login",passport.authenticate("local",{
    successRedirect:"/userprofile",
    failureRedirect:"/login"
}),function (req, res){

});

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

//logout
app.get("/logout",(req,res)=>{
    req.logout();
    res.redirect("/");
});

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