Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Emit event on twitter connected

  • Loading branch information...
commit 9c676b9148f9315dd05f475ea659a8b0972d3cce 1 parent 3f5286a
Anatoliy Chakkaev authored

Showing 2 changed files with 103 additions and 70 deletions. Show diff stats Hide diff stats

  1. +25 0 README.md
  2. +78 70 index.js
25 README.md
Source Rendered
@@ -16,6 +16,8 @@ Configure `config/twitter.yml` with your twitter app credentials:
16 16 url: "http://example.com"
17 17 key: key
18 18 secret: secret
  19 + connectPath: /twitter_connect
  20 + callbackPath: /twitter_callback
19 21
20 22 Callback path: `/twitter_callback`
21 23
@@ -25,3 +27,26 @@ Usage
25 27 In application add link to twitter connect `/twitter_connect`:
26 28
27 29 <%- link_to("Connect to twitter", '/twitter_connect') %>
  30 +
  31 +By default twitter connect path is `/twitter_connect`, but it can be configured in `config/twitter.yml`
  32 +Callback path can be configured too, see example below.
  33 +
  34 +When app will connected with twitter, global `app` object will receive message `twitterConnect`
  35 +as event emitter, so you can:
  36 +
  37 + app.on('twitterConnect', function (user, req) {
  38 + // find or create account for user
  39 + // save user id in req.session
  40 + });
  41 +
  42 +It is fine put code like this into user model (`app/models/user.js`):
  43 +
  44 + app.on('twitterConnect', function (twitter, req) {
  45 + User.findOne({twitterId: twitter.id}, function (err, user) {
  46 + if (user) {
  47 + req.session.user_id = user.id;
  48 + } else {
  49 + User.register({twitter: twitter});
  50 + }
  51 + });
  52 + });
148 index.js
@@ -6,28 +6,17 @@ var _twitterConsumerSecret;
6 6 var _host;
7 7 var _apiHost = 'http://twitter.com';
8 8 var _apiSecureHost = 'https://twitter.com';
  9 +var _callbackPath = '/twitter_callback';
  10 +
  11 +var TWITTER_CONNECT_EVENT = 'twitterConnect';
9 12
10 13 function consumer () {
11 14 return new oauth.OAuth(
12 15 _apiHost + "/oauth/request_token", _apiSecureHost + "/oauth/access_token",
13   - _twitterConsumerKey, _twitterConsumerSecret, "1.0A", _host + "/twitter_callback", "HMAC-SHA1");
14   -}
15   -
16   -function redirectBack (req, res, flash) {
17   - var location = req.session && req.session.beforeTwitterAuth || '/';
18   - console.log('redirect to', location);
19   - delete req.session.beforeTwitterAuth;
20   - if (flash) {
21   - if (flash.error) {
22   - req.flash('error', flash.error);
23   - } else if (flash.info) {
24   - req.flash('info', flash.info);
25   - }
26   - }
27   - res.redirect(location);
  16 + _twitterConsumerKey, _twitterConsumerSecret, "1.0A", _host + _callbackPath, "HMAC-SHA1");
