This repository was archived by the owner on Jan 23, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathv3client.js
206 lines (181 loc) · 5.41 KB
/
v3client.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
/*
* Copyright (C) 2017 TopCoder Inc., All Rights Reserved.
*
* V3 API client
*
* @version 1.0
* @author GFalcon
*/
"use strict";
/*jslint nomen: true*/
var request = require('request');
var _ = require('underscore');
var async = require('async');
var atob = require('atob');
/**
* The URL of the V3 API
*/
var v3url = process.env.TC_API_V3_URL || 'http://localhost:8084/v3/';
/**
* Cached V3 API tokens.
*
* This object stores V2 tokens as keys and V3 tokens as values
*/
var tokens = {};
/**
* Call the service. It handles both errors and bad response status codes.
*
* @param {Object} params - parameters for a request
* @param {Function<err, body>} callback - the callback function.
* It will get either an Error object or a response body.
*/
function callService(params, callback) {
params.json = true;
request(params, function (err, response, body) {
if (err) {
callback(err);
return;
}
/*jslint eqeq: true*/
if (response.statusCode != 200) {
/*jslint eqeq: false*/
callback(new Error('API ' + params.url + ' returned ' + response.statusCode + ' ' + (response.statusMessage || '')));
return;
}
callback(null, body);
});
}
/**
* Get the V3 API authorization token to use in subsequent calls
*
* @param {Object} connection - the connection object provided by ActionHero
* @param {Function<err, token>} callback - this function receives either an error,
* a V3 token or nothing at all (if the current connection's user is anonymous)
*/
function getToken(connection, callback) {
// Anonymous
if (_.isUndefined(connection.authToken)) {
callback();
return;
}
// Cached token
if (!_.isUndefined(tokens[connection.authToken]) && !isTokenExpired(tokens[connection.authToken])) {
callback(null, tokens[connection.authToken]);
return;
}
// Get the token by calling the API
callService({
url: v3url + 'authorizations',
method: 'POST',
body: {
param: {
externalToken: connection.authToken
}
}
}, function (err, body) {
if (err) {
callback(err);
} else {
tokens[connection.authToken] = body.result.content.token;
callback(null, body.result.content.token);
}
});
}
function urlBase64Decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!'
}
return decodeURIComponent(escape(atob(output)));//polyfill https://github.com/davidchambers/Base64.js
}
function decodeToken(token) {
var parts = token.split('.');
if (parts.length !== 3) {
throw new Error('The token is invalid')
}
var decoded = urlBase64Decode(parts[1]);
if (!decoded) {
throw new Error('Cannot decode the token')
}
return JSON.parse(decoded)
}
function getTokenExpirationDate(token) {
var decoded = decodeToken(token);
if(typeof decoded.exp === 'undefined') {
return null
}
var d = new Date(0);// The 0 here is the key, which sets the date to the epoch
d.setUTCSeconds(decoded.exp);
return d
}
function isTokenExpired(token) {
var d = getTokenExpirationDate(token);
if (d === null) {
return false
}
// Token expired?
return !(d.valueOf() > (new Date().valueOf()))
}
/**
* Get IDs of users in the specified group
*
* @param {Object} connection - the connection object provided by ActionHero
* @param {Number} groupId - the group ID
* @param {Function<err, members>} callback - the callback. Receives either an error
* or the list of group's users an array of numeric IDs
*/
function getGroupMembers(connection, groupId, callback) {
getToken(connection, function (err, token) {
if (err) {
callback(err);
return;
}
callService({
url: v3url + 'groups/' + groupId + '/members',
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
}
}, function (err, body) {
if (err) {
callback(err);
} else {
callback(null, body.result.content.map(function (item) {
return item.memberId;
}));
}
});
});
}
exports.v3client = function (api, next) {
api.v3client = {
/**
* Check if the user belongs to the group
*
* @param {Object} connection - the connection object provided by ActionHero
* @param {Number} userId - the user ID
* @param {Number} groupId - the group ID
* @param {Function<err, isIn>} callback - the callback. The second parameter
* is boolean vwhich is true if the user is found in the group.
*/
isUserInGroup: function (connection, userId, groupId, callback) {
getGroupMembers(connection, groupId, function (err, members) {
if (err) {
callback(err);
} else {
callback(null, members.indexOf(userId) >= 0);
}
});
}
};
next();
};