-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhelpers.js
235 lines (204 loc) · 6.85 KB
/
helpers.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/**
* This file contains helper functions utilized by this package.
*/
'use strict';
//***********
//* Modules *
//***********
const httpClient = require('axios');
const assert = require('assert');
const Validator = require('jsonschema').Validator;
const schema = require('./schema.js');
const querystring = require('querystring');
//*************
//* Constants *
//*************
/**
* The number of milliseconds in one second.
*
* @type {number}
*/
const millisecondsPerSecond = 1000;
/**
* The time, in seconds, prior to the actual expiration time of an access token, at which an access token will be
* considered to be expired.
*
* @type {number}
*/
const aboutToExpireThresholdSeconds = 60;
//*************
//* Functions *
//*************
/**
* Validates the contents of an options Object.
*
* @param options
* An object of the following format:
* {
* clientId: string,
* clientSecret: string,
* redirectUri: string,
* apiUri: string
* }
* In order for the options object to be valid, the object must exist, and all its properties must be non-empty string
* values.
*/
function validateOptions(options) {
assert(options, 'options must be provided');
const validator = new Validator();
const validatorResult = validator.validate(options, schema.packageOptions);
assert(validatorResult.valid, 'options must be valid');
}
/**
* Validates a sandbox authentication code.
*/
function validateSandboxAuthcode(authcode) {
assert(authcode, 'authcode must be provided');
const validator = new Validator();
const validatorResult = validator.validate(authcode, schema.sandboxAuthCodes);
assert(validatorResult.valid, validatorResult.errors.length? validatorResult.errors[0].message : 'unknown error');
}
/**
* Validates the contents of a oauthTokens object.
*
* @param oauthTokens
* An object of the following format:
* {
* "timestamp": epochMilliseconds,
* "dexcomOAuthToken": {
* "access_token": "your access token",
* "expires_in": timeToLiveInSeconds,
* "token_type": "Bearer",
* "refresh_token": "your refresh token"
* }
* }
*
* NOTE: field level validation was commented out because we have no control over what Dexcom decides to do.
* It's their token, not ours.
*/
function validateOAuthTokens(oauthTokens) {
assert(oauthTokens, 'oauthTokens must be provided');
/*
const validator = new Validator();
validator.addSchema(schema.dexcomOAuthToken, '/DexcomOAuthToken');
validator.addSchema(schema.epochTime, '/EpochTime');
const validatorResult = validator.validate(oauthTokens, schema.oauthTokens);
assert(validatorResult.valid, 'oauthTokens must be valid');
*/
}
/**
* Validates the components of a time window.
*
* @param startTime
* A number that represents an epoch time, in milliseconds. This value must be less than endTime.
*
* @param endTime
* A number that represents an epoch time, in milliseconds. This value must be greater than startTime.
*/
function validateTimeWindow(startTime, endTime) {
assert(startTime, 'startTime must be provided');
assert(endTime, 'endTime must be provided');
const validator = new Validator();
const startTimeValidatorResult = validator.validate(startTime, schema.epochTime);
assert(startTimeValidatorResult.valid, 'startTime must be valid');
const endTimeValidatorResult = validator.validate(endTime, schema.epochTime);
assert(endTimeValidatorResult.valid, 'endTime must be valid');
assert(startTime < endTime, 'startTime must be < endTime');
}
/**
* Gets the "Dexcomified" representation of an epoch timestamp. Dexcom uses the first 19 characters of the
* ISO 8601 time representation as its "date/time" representation.
*
* @see https://en.wikipedia.org/wiki/ISO_8601
*
* @param epochTime
* A number that represents the UTC epoch time, in milliseconds.
*
* @returns A string that matches the following format: "YYYY-MM-DDThh:mm:ss".
*/
function dexcomifyEpochTime(epochTime) {
const date = new Date(epochTime);
const dateString = date.toISOString().slice(0, 19);
return dateString;
}
/**
* Uses the Dexcom OAuth API to obtain a new access token if the access token passed to this function has expired,
* or is about to expire.
*
* @param options
* The Dexcom access options. The caller is assumed to have validated the options object prior to invoking this
* function.
*
* @param oauthTokens
* An object of the following format:
* {
* "timestamp": epochMilliseconds,
* "dexcomOAuthToken": {
* "access_token": "your access token",
* "expires_in": timeToLiveInSeconds,
* "token_type": "Bearer",
* "refresh_token": "your refresh token"
* }
* }
*
* @param force
* A boolean value that indicates if a new access token is to be acquired, regardless of the state of the access
* token passed to this function.
*
* @returns a Promise that wraps an Object of the following format:
* {
* "timestamp": epochMilliseconds,
* "dexcomOAuthToken": {
* "access_token": "your access token",
* "expires_in": timeToLiveInSeconds,
* "token_type": "Bearer",
* "refresh_token": "your refresh token"
* }
* }
*
* Notes:
*
* 1. Dexcom access tokens are not guaranteed to be JSON Web Tokens (JWTs).
* 2. The timestamp property represents the time, in epoch milliseconds, when the Dexcom access token was obtained.
* Downstream users may use the timestamp and the dexcomOAuthToken.expires_in values to determine if the Dexcom
* access token has expired and must be refreshed.
*/
async function refreshAccessToken(options, oauthTokens, force) {
if (!force &&
(Date.now() + (aboutToExpireThresholdSeconds * millisecondsPerSecond) <
oauthTokens.timestamp + (oauthTokens.dexcomOAuthToken.expires_in * millisecondsPerSecond)))
{
return oauthTokens;
}
// @see https://developer.dexcom.com/authentication
// Step Six: Refresh Tokens
const urlEncodedForm = querystring.stringify({
client_id: options.clientId,
client_secret: options.clientSecret,
refresh_token: oauthTokens.dexcomOAuthToken.refresh_token,
grant_type: 'refresh_token',
redirect_uri: options.redirectUri,
});
const httpConfig = {
headers: {
"cache-control": "no-cache",
"Content-Type": "application/x-www-form-urlencoded"
}
};
const result = await httpClient.post(`${options.apiUri}/v2/oauth2/token`, urlEncodedForm, httpConfig);
//console.log(result.status);
//console.log(result.data);
return {
timestamp: new Date().getTime(),
dexcomOAuthToken: result.data,
};
}
//**************
//* Public API *
//**************
exports.validateOptions = validateOptions;
exports.validateSandboxAuthcode = validateSandboxAuthcode;
exports.dexcomifyEpochTime = dexcomifyEpochTime;
exports.validateTimeWindow = validateTimeWindow;
exports.validateOAuthTokens = validateOAuthTokens;
exports.refreshAccessToken = refreshAccessToken;