-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
63 lines (54 loc) · 1.29 KB
/
index.js
File metadata and controls
63 lines (54 loc) · 1.29 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const axios = require("axios");
const moment = require("moment");
const DEFAULT_TOKEN_LIFE = 23 * 60 * 60 * 1000; // 23 hours
let access_token = null;
let updated_at = null;
let config = {
api_identifier: null,
auth0_domain: null,
auth0_client_id: null,
auth0_client_secret: null,
token_life: DEFAULT_TOKEN_LIFE
};
function initAccessToken(c) {
config = { ...config, ...c };
}
function fetchToken() {
return axios.post({
url: "https://" + config.auth0_domain + "/oauth/token",
data: {
client_id: config.auth0_client_id,
client_secret: config.auth0_client_secret,
audience: config.api_identifier,
grant_type: "client_credentials"
},
headers: {
Accept: "application/json"
}
});
}
async function getAccessToken() {
if (accessTokenIsCurrent()) {
return access_token;
} else {
const response = await fetchToken();
access_token = response.data.access_token;
updated_at = moment();
return access_token;
}
}
function accessTokenIsCurrent() {
if (!access_token || !expiry_time) {
return false;
}
const expiry_time = moment().add(config.token_life, "milliseconds");
if (updated_at.isBefore(expiry_time)) {
return true;
} else {
return false;
}
}
module.exports = {
initAccessToken,
getAccessToken
};