This repository has been archived by the owner on May 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.js
92 lines (80 loc) · 2.83 KB
/
token.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
var https = require('https');
module.exports.config = {};
var accessTokenObj;
/*
* Checks to see if we already have a valid access token, if so, proceed
* with that. If not, either generate a new one, or refresh the current.
*
* @callback callback
*
*/
module.exports.authenticate = function(callback) {
if(typeof accessTokenObj !== 'undefined') {
if(Date.now() > accessTokenObj.expires_datetime) {
// console.log('need to get a new token');
getAccessToken(callback);
} else {
// console.log('token valid, and not expired');
callback({ token: accessTokenObj });
}
} else {
// console.log('need to get a new token');
getAccessToken(callback);
}
};
/*
* Gets a new access token
*
* @callback callback
*
*/
var getAccessToken = function(callback) {
if(typeof module.exports.config.consumerKey === 'undefined' ||
typeof module.exports.config.consumerSecret === 'undefined')
throw new Error('Must specify consumer key and secret');
var combinedKey = module.exports.config.consumerKey+ ':' +
module.exports.config.consumerSecret,
encodedKey = new Buffer(combinedKey).toString('base64'),
postData = 'grant_type=client_credentials&scope=PRODUCTION',
postOptions = {
method: 'POST',
host: 'api-km.it.umich.edu',
path: '/token',
headers: {
'Authorization': 'Basic ' + encodedKey,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
},
postCallback = function(response) {
// non-standard response
if(response.statusCode !== 200) {
callback({ error: 'UM access token request returned non-200 ' +
'status code' });
return;
}
var tokenData = '';
response.on('data', function (chunk) {
tokenData += chunk;
});
response.on('end', function () {
try {
accessTokenObj = JSON.parse(tokenData);
} catch(e) {
callback({ error: 'JSON parse error: ' + e });
return;
}
accessTokenObj.expires_datetime = new Date();
accessTokenObj.expires_datetime = new Date(
accessTokenObj.expires_datetime.getTime() +
accessTokenObj.expires_in * 1000);
callback({ token: accessTokenObj });
});
},
postReq = https.request(postOptions, postCallback);
postReq.write(postData);
postReq.on('error', function(e) {
callback({ error: e.message });
});
postReq.end();
};