Skip to content

Instantly share code, notes, and snippets.

@jazarja
Created February 28, 2016 06:50
Show Gist options
  • Save jazarja/31d02896f70e33b36d8c to your computer and use it in GitHub Desktop.
Save jazarja/31d02896f70e33b36d8c to your computer and use it in GitHub Desktop.
Google OAuth Passport Sample
/**
* Sign in with Google.
*/
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: '/auth/google/callback',
passReqToCallback: true
}, function(req, accessToken, refreshToken, profile, done) {
if (req.user) {
User.findOne({ google: profile.id }, function(err, existingUser) {
if (existingUser) {
req.flash('errors', { msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
done(err);
} else {
User.findById(req.user.id, function(err, user) {
user.google = profile.id;
user.tokens.push({ kind: 'google', accessToken: accessToken, refreshToken: refreshToken });
user.profile.name = user.profile.name || profile.displayName;
user.profile.gender = user.profile.gender || profile._json.gender;
user.profile.picture = user.profile.picture || profile._json.image.url;
user.save(function(err) {
req.flash('info', { msg: 'Google account has been linked.' });
done(err, user);
});
});
}
});
} else {
console.log(accessToken+" "+refreshToken);
User.findOne({ google: profile.id }, function(err, existingUser) {
if (existingUser) {
return done(null, existingUser);
}
User.findOne({ email: profile.emails[0].value }, function(err, existingEmailUser) {
if (existingEmailUser) {
req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Google manually from Account Settings.' });
done(err);
} else {
var user = new User();
user.email = profile.emails[0].value;
user.google = profile.id;
user.tokens.push({ kind: 'google', accessToken: accessToken, refreshToken: refreshToken });
user.profile.name = profile.displayName;
user.profile.gender = profile._json.gender;
user.profile.picture = profile._json.image.url;
user.save(function(err) {
done(err, user);
});
}
});
});
}
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment