Tuesday 9 May 2017

PassportJS read session for authentication

am using Nodejs backend with express for routes

and for authentication am using passportJS

before i was using localStorage to send the auth in HTTP header

now i want to use session, but the problem is, i don't know how to make passportJS read session data instead of http request header

below my passport configuration

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

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

passport.use(new UniqueTokenStrategy({
        session: false},
    function (token, done) {
        models.User.findOne({where: {token: token}}).then(function (user) {
            if (user) {
                console.log("111111")
                models.userHasRoles.findOne({

                    where: {

                        userId: user.id


                    }
                }).then(function (hasRoles) {


                    if (!hasRoles) {
                        return done(null, false);
                    }
                    return done(null, user);
                });
            }else{
                console.log("222222")
                return done(null, user);
            }
        })
    }

    ));

and this is my routes so i check the session before anything happen

router.get('/testSession',passport.authenticate('token'),function (req,res) {

res.status(200).send('loggedin');

});



via Faisal

No comments:

Post a Comment