Skip to content

Instantly share code, notes, and snippets.

@smockle
Created May 26, 2015 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smockle/84027158531395839583 to your computer and use it in GitHub Desktop.
Save smockle/84027158531395839583 to your computer and use it in GitHub Desktop.
Almost working Twitter OAuth API signing code for authentication.
sign(href, method) {
return co(function* () {
let token = yield this.token;
let consumerKey = encodeURIComponent(process.env.TWITTER_CONSUMER_KEY);
let consumerSecret = encodeURIComponent(process.env.TWITTER_CONSUMER_SECRET);
let accessToken = encodeURIComponent(process.env.TWITTER_ACCESS_TOKEN);
let nonce = btoa(Random.string(32));
let timestamp = new Date().getTime();
let options = {
port: href.protocol === 'https:' ? 443 : 80,
method: method
};
let params = JSON.parse(JSON.stringify(href.query));
params.oauth_consumer_key = consumerKey;
params.oauth_nonce = nonce;
params.oauth_signature_method = "HMAC-SHA1";
params.oauth_timestamp = timestamp;
params.oauth_token = this.token;
let paramString = "";
Object.keys(params).sort().forEach(function(key, index, array) {
paramString += `${key}=${params[key]}`;
if (index < array.length - 1) paramString += '&';
});
paramString = encodeURIComponent(paramString);
let signatureBaseString = `${method}&${href.href}&${paramString}`;
let signingKey = `${consumerSecret}&${accessToken}`;
let signature = encodeURIComponent(crypto.createHmac('sha1', signingKey).update(signatureBaseString).digest('base64'));
options.headers = {
'Authorization': `OAuth oauth_consumer_key="${consumerKey}", oauth_nonce="${nonce}", oauth_signature="${signature}", oauth_signature_method="HMAC-SHA1", oauth_timestamp="${timestamp}", oauth_token="${accessToken}", oauth_version="1.0"`,
'Accept-Encoding': 'gzip'
};
Object.keys(options).forEach(function(key) {
href[key] = options[key];
});
return href;
}.bind(this));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment