Created
May 26, 2015 04:54
-
-
Save smockle/84027158531395839583 to your computer and use it in GitHub Desktop.
Almost working Twitter OAuth API signing code for authentication.
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
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