-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathTokenRefresher.js
78 lines (64 loc) · 1.96 KB
/
TokenRefresher.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { ObservableValue } from "../../observable/ObservableValue.js";
export class TokenRefresher {
constructor({
refreshToken,
accessToken,
accessTokenExpiresAt,
anticipation,
clock,
}) {
this._refreshToken = new ObservableValue(refreshToken);
this._accessToken = new ObservableValue(accessToken);
this._accessTokenExpiresAt = new ObservableValue(accessTokenExpiresAt);
this._anticipation = anticipation;
this._clock = clock;
}
async start(hsApi) {
this._hsApi = hsApi;
if (this.needsRenewing) {
await this.renew();
}
this._renewingLoop();
}
stop() {
// TODO
}
get needsRenewing() {
const remaining = this._accessTokenExpiresAt.get() - this._clock.now();
const anticipated = remaining - this._anticipation;
return anticipated < 0;
}
async _renewingLoop() {
while (true) {
const remaining =
this._accessTokenExpiresAt.get() - this._clock.now();
const anticipated = remaining - this._anticipation;
if (anticipated > 0) {
this._timeout = this._clock.createTimeout(anticipated);
await this._timeout.elapsed();
}
await this.renew();
}
}
async renew() {
const response = await this._hsApi
.refreshToken(this._refreshToken.get())
.response();
if (response["refresh_token"]) {
this._refreshToken.set(response["refresh_token"]);
}
this._accessToken.set(response["access_token"]);
this._accessTokenExpiresAt.set(
this._clock.now() + response["expires_in_ms"]
);
}
get accessToken() {
return this._accessToken;
}
get accessTokenExpiresAt() {
return this._accessTokenExpiresAt;
}
get refreshToken() {
return this._refreshToken;
}
}