Skip to content

Instantly share code, notes, and snippets.

@scan
Last active December 10, 2015 05:58
Show Gist options
  • Save scan/4391302 to your computer and use it in GitHub Desktop.
Save scan/4391302 to your computer and use it in GitHub Desktop.
var passport = require('passport'),
TwitterStrategy = require('passport-twitter').Strategy,
GoogleStrategy = require('passport-google-oauth').Strategy,
users = require('./model').users;
/*
This is for serializing a user object.
Basically, it should return all of an user object
that is necessary to identify it. Usually, the id
field will do just fine.
*/
passport.serializeUser(function(user, done) {
done(null, user.id);
});
/*
This goes the other way around. This function should
return a full user object. This is not only database agnostic,
you can also use web services or whatever here.
*/
passport.deserializeUser(function(id, done) {
users.findOne({id: id}, done);
});
var findOrCreate = function(provider, id, name, done) {
users.findOne({"auth.provider": provider, "auth.id": profile.id}, function(err, user) {
if(err || user) done(err, user);
else {
user = {auth: [{provider: provider, id: id}], name: profile.name };
users.insert(user, {safe: true}, function(err, usrs) {
done(err, usrs[0]);
});
}
});
}
passport.use(new TwitterStrategy(
{
consumerKey: process.env.TWITTER_CONSUMER_KEY,
consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
callbackURL: "http://" + process.env.domain + "/auth/twitter/callback"
}, function(token, tokenSecret, profile, done) {
findOrCreate('twitter', profile.id, profile.name, done);
}));
passport.use(new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://" + process.env.domain + "/auth/google/callback"
}, function(accessToken, refreshToken, profile, done) {
findOrCreate('google', profile.id, profile.name, done);
}));
module.exports.setup = function(app) {
app.get('/auth/twitter', passport.authenticate('twitter')));
app.get('/auth/google', passport.authenticate('google', scope: {'https://www.googleapis.com/auth/userinfo.profile'})));
app.get('/auth/twitter/callback', passport.authenticate('twitter', {successRedirect: '/', failureRedirect: '/login'})));
app.get('/auth/google/callback', passport.authenticate('google', {successRedirect: '/', failureRedirect: '/login'})));
}
module.exports.authenticationRequired = function(req, res, next) {
if(req.isAuthenticated()) next();
else res.redirect('/login');
}
module.exports.logout = function(req, res) {
req.logOut();
res.redirect('/login');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment