Skip to content

Instantly share code, notes, and snippets.

@reecer
Created October 8, 2014 22:26
Show Gist options
  • Save reecer/7b0692dd76ff987d4350 to your computer and use it in GitHub Desktop.
Save reecer/7b0692dd76ff987d4350 to your computer and use it in GitHub Desktop.
PassportJS Usage
var passport = require('passport'),
FacebookStrategy = require('passport-facebook').Strategy,
TwitterStrategy = require('passport-twitter').Strategy,
GithubStrategy = require('passport-github').Strategy,
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
/* ...server setup... */
// Setup passport auth
app.use(passport.initialize());
app.use(passport.session());
var passportCallback = function(accessToken, refreshToken, profile, done){
process.nextTick(function () {
return done(null, profile);
});
};
try{
passport.use(new FacebookStrategy({
clientID: config['FACEBOOK_CLIENTID'],
clientSecret: config['FACEBOOK_CLIENTSECRET'],
callbackURL: config['FACEBOOK_CALLBACKURL']
}, passportCallback));
passport.use(new TwitterStrategy({
consumerKey: config['TWITTER_CONSUMERKEY'],
consumerSecret: config['TWITTER_CONSUMERSECRET'],
callbackURL: config['TWITTER_CALLBACKURL']
}, passportCallback));
passport.use(new GithubStrategy({
clientID: config['GITHUB_CLIENTID'],
clientSecret: config['GITHUB_CLIENTSECRET'],
callbackURL: config['GITHUB_CALLBACKURL']
},passportCallback));
passport.use(new GoogleStrategy({
clientID: config['GOOGLE_CLIENTID'],
clientSecret: config['GOOGLE_CLIENTSECRET'],
callbackURL: config['GOOGLE_CALLBACKURL']
},passportCallback));
}catch (e){
console.error("[*]\tError initializing authentication protocols");
console.error(e);
}
// AUTH Routes
["facebook", "twitter", "google", "github"].forEach(function(name){
var mid1, mid2;
var mid = name === "google" ? {scope: 'https://www.googleapis.com/auth/plus.me'} : undefined;
app.get('/auth/' + name, passport.authenticate(name, mid));
app.get('/auth/' + name + '/callback', passport.authenticate(name, {failureRedirect: '/'}),
function(req,res){ res.redirect('/')});
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
// serialize and deserialize
passport.serializeUser(function(user, done) { done(null, user); });
passport.deserializeUser(function(obj, done) { done(null, obj); });
// test authentication
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment