Passport.js | isAuthenticated() always return false

Passport.js | isAuthenticated() always return false
0

#1

Hi, I am a newbie with Passport.js. While using Local strategy, I have trouble with isAuthenticated(). It always returns false even after login successfully.

Below is my code, plz help me!!!
Thank you guys so much :slight_smile:

const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const session = require('express-session');

const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
app.use(session({
    secret: 'mysecret',
    cookie: {
        maxAge: 60000 
    }
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());

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

app.post('/login', passport.authenticate('local',
        {failureRedirect: '/fail', successRedirect: '/succeed'}));

app.get('/succeed', (req, res) => {
    console.log(req.isAuthenticated());
    res.send("Dang nhap thanh cong");
});
 
app.get('/private', (req, res) => {
    console.log(req.isAuthenticated());
    if (req.isAuthenticated()) {
        res.send("Welcome");
    }
    res.send("Ban chua dang nhap");
});

passport.use(new LocalStrategy(
    (username, password, done) => {
        mongo.connect('mongodb://localhost:27017/local', (err, db) => {
            if (err) throw err;
            db.collection('users').findOne({name: username}, (err, user) => {
                if (err) { return done(err); }
                if (!user) {
                    return done(null, false);
                }
                return done(null, user)
            });
        });
    }
));

passport.serializeUser((user, done) => {
    done(null, user._id)
});

passport.deserializeUser((id, done) => {
    mongo.connect('mongodb://localhost:27017/local', (err, db) => {
        if (err) throw err;
        db.collection('users').findOne({ _id: id }, (err, user) => {
            if (err) { return done(err); }
            if (!user) {
                return done(null, false);
            }
            return done(null, user)
        });
    });
})

app.listen(3000);

#2

Well, I have used Passport, but with Facebook Strategy. I was using an example from Passport.js Github in my code and everything worked out of the box, although the mechanism is still not clear to me. Maybe check my code and compare it with yours: https://github.com/pilgrim011/voting-app/blob/master/app.js.

I just found the original example, it’s better than my implementation: https://github.com/passport/express-4.x-facebook-example/blob/master/server.js.