forked from AirVantage/zuorajs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
49 lines (38 loc) · 1.25 KB
/
auth.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
43
44
45
46
47
48
49
const { requestWithRetries, isRequestError, isStatusCodeError } = require('./requestPromiseUtils');
const shouldRetry = (err, nextTryCount) => {
if (nextTryCount > 5) {
return false;
}
return isRequestError(err) || (isStatusCodeError(err) && (err.statusCode === 403 || err.statusCode === 401));
};
const computeRetryDelay = (err, nextTryCount) => (Math.round(Math.random() * 100) + (nextTryCount * 750));
module.exports = (zuoraClient) => {
let accessToken;
let renewalTime;
const uri = `${zuoraClient.config.apiUrl}/oauth/token`;
const getAccessToken = async () => {
if (accessToken && Date.now() <= renewalTime) {
return accessToken;
}
const options = {
method: 'POST',
uri,
form: {
client_id: zuoraClient.config.clientId,
client_secret: zuoraClient.config.clientSecret,
grant_type: 'client_credentials',
},
json: true,
};
const response = await requestWithRetries(options, shouldRetry, computeRetryDelay);
if (!response) {
throw new Error('ZuoraJS: Auth: Empty Response');
}
accessToken = response.access_token;
renewalTime = Date.now() + ((response.expires_in * 1000) - 60000);
return accessToken;
};
return {
getAccessToken,
};
};