-
Notifications
You must be signed in to change notification settings - Fork 2
/
seagullApi.js
544 lines (476 loc) · 17.4 KB
/
seagullApi.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/*
== BSD2 LICENSE ==
Copyright (c) 2014, Tidepool Project
This program is free software; you can redistribute it and/or modify it under
the terms of the associated License, which is identical to the BSD 2-Clause
License as published by the Open Source Initiative at opensource.org.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the License for more details.
You should have received a copy of the License along with this program; if
not, you can obtain one from Tidepool Project at tidepool.org.
== BSD2 LICENSE ==
*/
'use strict';
const util = require('util');
const _ = require('lodash');
const async = require('async');
const log = require('../log.js')('seagullApi.js');
/*
Http interface for group-api
*/
module.exports = function (crudHandler, userApiClient, gatekeeperClient, metrics) {
/*
HELPERS
*/
function createDocAndCallback(userId, res, next, cb) {
crudHandler.createDoc(userId, {}, function (err, result) {
if (err) {
log.error(err, 'createDocAndCallback: Error creating metadata doc');
if (err.statusCode == 400) {
/* return a 500 code to indicate a temporary server error. Expect a retry. */
res.send(500);
} else {
res.send(err.statusCode);
}
return next();
} else {
cb();
}
});
}
function getCollection(req, res, sanitize, next) {
crudHandler.getDoc(_.get(req, 'params.userid'), function (err, result) {
if (err) {
log.error(err, 'getCollection: Error reading metadata doc');
res.send(err.statusCode);
} else {
var collection = _.get(req, 'params.collection');
var retVal = result.detail[collection];
if (retVal == null) {
res.send(404);
} else {
if (collection === 'profile' && sanitize) {
res.send(200, sanitizeProfile(retVal));
} else {
res.send(200, retVal);
}
}
}
return next();
});
}
var ANY = ['any'];
var NONE = ['none'];
var TRUES = ['true', 'yes', 'y', '1'];
function parsePermissions(permissions) {
permissions = _.trim(permissions);
if (permissions !== '') {
permissions = _.compact(_.map(permissions.split(','), _.trim));
if (_.isEqual(permissions, ANY)) {
return ANY;
} else if (_.isEqual(permissions, NONE)) {
return NONE;
} else if (!_.isEmpty(permissions)) {
return permissions;
}
}
return null;
}
function arePermissionsValid(permissions) {
if (permissions.length > 1) {
if (!_.isEmpty(_.intersection(_.union(ANY, NONE), permissions))) {
return false;
}
}
return true;
}
function arePermissionsSatisfied(queryPermissions, userPermissions) {
if (queryPermissions === ANY) {
return !_.isEmpty(userPermissions);
} else if (queryPermissions === NONE) {
return _.isEmpty(userPermissions);
} else {
return _.every(queryPermissions, _.partial(_.has, userPermissions));
}
}
function stringToBoolean(value) {
return _.includes(TRUES, _.trim(value).toLowerCase());
}
function parseUsersQuery(req) {
var query = {};
var trustorPermissions = parsePermissions(req.query.trustorPermissions);
if (trustorPermissions) {
query.trustorPermissions = trustorPermissions;
}
var trusteePermissions = parsePermissions(req.query.trusteePermissions);
if (trusteePermissions) {
query.trusteePermissions = trusteePermissions;
}
var email = _.trim(req.query.email);
if (email !== '') {
query.email = new RegExp(_.escapeRegExp(email), 'i');
}
var emailVerified = _.trim(req.query.emailVerified);
if (emailVerified !== '') {
query.emailVerified = stringToBoolean(emailVerified);
}
var termsAccepted = _.trim(req.query.termsAccepted);
if (termsAccepted !== '') {
query.termsAccepted = new RegExp(_.escapeRegExp(termsAccepted), 'i');
}
var name = _.trim(req.query.name);
if (name !== '') {
query.name = new RegExp(_.escapeRegExp(name), 'i');
}
var birthday = _.trim(req.query.birthday);
if (birthday !== '') {
query.birthday = new RegExp(_.escapeRegExp(birthday), 'i');
}
var diagnosisDate = _.trim(req.query.diagnosisDate);
if (diagnosisDate !== '') {
query.diagnosisDate = new RegExp(_.escapeRegExp(diagnosisDate), 'i');
}
return _.isEmpty(query) ? null : query;
}
function isUsersQueryValid(query) {
if (query) {
if (_.has(query, 'trustorPermissions') && !arePermissionsValid(query.trustorPermissions)) {
return false;
}
if (_.has(query, 'trusteePermissions') && !arePermissionsValid(query.trusteePermissions)) {
return false;
}
}
return true;
}
function userMatchesQueryOnPermissions(user, query) {
if (query) {
if (_.has(query, 'trustorPermissions') && !arePermissionsSatisfied(query.trustorPermissions, user.trustorPermissions)) {
return false;
}
if (_.has(query, 'trusteePermissions') && !arePermissionsSatisfied(query.trusteePermissions, user.trusteePermissions)) {
return false;
}
}
return true;
}
function userMatchesQueryOnUser(user, query) {
if (query) {
if (_.has(query, 'email') && !query.email.test(user.username)) {
return false;
}
if (_.has(query, 'emailVerified') && query.emailVerified != stringToBoolean(user.emailVerified)) {
return false;
}
if (_.has(query, 'termsAccepted') && !query.termsAccepted.test(user.termsAccepted)) {
return false;
}
}
return true;
}
function userMatchesQueryOnProfile(user, query) {
if (query) {
if (_.has(query, 'name') && !query.name.test(_.result(user, 'profile.fullName'))) {
return false;
}
if (_.has(query, 'birthday') && !query.birthday.test(_.result(user, 'profile.patient.birthday'))) {
return false;
}
if (_.has(query, 'diagnosisDate') && !query.diagnosisDate.test(_.result(user, 'profile.patient.diagnosisDate'))) {
return false;
}
}
return true;
}
function userMatchingQuery(user, query) {
if (query) {
if (!userMatchesQueryOnPermissions(user, query) ||
!userMatchesQueryOnUser(user, query) ||
!userMatchesQueryOnProfile(user, query)) {
return null;
}
}
return user;
}
function sanitizeUser(user) {
return _.omit(user, 'passwordExists');
}
function sanitizeProfile(profile) {
return _.pick(profile, 'fullName');
}
function hasReadPermissions(permissions) {
if (!permissions) {
return false;
}
return !_.isEmpty(_.keys(permissions));
}
return {
/*
IMPLEMENTATIONS OF METHODS
*/
users: function(req, res, next) {
var targetUserId = _.trim(req.params.userid);
if (targetUserId === '') {
log.error('Target user id not specified');
res.send(400, 'Target user id not specified');
return next(false);
}
var query = parseUsersQuery(req);
if (!isUsersQueryValid(query)) {
log.error('Query is invalid', query);
res.send(400, 'Query is invalid');
return next(false);
}
var mergedUserPermissions = {};
gatekeeperClient.groupsForUser(targetUserId, function(error, trustorUserPermissions) {
if (error) {
log.error(error, 'Error getting groups for target user id', targetUserId);
res.send(error.statusCode || 500);
return next(false);
}
_.forEach(trustorUserPermissions, function(p, u) { mergedUserPermissions[u] = { trustorPermissions: p }; });
gatekeeperClient.usersInGroup(targetUserId, async function(error, trusteeUserPermissions) {
if (error) {
log.error(error, 'Error getting users for target user id', targetUserId);
res.send(error.statusCode || 500);
return next(false);
}
_.forEach(trusteeUserPermissions, function(p, u) { mergedUserPermissions[u] = _.merge(mergedUserPermissions[u] || {}, { trusteePermissions: p }); });
delete mergedUserPermissions[targetUserId];
mergedUserPermissions = _.pickBy(mergedUserPermissions, function(p) { return userMatchesQueryOnPermissions(p, query); });
var userProfiles = [];
const mapLimit = util.promisify(async.mapLimit);
var userIds;
try {
const userIdsWithDups = _.keys(mergedUserPermissions);
userIds = Array.from(new Set(userIdsWithDups));
if (userIds.length != userIdsWithDups.length) {
log.error('found duplicate userid');
}
// Break requests for users into chunks of 200, so that the query parameter doesn't get too long
const results = await mapLimit(_.chunk(userIds, 200), 5, async usersChunk => {
const getUsers = util.promisify(userApiClient.getUsersWithIds);
try {
const users = await getUsers(usersChunk);
if (!users) {
// It's possible for a user profile to be deleted before the sharing permissions,
// thus it's ok to have missing users.
return [];
} else {
return users;
}
} catch (error) {
throw new Error(`Error getting users: ${error}`);
}
});
userProfiles = _.flatten(results);
} catch (error) {
const foundIds = userProfiles.map( v => v.userid );
const missingIds = userIds.filter(v => !foundIds.includes(v));
log.error(error, 'Failed to retreive these users', missingIds );
res.send(500);
return next(false);
}
async.mapLimit(userProfiles, 20, function(user, callback) {
const trustorUserId = user.userid;
if (!userMatchesQueryOnUser(user, query)) {
return callback();
}
user = _.merge(user, mergedUserPermissions[trustorUserId]);
crudHandler.getDoc(trustorUserId, function(error, document) {
if (error) {
if (error.statusCode == 404) {
return callback(null, userMatchingQuery(user, query));
}
log.error(error, 'Error getting document for user id', trustorUserId);
return callback(error);
}
user.profile = _.result(document, 'detail.profile');
if (_.isEmpty(user.trustorPermissions)) {
if (user.profile) {
delete user.profile.patient;
} else {
log.error(`User ${user.userid} does not have a valid profile. Consider investigating the account.`);
}
} else {
if (
user.trustorPermissions.custodian ||
user.trustorPermissions.view ||
user.trustorPermissions.upload) {
var settings = _.result(document, 'detail.settings');
if (!_.isEmpty(settings)) {
user.settings = settings;
}
}
if (user.trustorPermissions.custodian) {
var preferences = _.result(document, 'detail.preferences');
if (!_.isEmpty(preferences)) {
user.preferences = preferences;
}
}
}
return callback(null, userMatchingQuery(user, query));
});
}, function(error, users) {
if (error) {
log.error(error, 'random error');
res.send(error.statusCode || 500);
return next(false);
}
users = _.compact(users);
if (!req._tokendata.isserver) {
users = _.map(users, sanitizeUser);
}
res.send(200, users);
return next();
});
});
});
},
metacollections: function (req, res, next) {
log.debug('metacollections: params[%j], url[%s], method[%s]', req.params, req.url, req.method);
res.send(200, [ 'profile', 'groups', 'private' ]);
return next();
},
metacollection_read: function (req, res, next) {
log.debug('metacollection_read: params[%j], url[%s], method[%s]', req.params, req.url, req.method);
var collection = req.params.collection;
if (collection == null) {
res.send(400, 'No collection specified');
return next();
}
if (req._tokendata.isserver) {
var sanitize = false;
return getCollection(req, res, sanitize, next);
}
// Check to see if the user has trustor permissions for the requested user ID
gatekeeperClient.userInGroup(req._tokendata.userid, req.params.userid, function(error, permissions){
if (error && error.statusCode !== 401) {
log.error(error, 'Error getting groups for authenticated user id', req._tokendata.userid);
res.send(error.statusCode || 500);
return next(false);
}
const hasTrustorPermissions = !error && hasReadPermissions(permissions);
if (hasTrustorPermissions || collection === 'profile') {
const sanitize = !hasTrustorPermissions;
return getCollection(req, res, sanitize, next);
} else {
res.send(401, 'Unauthorized');
return next();
}
});
},
metacollection_update: function (req, res, next) {
var collection = req.params.collection;
if (collection == null) {
res.send(400, 'No collection specified');
return next();
}
var updates = req.body;
if (updates == null) {
res.send(400, 'Must have a body');
return next();
}
updates = _.reduce(updates, function (accum, update, key) {
accum[util.format('%s.%s', collection, key)] = update;
return accum;
}, {});
function doUpdate(addIfNotThere) {
var userId = req.params.userid;
crudHandler.partialUpdate(userId, updates, function (err, result) {
if (err) {
if (err.statusCode == 404 && addIfNotThere) {
return createDocAndCallback(userId, res, next, function () { doUpdate(false); });
} else {
log.error(err, 'Error updating metadata doc');
res.send(err.statusCode);
return next();
}
} else {
res.send(200, result.detail[collection]);
return next();
}
});
}
doUpdate(true);
},
metacollection_delete: function (req, res, next) {
log.debug('metacollection_delete: params[%j], url[%s], method[%s]', req.params, req.url, req.method);
res.send(501); // not implemented
return next();
},
metaprivate_read: function (req, res, next) {
log.debug('metaprivate_read: params[%j], url[%s], method[%s]', req.params, req.url, req.method);
var userId = req.params.userid;
var name = req.params.name;
if (name == null) {
res.send(400, 'No name specified');
return next();
}
function getPrivatePair(addIfNotThere) {
crudHandler.getDoc(userId, function (err, mongoResult) {
if (err) {
if (err.statusCode === 404 && addIfNotThere) {
return createDocAndCallback(userId, res, next, function () { getPrivatePair(addIfNotThere); });
}
log.error(err, 'Error reading metadata doc');
res.send(err.statusCode);
} else {
var result = mongoResult.detail;
// we have the doc now, let's see if it has the name
if (result.private && result.private[name]) {
res.send(200, result.private[name]);
return next();
} else {
if (addIfNotThere) {
return makeNewHash();
} else {
res.send(404);
}
}
}
return next();
});
}
function makeNewHash() {
// generate a private pair
// TODO: 20150627_darinkrauss This probably shouldn't be anon (including name)
userApiClient.getAnonymousPair(function (err, pair) {
if (err != null) {
log.info(err, 'Unable to generate a new anonymous pair!');
res.send(500);
return next();
} else {
var update = {};
update['private.' + name] = pair;
crudHandler.partialUpdate(userId, update, function (err, result) {
if (err) {
log.error(err, 'Error creating metadata doc');
if (err.statusCode == 404) {
res.send(404);
return next();
} else {
res.send(err.statusCode);
return next();
}
} else {
res.send(200, result.detail.private[name]);
return next();
}
});
}
});
}
getPrivatePair(true);
},
metaprivate_delete: function (req, res, next) {
log.debug('metaprivate_delete: params[%j], url[%s], method[%s]', req.params, req.url, req.method);
res.send(501); // not implemented
return next();
},
close: function () {
crudHandler.closeDatabase();
}
};
};