Created
November 14, 2019 12:09
-
-
Save t638403/07f98ed632998c09d7dda0dfb3a76233 to your computer and use it in GitHub Desktop.
request with hmac example
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
/*********************************************************************************************************************** | |
* MAKE REQUEST WITH HMAC TO API | |
**********************************************************************************************************************/ | |
const fs = require('fs'); | |
const http = require('https'); | |
const Hmmac = require('hmmac'); | |
const USER = process.env.HMAC_USER || '<username>'; | |
const SECRET = process.env.HMAC_SECRET || '<secret>'; | |
const SIGNED_HEADERS = process.env.HMAC_SIGNED_HEADERS || 'accept,date,host'; | |
const HOST = process.env.HMAC_HOST || '<host>'; | |
const PORT = process.env.HMAC_PORT || '443'; | |
const UPLOAD_FILE = process.env.HMAC_UPLOAD_FILE || null; | |
const METHOD = process.env.HMAC_METHOD || (UPLOAD_FILE ? 'POST' : 'GET'); | |
const PATH = process.env.HMAC_PATH || (UPLOAD_FILE ? '/data/engagement_stats' : '/data/candidates'); | |
const httpRequest = { | |
host : HOST, | |
port : PORT, | |
path : PATH, | |
method : METHOD, | |
body : '', | |
headers : { | |
'X-Auth-SignedHeaders' : SIGNED_HEADERS, | |
'Accept' : '*/*', | |
'Date' : new Date().toUTCString() | |
} | |
}; | |
if (UPLOAD_FILE) { | |
const data = fs.readFileSync(UPLOAD_FILE); | |
const boundary = `--${Math.random().toString(16).replace('.', '')}`; | |
const delimiter = `\r\n--${boundary}`; | |
const multipartBody = Buffer.concat([ | |
Buffer.from(`${delimiter}\r\nContent-Disposition: form-data; name="file"; filename="file.csv"\r\n\r\n`), | |
data, | |
Buffer.from(`${delimiter}--`)] | |
); | |
httpRequest.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary; | |
httpRequest.headers['Content-Length'] = multipartBody.length; | |
httpRequest.rbody = multipartBody; | |
} | |
const hmmac = new Hmmac({ | |
scheme : Hmmac.schemes.load('plain'), | |
signedHeaders : SIGNED_HEADERS.split(','), | |
}); | |
hmmac.sign(httpRequest, { key : USER, secret : SECRET }); | |
httpRequest.body = httpRequest.rbody || ''; | |
const req = http.request(httpRequest, res => { | |
console.log('\tdone.'); | |
console.log('\thandling response ...\n\n'); | |
let body = ''; | |
res.on('data', chunk => body += chunk); | |
res.on('end', () => { console.log('\n\n\tHTTP %s Response: %s', res.statusCode, body); process.exit(); }); | |
}); | |
console.log('\n\n\tmaking request ...'); | |
req.write(httpRequest.body); | |
req.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment