Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

req.isAuthenticated() is always false

My authentication function using passportjs 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... I have seen other related questions, but most of the threads aren't really answering the questions, or the answers that looks like a solution are not working even though I applied it, as they should I am still confused about what to do to make this work.

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.

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...');
});

console.log(req.isAuthenticated()) // Is always returning false.

like image 638
Precious Adeyinka Avatar asked Mar 13 '26 04:03

Precious Adeyinka


1 Answers

Try changing the order of

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

to

app.use(require("express-session")({
    secret: "Rusty is the worst and ugliest dog in the wolrd",
    resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

If you are using cookies make sure you add cookie-parser middleware

var express = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

If this is not the case check you calling end, if you are using axios include withCredentials

axios.get('some api url', {withCredentials: true});

if you are uisg fetch make sure to add credentials: 'include'

fetch('/...', {
  method: ..,
  headers: ...,
  credentials: 'include',
  body: ...
  ...})
like image 194
TRomesh Avatar answered Mar 15 '26 21:03

TRomesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!