public
Last active

Node Knockout 2012 - Getting Started with Passport

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
var express = require('express'),
passport = require('passport'),
TwitterStrategy = require('passport-twitter').Strategy,
ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn,
app = express();
 
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
 
passport.serializeUser(function(user, done) {
done(null, user);
});
 
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
 
 
var TWITTER_CONSUMER_KEY = "INSERT_KEY_HERE";
var TWITTER_CONSUMER_SECRET = "INSERT_SECRET_HERE";
 
passport.use(new TwitterStrategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"
},
function(token, tokenSecret, profile, done) {
// NOTE: You'll probably want to associate the Twitter profile with a
// user record in your application's DB.
var user = profile;
return done(null, user);
}
));
 
 
app.get('/', function(req, res){
res.send('Hello World');
});
 
app.get('/account',
ensureLoggedIn('/login'),
function(req, res) {
res.send('Hello ' + req.user.username);
});
 
app.get('/login',
function(req, res) {
res.send('<html><body><a href="/auth/twitter">Sign in with Twitter</a></body></html>');
});
app.get('/logout',
function(req, res) {
req.logout();
res.redirect('/');
});
 
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { successReturnToOrRedirect: '/', failureRedirect: '/login' }));
 
 
var server = app.listen(3000);
console.log('Express server started on port %s', server.address().port);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.