-
-
Save neomadara/266913c468ff5bf84e57 to your computer and use it in GitHub Desktop.
PassportJS Usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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