Sign in
Log inSign up

req.isAuthenticated() is always returning false

Precious Adeyinka's photo
Precious Adeyinka
·May 24, 2019

Hello, guys, I have an issue with Passportjs authentication. I have written a simple app to authenticate user login signup and logout using routes and passportjs.

My last piece of code is setup to only allow user access to the contents of the main site which is called a secret template in this case only if the user is a valid user (that is they are logged in or have successfully signed up).

The function I have created to do that looks like this:

// Authenticate user Login
function isLoggedIn(req, res, next) {
    if(req.isAuthenticated()) {
        return next();
    }
    res.redirect('/login');
}

and this basically was supposed to check if a user was already logged in.

and then I called the function as a middleware in one of my routes:

app.get('/secret', isLoggedIn , (req, res)=>{
    res.render('secret');
});

This is supposed to make sure that the user is logged in or have signed up before they get access to the secret page, otherwise, it should return the login page and require that the user is logged in or has signed up to gain access to the secret page.

But, this will always return false even though the user exists already and it will always redirect to the login page and this is overwriting all my authentication routes, so when I log in with a valid user credential or create a new user, the default behavior is to redirect to the 'secret page' but that is only redirecting to the login page every time.

I don't know what I am doing wrong here guys, I need ur help, please...

This is my full code just in case, you have a spotty eyes keener than mine.

var express               = require('express'),
    app                   = express(),
    mongoose              = require('mongoose'),
    bodyParser            = require ('body-parser'),
    User                  = require('./models/user'),
    passport              = require('passport'),     
    localStrategy         = require('passport-local'),
    passportLocalMongoose = require('passport-local-mongoose'); 

mongoose.connect('mongodb://localhost/auth_demo_app', {
    useNewUrlParser: true
});

app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(require("express-session")({
    secret: "Rusty is the worst and ugliest dog in the wolrd",
    resave: true,
    saveUninitialized: true
}));

passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());


// ==================================================
// ROUTES
// ==================================================

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

app.get('/secret',isLoggedIn, (req, res)=>{
    res.render('secret');
});

// AUTH ROUTES
// Register - Show Registration form
app.get('/register', (req, res)=>{
    res.render('register');
});
// Handle user Signup
app.post('/register', (req, res)=>{
    req.body.username
    req.body.password
    User.register(new User({username: req.body.username}), req.body.password, (err, user)=>{
        if(err){
            console.log(err);
            return res.render('register');
        }
        passport.authenticate('local')(req, res, ()=>{
            res.redirect('/secret');
        })
    })
});

// Login - Show Login form
app.get('/login', (req, res)=>{
    res.render('login');
});
// Handle user Signup
app.post('/login', passport.authenticate('local', {
        successRedirect: '/secret',
        failureRedirect: '/login',
    }),(req, res)=>{
        // Other stuff goes here 
});

// LOGOUT ROUTE
// Logs user out - ends user session
app.get('/logout', (req, res)=>{
    req.logOut();
    res.redirect('/');
});

// Authenticate user Login
function isLoggedIn(req, res, next) {
    if(req.isAuthenticated()) {
        console.log('User logged in successfully');
        return next();
    }
    res.redirect('/login');
}

app.listen(3000, ()=>{
    console.log('Server Started...');
});
Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct