Sathish
Sathish

Reputation: 200

How to get data like email id, name from google using passport.js?

I am new to node.js environment and I am using passport.js for the authentication purpose. I know how to authenticate using passport-google but I don't know how to get the data like email id, name, photo from the authenticated google account to the html form. The following one is the server.js

..
var passport = require('passport')
..
app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/return', passport.authenticate('google', { successRedirect: '/',
                                failureRedirect: '/login' }));

And the request.js file is

var passport = require('passport');
var GoogleStrategy = require('passport-google').Strategy;

passport.use(new GoogleStrategy({
returnURL: 'http://localhost:9000/profilepage.html',
realm: 'http://localhost:9000'
},
function(identifier, profile, done) {
User.findOrCreate({ openId: identifier }, function(err, user) {
  done(err, user);
});
}
));

Upvotes: 0

Views: 2724

Answers (1)

shawnzhu
shawnzhu

Reputation: 7585

The profile data will be populated into the second argument (named profile) of callback function of GoogleStrategy. Take a look at this code example: https://github.com/jaredhanson/passport-google/blob/master/examples/signon/app.js

You can access user profile information like this:

function(identifier, profile, done) {
  var userData = {identifier: identifier};

  // append more data if needed
  userData.email = profile.emails[0];
  userData.displayName = profile.displayName;
  userData.fullName = profile.familyName + " " + profile.givenName;
  // id is optional
  if (profile.id) {
    userData.id = profile.id;
  }

  return done(null, userData);
});

Upvotes: 1

Related Questions