JVG
JVG

Reputation: 21170

Checking if a user is logged in with PassportJS / ExpressJS

I have an Angular app built on the MEAN stack, using Passport to log in and authenticate users. I'm a little confused about how authentication works.

I have a route that Angular passes an $http call to to check if a user is logged in (and can thus access certain pages). The route looks like this:

// route to test if the user is logged in or not 
app.get('/loggedin', function(req, res) {
    res.send(req.isAuthenticated() ? req.user : '0');
});

From what I've read (which is very little, I can't find isAuthenticated() anywhere in the Passport docs...), Passport should be creating a persistent session for my users.

This works for the most-part, but if I close my Chrome application / reset my computer I have to log in again. I assumed that using Passport would mean that I don't need to create a hashed cookie to store login information. Is this not the case?

Other potential cause: I'm in development at the moment and am restarting the server often. Will the Passport sessions not persist through a server restart?

Edit: Here is my session config in app.js:

var session      = require('express-session');
app.use(session({ secret: 'heregoesasupersecretsecret' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

Upvotes: 2

Views: 4659

Answers (2)

Sunil Kumar
Sunil Kumar

Reputation: 545

If you are using passport for authentication in Node.js, you can use a middleware to check the authentication. I use the below code for this.

passport.use(new LocalStrategy({passReqToCallback : true}, function(req, username, password, done) {
    models.Accounts.findOne({ where: { username: username}}).then(function(user) {
        if (!user) {
            console.log('Unkown User');
            return done(null, false, {message: 'Unknown User'});
        }

        bcrypt.compare(password, user.password, function(err, isMatch) {
            if (err) throw err;
            if (isMatch) {
                req.session.username = req.body.username;
                return done(null, user);
            } else {
                return done(null, false, {message: 'Invalid Password'});
            }
        });
    }).catch(function(err) {
        return done(null, false);
    });
}));

You can use express-session library in Node.js to handle user sessions. You can add a middleware in your code like below.

app.use(session({
secret: 'track_courier_application_secret_key',
    cookie: {
        maxAge: 300000
    },
    saveUninitialized: true,
    resave: true
}));

In the above code I'm setting maxAge to 300K milli seconds. That is 5 minutes. After this a session object will be attached in every request to the server. You can access this session object using

req.session

Now you can write a get request like below to check if a user is logged in or not.

app.get('/accounts/isloggedin', function(req, res) {
    if(req.session.username)
        res.status(200).send('Hurray!');
    else
        res.status(401).send('User not logged in.');
});

Upvotes: 1

dsan
dsan

Reputation: 1588

You need to use a proper session store to put the sessions in to persist them between requests. Since you're using MongoDB, you could use connect-mongo.

Then you could do something like:

var session      = require('express-session'),
    MongoStore   = require('connect-mongo')(session);

app.use(session({ 
                   secret: 'heregoesasupersecretsecret',
                   store: new MongoStore()
                }
));
app.use(passport.initialize());
app.use(passport.session());

Upvotes: 0

Related Questions