Skip to content

Instantly share code, notes, and snippets.

@Dakuan
Created July 1, 2013 11:01
Show Gist options
  • Save Dakuan/5899971 to your computer and use it in GitHub Desktop.
Save Dakuan/5899971 to your computer and use it in GitHub Desktop.
Authenticate with the Twitter API using OAuth and Node.js
var OAuth2 = require('OAuth').OAuth2;
var https = require('https');
var oauth2 = new OAuth2(KEY, SECRET, 'https://api.twitter.com/', null, 'oauth2/token', null);
oauth2.getOAuthAccessToken('', {
'grant_type': 'client_credentials'
}, function (e, access_token) {
console.log(access_token); //string that we can use to authenticate request
var options = {
hostname: 'api.twitter.com',
path: '/1.1/statuses/user_timeline.json?screen_name=mostlyharmlessd',
headers: {
Authorization: 'Bearer ' + access_token
}
};
https.get(options, function (result) {
var buffer = '';
result.setEncoding('utf8');
result.on('data', function (data) {
buffer += data;
});
result.on('end', function () {
var tweets = JSON.parse(buffer);
console.log(tweets); // the tweets!
});
});
});
@rob-bar
Copy link

rob-bar commented Aug 24, 2013

thanks for this,
I made a coffeescript helper

https = require('https')
http = require('http')
config = require('config.coffee')
OAuth2 = require('OAuth').OAuth2

exports.help =
    oauth2: new OAuth2(config.site.twitter.screenname.key, config.site.twitter.screenname.secret, 'https://api.twitter.com/', null, 'oauth2/token', null)

    securerequest: (options, callback) ->
        request = https.request options, (res)->
            data = []

            res.on 'data', (chunk)->
                data.push(chunk)

            res.on 'error', (e)->
                console.log "Got error: #{e.message}"

            res.on 'end', ()->
                data = JSON.parse data.join('')
                callback(data)
        request.end()

    request: (options, callback) ->
        request = http.request options, (res)->
            data = []

            res.on 'data', (chunk)->
                console.log chunk
                data.push(chunk)

            res.on 'error', (e)->
                console.log "Got error: #{e.message}"

            res.on 'end', ()->
                data = JSON.parse data.join('')
                callback(data)
        request.end()

    oauthtoken: (callback) ->
        oauth2.getOAuthAccessToken '', {'grant_type': 'client_credentials'}, (e, access_token) ->
            callback access_token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment