Skip to content

Commit 0e100ff

Browse files
authored
Merge pull request #1 from olgierdp/master
initial commit
2 parents 7fcd938 + 1876d63 commit 0e100ff

6 files changed

Lines changed: 2564 additions & 0 deletions

File tree

.travis.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
language: node_js
2+
node_js:
3+
- "10"

app.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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;

manifest.yml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
applications:
2+
- path: .
3+
memory: 256M
4+
instances: 1
5+
domain: mybluemix.net
6+
name: apiproxy
7+
host: wwproxy
8+
disk_quota: 1024M

0 commit comments

Comments
 (0)