Search code examples
angularjsnode.jssessionpassport.jspassport-local

How to use the session from passportjs


I am able to login using passport-local. I want to test if the session created by passport is valid. I am logging in from Angular. When the user logs in, i dont create any manual cookie but see a connect.sid cookie is created. Now from Angular I'm sending another req:

$scope.test = function(){
    $http.get('\test').then(function(response){
        if(response){
            console.log(response);
        } else {
            console.log("Nothing Returned!");
        }
    });
}

And in node :

app.use(session({
    secret: 'mysecret',
    resave: true,
    saveUninitialized: true
}));


//Passport Init
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
        done(null, user.id);
    });


passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
         done(err, user);
    });
});


app.get('\test', function(req, res){

   //Tried the following (one at a time) : 
    var user = req.user;
    var user = req[user];
    var user = req["user"];
    var user = req.session;

    console.log(user);
    res.send(user);

});

None of the above works. I get res code 200 but nothing in response.data in Angular and nothing in undefined in node console.

Im doing this cause I think :

  1. After user logs in, Passportjs creates session is persisted until its destroyed by logout.
  2. After user logs in, there is no need to create a cookie and send it to Angular. Passport does this automatically.
  3. When Angular sends any request, node can access the session of req and verify with it's own session.

Am I correct with all these 3 points?

Many thanks!

EDIT My mongoose schema:

var UserSchema = mongoose.Schema({
    id : {type:String, default:"abc123"},
    username: {type:String, index: true},
    password: String,
    email: {type:String, unique:true}
});

module.exports = mongoose.model('User', UserSchema);

EDIT 2 Adding output that i get when placed the express session before passport session

enter image description here

EDIT 3 My strategy :

passport.use(new LocalStrategy(
    function(username, password, done){
        User.findOne({username: username}, function(err, doc){
            if(err) {
                // console.log(err);
                return done(err);
            }
            return done(null, doc);
        });
    }
));

Solution

  • You need to change the order, put 'express session' before 'passport session'. It should work this way:

    app.use(session({
        secret: 'mysecret',
        resave: true,
        saveUninitialized: true
    }));
    
    app.use(passport.initialize());
    app.use(passport.session());
    

    http://passportjs.org/docs/configure