Passport's serializeUser doesn't respond

378 views Asked by At

I can't quite figure out how to use Passport's serializeUser function in express/SQL.

Here are my questions:

  1. How does passport.serializeUser know what "user" is? Where should I have specified it?
  2. How does passport.serializeUser know which request object should be bound with a cookie?

My app configuration looks like this:

var passport = require('passport');
app.use(session({ secret: 'Secret',
              saveUninitialized: true,
              resave: true}));
app.use(passport.initialize());
app.use(passport.session());

I also expose the following code to the app in twitter_auth.js:

// twitter authentication and login
app.get('/auth/twitter', passport.authenticate('twitter'));

// handle callback after twitter has authenticated user
app.get('/auth/twitter/callback',passport.authenticate('twitter',{
            successRedirect: '/',
            failureRedirect: '/'
}));

// used to serialize user
passport.serializeUser(function(user,done){
    done(null,user);
});


// used to deserialize the user
passport.deserializeUser(function(User_ID,done){
   connection.query('SELECT * from UsersTable where User_ID = '+User_ID,     function(err,rows){
      done(err,rows[0]); 
   });
});

When I try spotting it:

// used to serialize user
passport.serializeUser(function(user,done){
 console.log('spotted here!');  
 done(null,user);
});

I never see anything. What's wrong?

1

There are 1 answers

0
Adam On

To answer your two questions:

  1. You have to define what 'user' is inside the authentication code.

    It should look like this:

    passport.use(new TwitterStrategy({
        consumerKey:*******,
        consumerSecret:******,
        callbackURL:'/auth/twitter/callback'
    },
    function(token, tokenSecret, profile,done){
      var user = db.call(retrieve a user) ; //whatever you want it to be
      done(null,user);
     });
    
  2. The authentication route was accessed via some request object to begin with, and it's the code there:

    done(null,user);
    

    that knows of your req object. From my understanding, that is.

A good source on this is: http://toon.io/understanding-passportjs-authentication-flow/