Skip to content

Instantly share code, notes, and snippets.

@GEverding
Created October 17, 2012 19:44
Show Gist options
  • Save GEverding/3907684 to your computer and use it in GitHub Desktop.
Save GEverding/3907684 to your computer and use it in GitHub Desktop.
Log Into Twitter w/ Node
module.exports = {
twitter: {
consumer_key: 'YOUR CONSUMER KEY',
consumer_secret: 'YOUR CONSUMER SECERET'
}
var oauth = require('oauth');
var config = require('config');
var twitter = function() {
return new oauth.OAuth(
'https://api.twitter.com/oauth/request_token', 'https://api.twitter.com/oauth/access_token',
config.twitter.consumerKey, config.twitter.consumerSecret,
'1.0A', 'http://local.host:5001/auth/twitter/callback', 'HMAC-SHA1');
}
app.get('/', function(req, res){
res.render('index', {});
}
app.get('/auth/twitter', function(req, res){
twitter().getOAuthRequestToken(function(error, oauthToken, oauthTokenSecret, results){
if (error) {
res.send("Error getting OAuth request token : " + error, 500);
} else {
req.session.oauthRequestToken = oauthToken;
req.session.oauthRequestTokenSecret = oauthTokenSecret;
res.redirect("https://api.twitter.com/oauth/authorize?oauth_token="+req.session.oauthRequestToken);
}
});
});
app.get('/auth/twitter/callback', function(req, res){
twitter().getOAuthAccessToken(req.session.oauthRequestToken, req.session.oauthRequestTokenSecret, req.query.oauth_verifier, function(error, oauthAccessToken, oauthAccessTokenSecret, results) {
if (error) {
res.send("Error getting OAuth access token : " + error + "["+oauthAccessToken+"]"+ "["+oauthAccessTokenSecret+"]"+ "["+sys.inspect(results)+"]", 500);
} else {
req.session.oauthAccessToken = oauthAccessToken;
req.session.oauthAccessTokenSecret = oauthAccessTokenSecret;
// Right here is where we would write out some nice user stuff
twitter().get("http://api.twitter.com/1.1/account/verify_credentials.json", req.session.oauthAccessToken, req.session.oauthAccessTokenSecret, function (error, data, response) {
if (error) {
res.send("Error getting twitter screen name : " + error, 500);
} else {
console.log("data is %j", JSON.parse(data));
data = JSON.parse(data);
req.session.twitterScreenName = data["screen_name"];
res.redirect('/')
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment