-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth2-client-service.js
42 lines (36 loc) · 1.23 KB
/
oauth2-client-service.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
42
const moment = require('moment');
const request = require('request');
// Storage token to avoid request token overhead and rate limit
let token;
let token_created_at;
exports.getToken = async function() {
return new Promise((resolve, reject) => {
// Check token expires time
if (token && (moment.now() < token_created_at + token.expires_in * 1000)) {
resolve(token.token_type + ' ' + token.access_token);
} else {
// If not valid then
// Get new access token at /oauth2/token
const options = {
method: 'POST',
uri: process.env.OAUTH2_SERVER_URL && (process.env.OAUTH2_SERVER_URL + '/oauth2/token'),
headers: {
authorization: `Basic ${Buffer(process.env.OAUTH2_CLIENT_ID + ':' + process.env.OAUTH2_CLIENT_SECRET).toString('base64')}`,
},
form: {
grant_type: 'client_credentials'
}
};
request(options, (error, response, body) => {
if (error) {
console.error(error);
reject(error);
} else {
token_created_at = moment.now();
token = JSON.parse(body);
resolve(token.token_type + ' ' + token.access_token);
}
})
}
});
};