Search code examples
javascriptnode.jsexpresspassport.jstwitter-oauth

req.user is coming back as undefined with Express and Passport?


When my app redirects to "/" req.user is undefined, but in the twitter callback, req.user gives me the data that I'm looking for. I lose the data on redirect. There is still information in req for "/" but not req.user which I need.

Can anyone help me solve this problem?

This is my index.js

const express = require('express')
const app = express()
const cookieSession = require('cookie-session')
const passport = require('passport');
require('./passport')
const isLoggedIn = require('./Middleware/auth')

app.use(cookieSession({
  name: 'twitter-auth-session',
  keys: ['key1', 'key2']
}))
app.use(passport.initialize());
app.use(passport.session());

app.get('/auth/error', (req, res) => res.send('Unknown Error'))


//, isLoggedIn,

app.get('/', (req,res)=>{
  console.log('HELLOOOOO', req.user)
  res.send(`Hello`)
});

app.get('/logout', (req, res) => {
  req.session = null;
  req.logout();
  res.redirect('/');
})

app.get('/auth/twitter',passport.authenticate('twitter'));
app.get('/auth/twitter/callback',passport.authenticate('twitter', { failureRedirect: '/auth/error' }),
function(req, res) {
  // console.log("REQUEST", req.user)
  res.redirect('/');
});

app.listen(8000,()=>{
  console.log('Server is up and running at the port 8000')
})

This is my passport.js middleware:

const passport = require('passport');
const TwitterStrategy = require('passport-twitter').Strategy;

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

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

passport.use(new TwitterStrategy({
  consumerKey: "xxxxxxxxxxx",
  consumerSecret: "xxxxxxxxxxx",
  callbackURL: "http://www.localhost:8000/auth/twitter/callback",
}, function(accessToken, refreshToken, profile, cb) {
  return cb(null, profile);
}));

Solution

  • Ok so after some trial and much error the problem seemed to be with the way that I was using sessions or the cookie-session library.

    I added the library

    const session = require('express-session')
    

    I changed

    app.use(cookieSession({
      name: 'twitter-auth-session',
      keys: ['key1', 'key2']
    }))
    

    to

    app.use(session({ secret: 'secret' }))
    

    And that seems to have fixed things, just in case you all are looking at this really obscure answer haha.