-
Notifications
You must be signed in to change notification settings - Fork 27
/
TokenManager.js
46 lines (40 loc) · 1017 Bytes
/
TokenManager.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
var Promise = require("bluebird");
var EXPIRES_IN_LEEWAY = 60;
function now() {
return parseInt(Date.now() / 1000, 10);
}
module.exports = function TokenManager(client, initialState) {
var state = Object.assign(
{ instance: null, expiresIn: null, updatedAt: null },
initialState
);
var updateToken = function() {
state.updatedAt = now();
state.expiresIn = null;
state.instance = client.auth.client().then(
function(token) {
state.expiresIn = token.expires_in;
return token;
},
function(err) {
state.instance = null;
return Promise.reject(err);
}
);
};
var isTokenFresh = function() {
return (
state.expiresIn === null || // token is updating
state.updatedAt + state.expiresIn > now() + EXPIRES_IN_LEEWAY
);
};
return {
getToken: function() {
if (state.instance === null || !isTokenFresh()) {
updateToken();
}
return state.instance;
},
_state: state
};
};