Created
December 5, 2018 23:50
-
-
Save appellation/1e8f505fa799a4104e7e51165584919b to your computer and use it in GitHub Desktop.
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
axios.interceptors.request.use((req) => { | |
let { token, secret } = req; | |
if (token) delete req.token; | |
else token = process.env.TW_TOKEN; | |
if (secret) delete req.secret; | |
else secret = process.env.TW_TOKEN_SECRET; | |
const oauth = { | |
oauth_consumer_key: process.env.TW_KEY, | |
oauth_nonce: crypto.randomBytes(20).toString('hex'), | |
oauth_signature_method: 'HMAC-SHA1', | |
oauth_timestamp: Math.floor(Date.now() / 1e3), | |
oauth_token: token, | |
oauth_version: '1.0', | |
}; | |
Object.entries(req.params).forEach(([k, v]) => { | |
if (v === undefined) delete req.params[k]; | |
}); | |
// gather all request data and encode it | |
const params = Object.entries({ | |
...req.params, | |
...req.body, | |
...oauth, | |
}) | |
.map(kv => kv.map(encodeURIComponent).join('=')) | |
.sort() | |
.join('&'); | |
// prepare encrypted values | |
const base = [ | |
req.method.toUpperCase(), | |
encodeURIComponent(req.baseURL + req.url), | |
encodeURIComponent(params), | |
].join('&'); | |
const key = [ | |
encodeURIComponent(process.env.TW_SECRET), | |
encodeURIComponent(secret), | |
].join('&'); | |
// encrypt values | |
const signature = crypto.createHmac('sha1', key); | |
signature.update(base); | |
oauth.oauth_signature = signature.digest('base64'); | |
const header = Object.entries(oauth) | |
.map(([k, v]) => `${encodeURIComponent(k)}="${encodeURIComponent(v)}"`) | |
.sort() | |
.join(', '); | |
req.headers.Authorization = `OAuth ${header}`; | |
return req; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment