Created
January 3, 2011 20:07
-
-
Save jdub/763879 to your computer and use it in GitHub Desktop.
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
/* | |
* CONNECT/STACK STYLE TWITTER "O"AUTHENTICATION MIDDLEWARE | |
*/ | |
// FIXME: options should include cookie lifetime | |
Twitter.prototype.auth = function(mount) { | |
var self = this, | |
cookie = require('cookie'), | |
url = require('url'), | |
mount = mount || '/twauth'; | |
return function handle(req, res, next) { | |
try { | |
var twauth = JSON.parse(req.getSecureCookie('twauth')); | |
} catch (error) { | |
var twauth = null; | |
} | |
if ( twauth && twauth.screen_name && twauth.access_token_secret ) { | |
return next(); | |
} | |
// FIXME: these don't reflect how the server might do http/https | |
var purl = url.parse('http://' + req.headers.host + req.url, true); | |
if ( !self.oauth._authorize_callback ) { | |
var pmount = url.parse('http://' + req.headers.host + mount, true); | |
self.oauth._authorize_callback = pmount.href; | |
} | |
// Returning from Twitter with oauth_token | |
if ( purl.pathname == mount && purl.query && purl.query.oauth_token && twauth && twauth.oauth_token_secret ) { | |
self.oauth.getOAuthAccessToken( | |
purl.query.oauth_token, | |
twauth.oauth_token_secret, | |
purl.query.oauth_verifier, | |
function(error, access_token, access_token_secret, params) { | |
var user_id = params && params.user_id, | |
screen_name = params && params.screen_name; | |
if ( error ) { | |
return next(error); | |
} else { | |
res.setSecureCookie('twauth', JSON.stringify({ | |
user_id: user_id, | |
screen_name: screen_name, | |
access_token: access_token, | |
access_token_secret: access_token_secret | |
}), {}); | |
// FIXME: remember where we came from | |
res.writeHead(302, {'Location': '/'}); | |
res.end(); | |
return; | |
} | |
}); | |
// Begin OAuth transaction | |
} else { | |
self.oauth.getOAuthRequestToken( | |
function(error, oauth_token, oauth_token_secret, oauth_authorize_url, params) { | |
if ( error ) { | |
return next(error); | |
} else { | |
res.setSecureCookie('twauth', JSON.stringify({ | |
oauth_token: oauth_token, | |
oauth_token_secret: oauth_token_secret | |
}), {}); | |
res.writeHead(302, { | |
'Location': self.options.authorize_url + '?' | |
+ querystring.stringify({oauth_token: oauth_token}) | |
}); | |
res.end(); | |
return; | |
} | |
}); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment