req.user.displayname undefined Nodejs + passport = google oauth

862 views Asked by At

Im trying to access to req.user.displayName after login but im getting undefined. There is some thing that I missing?

├── config
│   └── passport.js
├── controllers
│   ├── index.controllers.js
│   └── users.controllers.js
├── helpers
│   └── auth.js
├── models
├── public
├── routes
│   ├── index.routes.js
│   └── users.routes.js
├── server.js
└── views

config/passport.js ;

const { use } = require('passport');
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../models/user');

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

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

passport.use(new GoogleStrategy({
  clientID: 'blablablablablabla',
  clientSecret: 'blablablabla',
  callbackURL: "http://localhost:4000/google/callback",
  passReqToCallback: true
},
  async (req, token, refreshToken, profile, done) => {
    const newUser = {
      googleId: profile.id,
      displayName: profile.displayName,
      firstName: profile.name.givenName,
      lastName: profile.name.familyName,
      image: profile.photos[0].value,
    }

    try {
      let user = await User.findOne({ googleId: profile.id })

      if (user) {
        done(null, user)
      } else {
        user = await User.create(newUser)
        done(null, user)
      }
    } catch (err) {
      console.error(err)
    }
  }
));

Im trying to access to req.user.displayName after login (redirect to '/' and pass req.user.displayName to render in ejs view)

controllers/index.controllers.js

const index_controller = {};

index_controller.renderHome = async (req, res) => {
    res.render('home', { username: req.user.displyaName })
};

routes/index.routes.js

const { renderHome } = require('../controllers/index.controllers')

const { isAuth } = require('../helpers/auth')

router.get('/', isAuth, renderHome);

routes/users.routes.js

router.get('/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
    // res.send(req.user)
    res.redirect('/');
  });

Also you can find the entire code here: https://github.com/fcarreon/google-test

1

There are 1 answers

0
Erwan On BEST ANSWER

According to the documentation (here), you should use :

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

You use the same code for both serializing and deserializing the user.