-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathuser.js
576 lines (522 loc) · 16.4 KB
/
user.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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
// == BSD2 LICENSE ==
// Copyright (c) 2015, 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';
var async = require('async');
var _ = require('lodash');
function defaultProperty(obj, property, defaultValue) {
if (obj[property] == null) {
obj[property] = defaultValue;
}
return obj;
}
function requireProperty(objectName, obj, property) {
var value = obj[property];
if (value == null) {
throw new Error('Property [' + property + '] required on ' + objectName);
}
return value;
}
var requireDep = requireProperty.bind(null, 'deps');
module.exports = function (common, config, deps) {
var myToken = null;
var myUserId = null;
// This is a 'version' counter for the number of times we've logged in.
// It is used to invalidate stale attempts at refreshing a token
var loginVersion = 0;
var TOKEN_LOCAL_KEY = 'authToken';
/*jshint unused:false */
var log = requireDep(deps,'log');
var store = requireDep(deps, 'localStore');
var superagent = requireDep(deps, 'superagent');
//config
config = _.clone(config);
defaultProperty(config, 'tokenRefreshInterval', 10 * 60 * 1000); // 10 minutes
/**
* Initialize client for user
*
* @param cb
*/
function initialize(cb) {
myToken = store.getItem(TOKEN_LOCAL_KEY);
common.syncToken(myToken);
if (myToken == null) {
log.info('No local session found');
return cb();
}
refreshUserToken(myToken, function(err, data) {
var hasNewSession = data && data.userid && data.token;
if (err || !hasNewSession) {
log.info('Local session invalid', err, data);
saveSession(null, null);
return cb();
}
log.info('Loaded local session');
saveSession(data.userid, data.token, {remember:true});
cb(null, {userid: data.userid, token: data.token});
});
}
function refreshUserToken(token, cb) {
superagent.get(common.makeAPIUrl('/auth/#'))
.set(common.SESSION_TOKEN_HEADER, token)
.retry()
.end(
function (err, res) {
if (err) {
err.body = (err.response && err.response.body) || '';
return cb(err, null);
}
if (res.status !== 200) {
return common.handleHttpError(res, cb);
}
return cb(null, {userid: res.body.userid, token: res.headers[common.SESSION_TOKEN_HEADER]});
});
}
/**
* Save user session (in-memory and stored in browser)
* @param newUserId user Id
* @param newToken session token
* @param options (optional) object with options `remember`, `noRefresh`
* @param cb
* @returns {cb} cb(err, response)
*/
function saveSession(newUserId, newToken, options, cb) {
options = options || {};
if (typeof options === 'function') {
cb = options;
options = {};
}
cb = cb || _.noop;
myToken = newToken;
common.syncToken(myToken);
myUserId = newUserId;
// Store and increment the loginVersion. This is a mechanism to nullify any refreshSession calls that
// are waiting for their timeout to run.
var currVersion = ++loginVersion;
if (newToken == null) {
store.removeItem(TOKEN_LOCAL_KEY);
log.info('Destroyed local session');
return;
}
log.info('Session saved');
if (options.remember) {
store.setItem(TOKEN_LOCAL_KEY, newToken);
log.info('Saved session locally');
}
var refreshSession = function() {
if (myToken == null || currVersion !== loginVersion) {
log.info('Stopping session token refresh for version', currVersion);
return;
}
log.info('Refreshing session token');
refreshUserToken(myToken, function(err, data) {
var hasNewSession = data && data.userid && data.token;
if (err || !hasNewSession) {
log.warn('Failed refreshing session token', err);
saveSession(null, null);
} else {
saveSession(data.userid, data.token, options);
}
});
};
if(!options.noRefresh){
setTimeout(refreshSession, config.tokenRefreshInterval);
}
return cb(null, {userId: myUserId, token: myToken});
}
/**
* Destroy user session (in-memory and stored in browser)
*/
function destroySession() {
return saveSession(null, null);
}
/**
* Tells if the current client is logged in
*
* @returns {boolean} true if logged in
*/
function isLoggedIn() {
return myToken != null;
}
/**
* Returns the logged in user's id
*
* @returns {String} userid or null if not logged in
*/
function getUserId() {
return myUserId;
}
/**
* Returns the logged in user's token
*
* @returns {String} users token
*/
function getUserToken(){
return myToken;
}
/**
* Login user to the Tidepool platform using the provided oauth token
*
* @param provided oauth token
* @param cb
* @returns {cb} cb(err, response)
*/
function oauthLogin(oauthToken, cb) {
superagent
.post(common.makeAPIUrl('/auth/oauthlogin'))
.set('Authorization', 'bearer '+oauthToken)
.retry()
.end(
function (err, res) {
if (err != null) {
err.body = (err.response && err.response.body) || '';
return cb(err, null);
}
if (res.status !== 200) {
return common.handleHttpError(res, cb);
}
var oauthUserId = res.body.oauthUser.userid;
var theToken = res.headers[common.SESSION_TOKEN_HEADER];
//save the session and remember by default
saveSession(oauthUserId, theToken, {remember:true});
return cb(null,{userid: oauthUserId, user: res.body.oauthUser, target: res.body.oauthTarget});
});
}
/**
* Login user to the Tidepool platform
*
* @param user object with a username and password to login
* @param options (optional) object with `remember` boolean attribute
* @param cb
* @returns {cb} cb(err, response)
*/
function login(user, options, cb) {
options = options || {};
if (typeof options === 'function') {
cb = options;
options = {};
}
if (user.username == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a username' });
}
if (user.password == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a password' });
}
superagent
.post(common.makeAPIUrl('/auth/#', user.longtermkey))
.auth(user.username, user.password)
.retry()
.end(
function (err, res) {
if (err != null) {
err.body = (err.response && err.response.body) || '';
return cb(err, null);
}
if (res.status !== 200) {
return common.handleHttpError(res, cb);
}
var theUserId = res.body.userid;
var theToken = res.headers[common.SESSION_TOKEN_HEADER];
saveSession(theUserId, theToken, options);
return cb(null,{userid: theUserId, user: res.body});
});
}
/**
* Logout user
*
* @returns {cb} cb(err, response)
*/
function logout(cb) {
common.assertArgumentsSize(arguments, 1);
if (isLoggedIn() === false) {
setTimeout(function(){ cb(null, {}); }, 0);
}
var onSuccess=function(res){
saveSession(null, null);
return res.status;
};
common.doPostWithToken(
'/auth/logout',
{},
{200: onSuccess},
cb
);
}
/**
* # user to the Tidepool platform
*
* @param user object with a username and password
* @param options (optional) object with `remember` boolean attribute
* @param cb
* @returns {cb} cb(err, response)
*/
function #(user, options, cb) {
options = options || {};
if (typeof options === 'function') {
cb = options;
options = {};
}
if (user.username == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a username' });
}
if (user.password == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a password' });
}
var newUser = _.pick(user, 'username', 'password', 'emails', 'roles');
superagent
.post(common.makeAPIUrl('/auth/user'))
.send(newUser)
.retry()
.end(
function (err, res) {
if (err != null) {
err.body = (err.response && err.response.body) || '';
return cb(err);
}
var theUserId = res.body.userid;
var theToken = res.headers[common.SESSION_TOKEN_HEADER];
saveSession(theUserId, theToken, options);
return cb(null,res.body);
});
}
/**
* Create a custodial account for the logged in user
*
* @param profile {Object} profile for account that is being created for
* @param cb
* @returns {cb} cb(err, response)
*/
function createCustodialAccount(profile, cb) {
if (_.isEmpty(profile.fullName)) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a fullName' });
}
var custodialUser = {};
// create an custodial account to attach to ours
function createAccount(next){
var body = {};
if(!_.isEmpty(profile.emails)){
body.emails = profile.emails;
body.username = profile.emails[0];
}
superagent
.post(common.makeAPIUrl('/auth/user/' + getUserId() + '/user'))
.set(common.SESSION_TOKEN_HEADER, getUserToken())
.send(body)
.retry()
.end(
function (err, res) {
if (err != null) {
err.body = (err.response && err.response.body) || '';
err.message = (err.response && err.response.error) || '';
return next(err);
}
if(res.status === 201){
custodialUser.id = res.body.userid;
return next(null,{userid:res.body.userid});
}
return next({status:res.status,message:res.error});
});
}
//add a profile name to the child account
function createProfile(next){
superagent
.put(common.makeAPIUrl('/metadata/'+ custodialUser.id + '/profile'))
.send(profile)
.set(common.SESSION_TOKEN_HEADER, getUserToken())
.retry()
.end(
function (err, res) {
if (err != null) {
err.body = (err.response && err.response.body) || '';
err.message = (err.response && err.response.error) || '';
return next(err);
}
if(res.status === 200){
return next(null,res.body);
}
return next({status:res.status,message:res.error});
});
}
// optionally send a confirmation email if email was provided
function sendEmailConfirmation(next){
if(_.isEmpty(profile.emails)){
return next(null);
}
superagent
.post(common.makeAPIUrl('/confirm/send/#/'+custodialUser.id))
.set(common.SESSION_TOKEN_HEADER, getUserToken())
.send({})
.retry()
.end(
function (err, res) {
if (err != null) {
err.body = (err.response && err.response.body) || '';
err.message = (err.response && err.response.error) || '';
return next(err);
}
if(res.status === 200){
return next(null,res.body);
}
return next({status:res.status,message:res.error});
});
}
async.series([
createAccount,
createProfile,
sendEmailConfirmation
], function(err, results) {
if(_.isEmpty(err)){
var acct = {
userid: results[0].userid,
profile: results[1]
};
return cb(null,acct);
}
return cb(err);
});
}
/**
* Update current user account info
*
* @param {Object} user object with account info
* @param cb
* @returns {cb} cb(err, response)
*/
function updateCurrentUser(user, cb) {
common.assertArgumentsSize(arguments, 2);
var updateData = {
updates: _.pick(user, 'username', 'password', 'emails', 'termsAccepted')
};
common.doPutWithToken('/auth/user', updateData, cb);
}
/**
* Update custodial user account info
*
* @param {Object} user object with account info
* @param custodial user id
* @param cb
* @returns {cb} cb(err, response)
*/
function updateCustodialUser(user, id, cb) {
common.assertArgumentsSize(arguments, 3);
var updateData = {
updates: _.pick(user, 'username', 'password', 'emails', 'termsAccepted')
};
common.doPutWithToken('/auth/user/' + id, updateData, cb);
}
/**
* Add or update the date the user accepted the terms and conditions
*
* @param {Object} user object with the attached terms info
* @param cb
* @returns {cb} cb(err, response)
*/
function acceptTerms(user, cb) {
common.assertArgumentsSize(arguments, 2);
if(_.isEmpty(user.terms)){
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a terms field' });
}
var updateUserTerms = {
updates: _.pick(user, 'terms')
};
common.doPutWithToken('/auth/user', updateUserTerms, cb);
}
/**
* Get current user account info
*
* @returns {cb} cb(err, response)
*/
function getCurrentUser(cb) {
common.assertArgumentsSize(arguments, 1);
common.doGetWithToken('/auth/user', cb);
}
/**
* Create a restricted token for a given user. One that is only usable for a limited
* period of time to a limited set of APIs.
*
* @param {String} userId of the user to create a restricted token for
* @param {String} restrictedTokenRequest the restricted token requested access
* @param cb
* @returns {cb} cb(err, response)
*/
function createRestrictedTokenForUser(userId, restrictedTokenRequest, cb) {
common.assertArgumentsSize(arguments, 3);
common.doPostWithToken(
'/v1/users/' + userId + '/restricted_tokens',
restrictedTokenRequest,
{ 201: function(res) { return res.body; } },
cb
);
}
/**
* Create the OAuth provider authorization for the specified provider and restricted token.
*
* @param {String} provider the provider
* @param {String} restrictedToken the restricted token
* @param cb
* @returns {cb} cb(err, response)
*/
function createOAuthProviderAuthorization(provider, restrictedToken, cb) {
common.assertArgumentsSize(arguments, 3);
var authorizationURL = common.makeAPIUrl('/v1/oauth/' + provider + '/authorize');
authorizationURL += '?restricted_token=' + restrictedToken;
cb(null, authorizationURL);
}
/**
* Delete the OAuth provider authorization for the specified provider.
*
* @param {String} provider the provider
* @param cb
* @returns {cb} cb(err, response)
*/
function deleteOAuthProviderAuthorization(provider, cb) {
common.assertArgumentsSize(arguments, 2);
superagent
.del(common.makeAPIUrl('/v1/oauth/' + provider + '/authorize'))
.set(common.SESSION_TOKEN_HEADER, getUserToken())
.retry()
.end(
function(err, res) {
if (err != null) {
err.body = (err.response && err.response.body) || '';
err.message = (err.response && err.response.error) || '';
return cb(err);
}
if (res.status === 200) {
return cb(null, res.body);
}
return cb({ status: res.status, message: res.error });
});
}
return {
acceptTerms : acceptTerms,
createCustodialAccount : createCustodialAccount,
destroySession: destroySession,
getCurrentUser : getCurrentUser,
getUserId : getUserId,
getUserToken : getUserToken,
isLoggedIn: isLoggedIn,
login : login,
oauthLogin : oauthLogin,
logout : logout,
# : #,
initialize : initialize,
updateCurrentUser : updateCurrentUser,
updateCustodialUser: updateCustodialUser,
createRestrictedTokenForUser: createRestrictedTokenForUser,
createOAuthProviderAuthorization: createOAuthProviderAuthorization,
deleteOAuthProviderAuthorization: deleteOAuthProviderAuthorization,
saveSession: saveSession,
};
};