-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathToken.js
41 lines (36 loc) · 893 Bytes
/
Token.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
*/
var request = require('request');
const {promisify} = require('util');
var currentToken;
var tokenExpiration = 0;
function main(params) {
if (tokenExpiration < Date.now())
return refresh(params);
else
return Promise.resolve({
jwt: currentToken,
source: "cache"
});
}
async function refresh(params) {
var postPromise = promisify(request.post);
var res = await postPromise('https://api.watsonwork.ibm.com/oauth/token', {
auth: {
user: params.WatsonWorkspace.AppId,
pass: params.WatsonWorkspace.AppSecret
},
json: true,
form: {
grant_type: 'client_credentials'
}
});
currentToken = res.body.access_token;
tokenExpiration = Date.now() + ((res.body.expires_in - 2) * 1000);
return {
source: "refresh",
jwt: currentToken
};
}
exports.main = main;
exports.reset = function() { tokenExpiration = 0; }