28 17 }
29 18
30   -exports.init = function () {
  19 +exports.init = function initTwitterConnect () {
31 20 try {
32 21 var settings = require('yaml').eval(require('fs').readFileSync(app.root + '/config/twitter.yml').toString('utf8'))[app.settings.env];
33 22 } catch (e) {
@@ -35,67 +24,86 @@ exports.init = function () {
35 24 console.log('Error:', e.message);
36 25 }
37 26 if (settings) {
38   - _twitterConsumerKey = settings.key;
39   - _twitterConsumerSecret = settings.secret;
40   - _host = settings.url;
  27 + initApp(settings);
  28 + }
  29 +};
41 30
42   - app.get('/twitter_connect', function (req, res) {
43   - console.log(req.headers);
44   - req.session.beforeTwitterAuth = req.headers.referer;
45   - console.log('save referer:', req.session.beforeTwitterAuth);
46   - delete req.session.twitter;
47   - consumer().getOAuthRequestToken(gotToken);
  31 +function initApp (settings) {
  32 + _twitterConsumerKey = settings.key;
  33 + _twitterConsumerSecret = settings.secret;
  34 + _host = settings.url;
48 35
49   - function gotToken (error, oauthToken, oauthTokenSecret, results) {
50   - if (error) {
51   - redirectBack(req, res, {error: "Error getting OAuth request token : " + sys.inspect(error)});
52   - } else {
53   - req.session.twitter = {
54   - oauthRequestToken: oauthToken,
55   - oauthRequestTokenSecret: oauthTokenSecret
56   - };
57   - console.log('got new token');
58   - res.redirect(_apiSecureHost + "/oauth/authorize?oauth_token=" + oauthToken);
59   - }
  36 + app.get(settings.connectPath || '/twitter_connect', function (req, res) {
  37 + console.log(req.headers);
  38 + req.session.beforeTwitterAuth = req.headers.referer;
  39 + delete req.session.twitter;
  40 + consumer().getOAuthRequestToken(gotToken);
  41 +
  42 + function gotToken (error, oauthToken, oauthTokenSecret, results) {
  43 + if (error) {
  44 + redirectBack(req, res, {error: "Error getting OAuth request token : " + sys.inspect(error)});
  45 + } else {
  46 + req.session.twitter = {
  47 + oauthRequestToken: oauthToken,
  48 + oauthRequestTokenSecret: oauthTokenSecret
  49 + };
  50 + res.redirect(_apiSecureHost + "/oauth/authorize?oauth_token=" + oauthToken);
60 51 }
61   - });
  52 + }
  53 + });
  54 +
  55 + if (settings.callbackPath) {
  56 + _callbackPath = callbackPath;
  57 + }
62 58
63   - app.get('/twitter_callback', function (req, res) {
64   - console.log('callback');
65   - consumer().getOAuthAccessToken(
66   - req.session.twitter.oauthRequestToken,
67   - req.session.twitter.oauthRequestTokenSecret,
68   - req.query.oauth_verifier,
69   - twitterCallback
70   - );
  59 + app.get(settings.callbackPath || '/twitter_callback', function (req, res) {
  60 + consumer().getOAuthAccessToken(
  61 + req.session.twitter.oauthRequestToken,
  62 + req.session.twitter.oauthRequestTokenSecret,
  63 + req.query.oauth_verifier,
  64 + twitterCallback
  65 + );
71 66
72   - function twitterCallback (error, oauthAccessToken, oauthAccessTokenSecret, results) {
73   - if (error) {
74   - res.send("Error getting OAuth access token : " + sys.inspect(error), 500);
75   - return;
76   - }
77   - consumer().get(
78   - _apiHost + "/account/verify_credentials.json",
79   - oauthAccessToken,
80   - oauthAccessTokenSecret,
81   - gotData);
  67 + function twitterCallback (error, oauthAccessToken, oauthAccessTokenSecret, results) {
  68 + if (error) {
  69 + res.send("Error getting OAuth access token : " + sys.inspect(error), 500);
  70 + return;
  71 + }
  72 + consumer().get(
  73 + _apiHost + "/account/verify_credentials.json",
  74 + oauthAccessToken,
  75 + oauthAccessTokenSecret,
  76 + gotData);
82 77
83   - function gotData (error, data, response) {
84   - if (error) {
85   - redirectBack(req, res, {error: "Error getting twitter screen name : " + sys.inspect(error)});
86   - console.log('gotData:', error);
87   - } else {
88   - if (typeof data === 'string') {
89   - data = JSON.parse(data);
90   - }
91   - req.session.twitter = data;
92   - req.session.twitter.oauthAccessToken = oauthAccessToken;
93   - req.session.twitter.oauthAccessTokenSecret = oauthAccessTokenSecret;
94   - console.log(req.session.twitter);
95   - redirectBack(req, res);
  78 + function gotData (error, data, response) {
  79 + if (error) {
  80 + redirectBack(req, res, {error: "Error getting twitter screen name : " + sys.inspect(error)});
  81 + console.log('gotData:', error);
  82 + } else {
  83 + if (typeof data === 'string') {
  84 + data = JSON.parse(data);
96 85 }
  86 + req.session.twitter = data;
  87 + req.session.twitter.oauthAccessToken = oauthAccessToken;
  88 + req.session.twitter.oauthAccessTokenSecret = oauthAccessTokenSecret;
  89 + app.emit(TWITTER_CONNECT_EVENT, req.session.twitter, req, res);
  90 + redirectBack(req, res);
97 91 }
98 92 }
99   - });
  93 + }
  94 + });
  95 +}
  96 +
  97 +function redirectBack (req, res, flash) {
  98 + var location = req.session && req.session.beforeTwitterAuth || '/';
  99 + delete req.session.beforeTwitterAuth;
  100 + if (flash) {
  101 + if (flash.error) {
  102 + req.flash('error', flash.error);
  103 + } else if (flash.info) {
  104 + req.flash('info', flash.info);
  105 + }
100 106 }
101   -};
  107 + res.redirect(location);
  108 +}
  109 +

0 comments on commit 9c676b9

Please sign in to comment.
Something went wrong with that request. Please try again.