Created
February 20, 2020 20:30
-
-
Save iamdaniele/4470963da5c9543f34bee619d403f320 to your computer and use it in GitHub Desktop.
Get OAuth 1.0a access tokens for your user
This file contains hidden or 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
const qs = require('querystring'); | |
const request = require('request'); | |
const readline = require('readline').createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
const util = require('util'); | |
const get = util.promisify(request.get); | |
const post = util.promisify(request.post); | |
const package = require('./package.json'); | |
const [consumer_key, consumer_secret] = process.argv.slice(2); | |
if (!consumer_key || !consumer_secret) { | |
console.error('One or more credentials are missing'); | |
process.exit(-1); | |
} | |
const requestTokenURL = new URL('https://api.twitter.com/oauth/request_token'); | |
const accessTokenURL = new URL('https://api.twitter.com/oauth/access_token'); | |
const authorizeURL = new URL('https://api.twitter.com/oauth/authorize'); | |
async function input(prompt) { | |
return new Promise(async (resolve, reject) => { | |
readline.question(prompt, (out) => { | |
readline.close(); | |
resolve(out); | |
}); | |
}); | |
} | |
async function requestToken() { | |
const oAuthConfig = { | |
callback: 'oob', | |
consumer_key: consumer_key, | |
consumer_secret: consumer_secret, | |
}; | |
const req = await post({url: requestTokenURL, oauth: oAuthConfig}); | |
if (req.body) { | |
return qs.parse(req.body); | |
} else { | |
throw new Error('Cannot get an OAuth request token'); | |
} | |
} | |
async function accessToken({oauth_token, oauth_token_secret}, verifier) { | |
const oAuthConfig = { | |
consumer_key: consumer_key, | |
consumer_secret: consumer_secret, | |
token: oauth_token, | |
token_secret: oauth_token_secret, | |
verifier: verifier, | |
}; | |
const req = await post({url: accessTokenURL, oauth: oAuthConfig}); | |
if (req.body) { | |
return qs.parse(req.body); | |
} else { | |
throw new Error('Cannot get an OAuth request token'); | |
} | |
} | |
(async () => { | |
try { | |
// Get request token | |
const oAuthRequestToken = await requestToken(); | |
// Get authorization | |
authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token); | |
console.log('Please go here and authorize:', authorizeURL.href); | |
const pin = await input('Paste the PIN here: '); | |
// Get the access token | |
const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim()); | |
console.log(oAuthAccessToken); | |
} catch(e) { | |
console.error(e); | |
process.exit(-1); | |
} | |
process.exit(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment