Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial stab at built-in stack/connect style oauth middleware

  • Loading branch information...
commit 85d43c406c1b0c508bfc9bc1bab8c048138aa29f 1 parent 18c19ee
@jdub jdub authored
Showing with 77 additions and 0 deletions.
  1. +77 −0 lib/twitter.js
View
77 lib/twitter.js
@@ -211,6 +211,83 @@ Twitter.prototype.stream = function(method, params, callback) {
/*
+ * 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;
+ }
+ });
+ }
+ };
+}
+
+
+/*
* CONVENIENCE FUNCTIONS (not API stable!)
*/
Please sign in to comment.
Something went wrong with that request. Please try again.