Google Strategy - kplian/pxp-nd GitHub Wiki
Support for Google is implemented by the passport-google-oauth module.
1. Install
$ npm install passport-google-oauth
2. Configuration oAuth 2.0
The Google OAuth 2.0 authentication strategy authenticates users using a Google account and OAuth 2.0 tokens. Create config file src/lib/auth/passport-google:
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
passport.use(new GoogleStrategy({
clientID: 'yourGoogleClientID',
clientSecret: 'yourGoogleClientSecret',
callbackURL: "http://localhost:3000/api/google/callback"
},
function(accessToken, refreshToken, profile, done) {
// In this section you should use the business logic corresponding to your needs.
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
3. Routes
Use passport.authenticate(), specifying the 'google' strategy, to authenticate requests. Add routes in src/lib/auth/authRoutes.js:
router.get('/api/google',
passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));
router.get('/api/google/callback',
passport.authenticate(
'google',
{ failureRedirect: '/api/login' } //redirect when failed login
),
// Custom callback when login is correct
function(req, res) {
console.log('res');
res.redirect('/');
});
4. Use config
Finally import the configuration file into your main file before initializing passport:
// ...
require('./src/lib/auth/passport-google');
app.use(passport.initialize());
// ...