Google oauth2 login

This commit is contained in:
Sahat Yalkabov
2013-11-21 14:20:38 -05:00
parent 3db05555f8
commit 4ba93805e4
4 changed files with 61 additions and 2 deletions

19
app.js
View File

@@ -61,6 +61,25 @@ app.post('/contact', contact.postContact);
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' }));
app.get('/auth/google', passport.authenticate('google', {
scope: [
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'
]
}), function (req, res) {
// The request will be redirected to Google for authentication, so this
// function will not be called.
});
app.get('/auth/google/callback', passport.authenticate('google', {
failureRedirect: '/login'
}), function (req, res) {
res.redirect('/');
});
app.get('/auth/foursquare', api.foursquareAuth);
app.get('/auth/foursquare/callback', api.foursquareCallback);
app.get('*', home.index);

View File

@@ -1,6 +1,7 @@
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
FacebookStrategy = require('passport-facebook').Strategy,
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
User = require('../models/User'),
config = require('./config.json');
@@ -65,7 +66,46 @@ passport.use(new FacebookStrategy({
});
});
}
));
passport.use(new GoogleStrategy({
clientID: config.google.clientId,
clientSecret: config.google.clientSecret,
callbackURL: config.google.callbackUrl
},
function(accessToken, refreshToken, profile, done) {
console.log(accessToken);
console.log(profile);
User.findOne({ google: profile.id }, function(err, existingUser) {
if (err) {
done(err);
}
if (existingUser) {
return done(null, existingUser);
}
var user = new User({
firstName: profile.name.givenName,
lastName: profile.name.familyName,
provider: profile.provider
});
user[profile.provider] = profile.id;
user.save(function(err) {
if (err) {
if (err.code === 11000) {
// Found another user with the same email
}
}
done(null, user);
});
});
}
));

View File

@@ -9,7 +9,7 @@
"passport": "latest",
"passport-local": "latest",
"passport-facebook": "latest",
"passport-google": "latest",
"passport-google-oauth": "latest",
"underscore": "latest",
"forever": "latest",
"node-foursquare": "latest",

View File

@@ -11,7 +11,7 @@ block content
i.fa.fa-facebook-square
| Facebook
.col-xs-6.col-sm-6.col-md-6
a.btn.btn-lg.btn-danger.btn-block(href='#')
a.btn.btn-lg.btn-danger.btn-block(href='/auth/google')
i.fa.fa-google-plus-square
| Google
.login-or