|
| 1 | +const request = require('request'); |
| 2 | +const httpProxy = require('http-proxy'); |
| 3 | +const http = require('http'); |
| 4 | +const auth = require('basic-auth'); |
| 5 | + |
| 6 | +const log = require('debug').debug('watsonwork-apiproxy'); |
| 7 | + |
| 8 | +const tokens = {}; // token cache |
| 9 | + |
| 10 | +const requestToken = (clientId, clientSecret, cb) => { |
| 11 | + request.post('https://api.watsonwork.ibm.com/oauth/token', { |
| 12 | + auth: { |
| 13 | + user: clientId, |
| 14 | + pass: clientSecret |
| 15 | + }, |
| 16 | + json: true, |
| 17 | + form: { |
| 18 | + grant_type: 'client_credentials' |
| 19 | + } |
| 20 | + }, (err, res) => { |
| 21 | + if (err || res.statusCode !== 200) { |
| 22 | + return cb(err || new Error(res.statusCode)); |
| 23 | + } |
| 24 | + return cb(null, res.body); |
| 25 | + }); |
| 26 | +}; |
| 27 | + |
| 28 | +const getToken = (clientId, clientSecret, cb) => { |
| 29 | + let id = clientId + clientSecret; |
| 30 | + if (tokens[id] && tokens[id].exp - Date.now() > 60) { |
| 31 | + log('Token in cache'); |
| 32 | + return cb(null, tokens[id].token); |
| 33 | + } |
| 34 | + requestToken(clientId, clientSecret, (err, res) => { |
| 35 | + if (err) return cb(err); |
| 36 | + log('Got new token'); |
| 37 | + tokens[id] = { token: res.access_token, exp: res.expires_in }; |
| 38 | + return cb(null, tokens[id].token); |
| 39 | + }); |
| 40 | +}; |
| 41 | + |
| 42 | +const proxy = httpProxy.createProxy(); |
| 43 | +const server = http.createServer((req, res) => { |
| 44 | + let basic = auth(req); |
| 45 | + if (!basic) { |
| 46 | + res.writeHead(401, 'No Basic Authorization header'); |
| 47 | + res.end(); |
| 48 | + return; |
| 49 | + } |
| 50 | + getToken(basic.name, basic.pass, (err, token) => { |
| 51 | + if (err) { |
| 52 | + log(err); |
| 53 | + res.writeHead(401, 'Could not get the token'); |
| 54 | + res.end(); |
| 55 | + return; |
| 56 | + } |
| 57 | + proxy.web(req, res, { |
| 58 | + target: 'https://api.watsonwork.ibm.com/', |
| 59 | + changeOrigin: true, |
| 60 | + headers: { 'Authorization': `Bearer ${token}` } |
| 61 | + }); |
| 62 | + }); |
| 63 | +}); |
| 64 | +server.listen(process.env.PORT); |
| 65 | + |
| 66 | +module.exports = server; |
0 commit comments