Node.js – user is not defined: Nodejs/Express + Passport

expressnode.jspassport.js

My problem is very similar to this question however the answers seems to not work for me (I see that user never picked an answer also).

I have a fresh install of Nodejs and Express.

My setup:

app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('hithere'));
app.use(session({
    secret: 'hithere',
    resave: false,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());


passport.serializeUser(function(user, done) {
  console.log('Serialize user called.');
  return done(null, user);
});

passport.deserializeUser(function(id, done) {
  console.log('Deserialize user called.');
  return done(null, user);
});

passport.use(new LocalStrategy(
  function(username, password, done) {
    console.log('local strategy called with: %s', username);
    return done(null, {username:username, password:password});
  }));


app.use('/', routes);
app.use('/users', users);
app.get('/success', function(req, res) {
  req.send('sucess!');
});
app.get('/failure', function(req, res) {
  req.send('failure!');
})
app.post('/register', function(req, res) {
    console.log(req.body);
});

app.post('/signup', passport.authenticate('local', { successRedirect: '/success', failureRedirect: '/failure' }));

I'm using express-session.

My LocalStrategy, serialize and deserialize user are all getting called, but frankly I'm not really sure what to put on the deserialize function on this test app.

Any suggestions for a fix?

Best Solution

You get user is not defined because user in fact is not defined in your deserializeUser() callback. If you look at the example in the Sessions section on this page, you will see that you are supposed to look up the id in your database and pass a user object (generated from the result of the database query) to the done callback.

For simple testing purposes, you could easily just use a fake user object until you have a database set up:

passport.deserializeUser(function(id, done) {
  console.log('Deserialize user called.');
  return done(null, { firstName: 'Foo', lastName: 'Bar' });
});