user-methods.js
25.9 KB
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
'use strict';
/* global fetch, Request, Response, XMLHttpRequest */
const AuthError = require('./errors').AuthError;
const permissionApis = require('./permission-api');
const merge = require('deepmerge');
const require_method = require;
const URL = require('url-parse');
const refreshTimers = {};
const retryInterval = 5 * 1000; // Amount of time between retrying authentication requests, if the first request failed.
const refreshBuffer = 20 * 1000; // A "safe" amount of time before a token expires that allow us to refresh it.
const refreshLowerBound = 10 * 1000; // Lower bound for refreshing tokens.
function node_require(module) {
return require_method(module);
}
function checkTypes(args, types) {
args = Array.prototype.slice.call(args);
for (var i = 0; i < types.length; ++i) {
if (args.length > i && typeof args[i] !== types[i]) {
throw new TypeError('param ' + i + ' must be of type ' + types[i]);
}
}
}
function checkObjectTypes(obj, types) {
for (const name of Object.getOwnPropertyNames(types)) {
const actualType = typeof obj[name];
let targetType = types[name];
const isOptional = targetType[targetType.length - 1] === '?';
if (isOptional) {
targetType = targetType.slice(0, -1);
}
if (!isOptional && actualType === 'undefined') {
throw new Error(`${name} is required, but a value was not provided.`);
}
if (actualType !== targetType) {
throw new TypeError(`${name} must be of type '${targetType}' but was of type '${actualType}' instead.`);
}
}
}
function normalizeSyncUrl(authUrl, syncUrl) {
const parsedAuthUrl = new URL(authUrl);
const realmProtocol = (parsedAuthUrl.protocol === "https:") ? "realms" : "realm";
// Inherit ports from the Auth url
const port = parsedAuthUrl.port ? `:${parsedAuthUrl.port}` : "";
const baseUrl = `${realmProtocol}://${parsedAuthUrl.hostname}${port}`;
if (!syncUrl) {
syncUrl = "/default";
}
return new URL(syncUrl, baseUrl, false).toString();
}
// node-fetch supports setting a timeout as a nonstandard extension, but normal fetch doesn't
function fetchWithTimeout(input, init) {
const request = new Request(input, init);
const xhr = new XMLHttpRequest();
xhr.timeout = init.timeout || 0;
return new Promise(function(resolve, reject) {
xhr.onload = () => {
const options = {
status: xhr.status,
statusText: xhr.statusText,
url: xhr.responseURL,
headers: xhr.responseHeaders
};
if (!options.headers) {
options.headers = {'content-type': xhr.getResponseHeader('content-type')};
}
const body = 'response' in xhr ? xhr.response : xhr.responseText;
resolve(new Response(body, options));
};
xhr.onerror = () => reject(new TypeError('Network request failed'));
xhr.ontimeout = () => reject(new TypeError('Network request failed'));
xhr.open(request.method, request.url, true);
request.headers.forEach((value, name) => xhr.setRequestHeader(name, value));
xhr.send(typeof request._bodyInit === 'undefined' ? init.body : request._bodyInit);
});
}
// Perform a HTTP request, enqueuing it if too many requests are already in
// progress to avoid hammering the server.
const performFetch = (function() {
const doFetch = typeof fetch === 'undefined' ? node_require('node-fetch') : fetchWithTimeout;
const queue = [];
let count = 0;
const maxCount = 5;
const next = () => {
if (count >= maxCount) {
return;
}
const req = queue.shift();
if (!req) {
return;
}
const [url, options, resolve, reject] = req;
if (options.headers === undefined) {
options.headers = {};
}
if (typeof options.body !== "undefined") {
// fetch expects a stringified body
if (typeof options.body === "object") {
options.body = JSON.stringify(options.body);
}
// If content-type header is not explicitly set, we should set it ourselves
if (typeof options.headers['content-type'] === "undefined") {
options.headers['content-type'] = 'application/json;charset=utf-8';
}
}
if (!options.headers['accept']){
options.headers['accept'] = 'application/json';
}
++count;
// node doesn't support Promise.prototype.finally until 10
doFetch(url, options)
.then(response => {
--count;
next();
resolve(response);
})
.catch(error => {
--count;
next();
reject(error);
});
};
return (url, options) => {
return new Promise((resolve, reject) => {
queue.push([url, options, resolve, reject]);
next();
});
};
})();
const url_parse = require('url-parse');
function append_url(server, path) {
return server + (server.charAt(server.length - 1) != '/' ? '/' : '') + path;
}
function scheduleAccessTokenRefresh(user, localRealmPath, realmUrl, expirationDate) {
let userTimers = refreshTimers[user.identity];
if (!userTimers) {
refreshTimers[user.identity] = userTimers = {};
}
// We assume that access tokens have ~ the same expiration time, so if someone already
// scheduled a refresh, it's likely to complete before the one we would have scheduled
if (!userTimers[localRealmPath]) {
const timeout = Math.max(expirationDate - Date.now() - refreshBuffer, refreshLowerBound);
userTimers[localRealmPath] = setTimeout(() => {
delete userTimers[localRealmPath];
refreshAccessToken(user, localRealmPath, realmUrl);
}, timeout);
}
}
function print_error() {
(console.error || console.log).apply(console, arguments);
}
function validateRefresh(user, localRealmPath, response, json) {
let session = user._sessionForOnDiskPath(localRealmPath);
if (!session) {
return;
}
const errorHandler = session.config.error;
if (response.status != 200) {
let error = new AuthError(json);
if (errorHandler) {
errorHandler(session, error);
} else {
print_error(`Unhandled session token refresh error for user ${user.identity} at path ${localRealmPath}`, error);
}
return;
}
if (session.state === 'invalid') {
return;
}
return session;
}
function refreshAdminToken(user, localRealmPath, realmUrl) {
const token = user.token;
const server = user.server;
// We don't need to actually refresh the token, but we need to let ROS know
// we're accessing the file and get the sync label for multiplexing
let parsedRealmUrl = url_parse(realmUrl);
const url = append_url(user.server, 'realms/files/' + encodeURIComponent(parsedRealmUrl.pathname));
performFetch(url, { method: 'GET', timeout: 10000.0, headers: { Authorization: user.token }})
.then((response) => {
// There may not be a Realm Directory Service running on the server
// we're talking to. If we're talking directly to the sync service
// we'll get a 404, and if we're running inside ROS we'll get a 503 if
// the directory service hasn't started yet (perhaps because we got
// called due to the directory service itself opening some Realms).
//
// In both of these cases we can just pretend we got a valid response.
if (response.status === 404 || response.status === 503) {
return {response: {status: 200}, json: {path: parsedRealmUrl.pathname, syncLabel: '_direct'}};
}
else {
return response.json().then((json) => { return { response, json }; });
}
})
.then((responseAndJson) => {
const response = responseAndJson.response;
const json = responseAndJson.json;
const credentials = credentialsMethods.adminToken(token)
const newUser = user.constructor.login(server, credentials);
const session = validateRefresh(newUser, localRealmPath, response, json);
if (session) {
parsedRealmUrl.set('pathname', json.path);
session._refreshAccessToken(user.token, parsedRealmUrl.href, json.syncLabel);
}
})
.catch((e) => {
print_error(e);
setTimeout(() => refreshAccessToken(user, localRealmPath, realmUrl), retryInterval);
});
}
function refreshAccessToken(user, localRealmPath, realmUrl) {
if (!user._sessionForOnDiskPath(localRealmPath)) {
// We're trying to refresh the token for a session that's closed. This could happen, for example,
// when the server is not reachable and we periodically try to refresh the token, but the user has
// already closed the Realm file.
return;
}
if (!user.server) {
throw new Error("Server for user must be specified");
}
const parsedRealmUrl = url_parse(realmUrl);
const path = parsedRealmUrl.pathname;
if (!path) {
throw new Error(`Unexpected Realm path inferred from url '${realmUrl}'. The path section of the url should be a non-empty string.`);
}
if (user.isAdminToken) {
return refreshAdminToken(user, localRealmPath, realmUrl);
}
const url = append_url(user.server, 'auth');
const options = {
method: 'POST',
body: {
data: user.token,
path,
provider: 'realm',
app_id: ''
},
// FIXME: This timeout appears to be necessary in order for some requests to be sent at all.
// See https://github.com/realm/realm-js-private/issues/338 for details.
timeout: 10000.0
};
const server = user.server;
const identity = user.identity;
performFetch(url, options)
.then((response) => response.json().then((json) => { return { response, json }; }))
.then((responseAndJson) => {
const response = responseAndJson.response;
const json = responseAndJson.json;
// Look up a fresh instance of the user.
// We do this because in React Native Remote Debugging
// `Realm.clearTestState()` will have invalidated the user object
let newUser = user.constructor._getExistingUser(server, identity);
if (!newUser) {
return;
}
const session = validateRefresh(newUser, localRealmPath, response, json);
if (!session) {
return;
}
const tokenData = json.access_token.token_data;
parsedRealmUrl.set('pathname', tokenData.path);
session._refreshAccessToken(json.access_token.token, parsedRealmUrl.href, tokenData.sync_label);
const errorHandler = session.config.error;
if (errorHandler && errorHandler._notifyOnAccessTokenRefreshed) {
errorHandler(session, errorHandler._notifyOnAccessTokenRefreshed)
}
const tokenExpirationDate = new Date(tokenData.expires * 1000);
scheduleAccessTokenRefresh(newUser, localRealmPath, realmUrl, tokenExpirationDate);
})
.catch((e) => {
print_error(e);
// in case something lower in the HTTP stack breaks, try again in `retryInterval` seconds
setTimeout(() => refreshAccessToken(user, localRealmPath, realmUrl), retryInterval);
})
}
/**
* The base authentication method. It fires a JSON POST to the server parameter plus the auth url
* For example, if the server parameter is `http://myapp.com`, this url will post to `http://myapp.com/auth`
* @param {object} userConstructor
* @param {string} server the http or https server url
* @param {object} json the json to post to the auth endpoint
* @param {Function} callback an optional callback with an error and user parameter
* @returns {Promise} only returns a promise if the callback parameter was omitted
*/
function _authenticate(userConstructor, server, json, retries) {
json.app_id = '';
const url = append_url(server, 'auth');
const options = {
method: 'POST',
body: json,
open_timeout: 5000,
timeout: 5000
};
return performFetch(url, options).then((response) => {
const contentType = response.headers.get('Content-Type');
if (contentType.indexOf('application/json') === -1) {
return response.text().then((body) => {
throw new AuthError({
title: `Could not authenticate: Realm Object Server didn't respond with valid JSON`,
body,
});
});
} else if (!response.ok) {
return response.json().then((body) => Promise.reject(new AuthError(body)));
} else {
return response.json().then((body) => {
// TODO: validate JSON
const token = body.refresh_token.token;
const identity = body.refresh_token.token_data.identity;
const isAdmin = body.refresh_token.token_data.is_admin;
return userConstructor.createUser(server, identity, token, false, isAdmin);
});
}
}, (err) => {
if (retries < 3) {
// Retry on network errors (which are different from the auth endpoint returning an error)
return _authenticate(userConstructor, server, json, retries + 1);
} else {
throw err;
}
});
}
function _updateAccount(userConstructor, server, json) {
const url = append_url(server, 'auth/password/updateAccount');
const options = {
method: 'POST',
body: json,
open_timeout: 5000
};
return performFetch(url, options)
.then((response) => {
const contentType = response.headers.get('Content-Type');
if (contentType.indexOf('application/json') === -1) {
return response.text().then((body) => {
throw new AuthError({
title: `Could not update user account: Realm Object Server didn't respond with valid JSON`,
body,
});
});
}
if (!response.ok) {
return response.json().then((body) => Promise.reject(new AuthError(body)));
}
});
}
const credentialsMethods = {
usernamePassword(username, password, createUser) {
checkTypes(arguments, ['string', 'string', 'boolean']);
return new Credentials('password', username, { register: createUser, password });
},
facebook(token) {
checkTypes(arguments, ['string']);
return new Credentials('facebook', token);
},
google(token) {
checkTypes(arguments, ['string']);
return new Credentials('google', token);
},
anonymous() {
return new Credentials('anonymous');
},
nickname(value, isAdmin) {
checkTypes(arguments, ['string', 'boolean']);
return new Credentials('nickname', value, { is_admin: isAdmin || false });
},
azureAD(token) {
checkTypes(arguments, ['string']);
return new Credentials('azuread', token)
},
jwt(token, providerName) {
checkTypes(arguments, ['string', 'string']);
return new Credentials(providerName || 'jwt', token);
},
adminToken(token) {
checkTypes(arguments, ['string']);
return new Credentials('adminToken', token);
},
custom(providerName, token, userInfo) {
if (userInfo) {
checkTypes(arguments, ['string', 'string', 'object']);
} else {
checkTypes(arguments, ['string', 'string']);
}
return new Credentials(providerName, token, userInfo);
}
}
const staticMethods = {
get current() {
const allUsers = this.all;
const keys = Object.keys(allUsers);
if (keys.length === 0) {
return undefined;
} else if (keys.length > 1) {
throw new Error("Multiple users are logged in");
}
return allUsers[keys[0]];
},
login(server, credentials) {
if (arguments.length === 3) {
// Deprecated legacy signature.
checkTypes(arguments, ['string', 'string', 'string']);
console.warn("User.login is deprecated. Please use User.login(server, Credentials.usernamePassword(...)) instead.");
const newCredentials = credentialsMethods.usernamePassword(arguments[1], arguments[2], /* createUser */ false);
return this.login(server, newCredentials);
}
checkTypes(arguments, ['string', 'object']);
if (credentials.identityProvider === 'adminToken') {
let u = this._adminUser(server, credentials.token);
return u;
}
return _authenticate(this, server, credentials, 0);
},
deserialize(serialized) {
if (serialized.adminToken) {
checkObjectTypes(serialized, {
server: 'string',
adminToken: 'string',
});
return this._adminUser(serialized.server, serialized.adminToken);
}
checkObjectTypes(serialized, {
server: 'string',
identity: 'string',
refreshToken: 'string',
isAdmin: 'boolean',
});
return this.createUser(serialized.server, serialized.identity, serialized.refreshToken, false, serialized.isAdmin || false);
},
requestPasswordReset(server, email) {
checkTypes(arguments, ['string', 'string']);
const json = {
provider_id: email,
data: { action: 'reset_password' }
};
return _updateAccount(this, server, json);
},
completePasswordReset(server, resetToken, newPassword) {
checkTypes(arguments, ['string', 'string']);
const json = {
data: {
action: 'complete_reset',
token: resetToken,
new_password: newPassword
}
};
return _updateAccount(this, server, json);
},
requestEmailConfirmation(server, email) {
checkTypes(arguments, ['string', 'string']);
const json = {
provider_id: email,
data: { action: 'request_email_confirmation' }
};
return _updateAccount(this, server, json);
},
confirmEmail(server, confirmationToken) {
checkTypes(arguments, ['string', 'string']);
const json = {
data: {
action: 'confirm_email',
token: confirmationToken
}
};
return _updateAccount(this, server, json);
},
_refreshAccessToken: refreshAccessToken,
// Deprecated...
adminUser(token, server) {
checkTypes(arguments, ['string', 'string']);
console.warn("User.adminUser is deprecated. Please use User.login(server, Credentials.adminToken(token)) instead.");
const credentials = credentialsMethods.adminToken(token);
return this.login(server, credentials);
},
register(server, username, password) {
checkTypes(arguments, ['string', 'string', 'string']);
console.warn("User.register is deprecated. Please use User.login(server, Credentials.usernamePassword(...)) instead.");
const credentials = credentialsMethods.usernamePassword(username, password, /* createUser */ true);
return this.login(server, credentials);
},
registerWithProvider(server, options) {
checkTypes(arguments, ['string', 'object']);
console.warn("User.registerWithProvider is deprecated. Please use User.login(server, Credentials.SOME-PROVIDER(...)) instead.");
const credentials = credentialsMethods.custom(options.provider, options.providerToken, options.userInfo);
return this.login(server, credentials);
},
authenticate(server, provider, options) {
checkTypes(arguments, ['string', 'string', 'object'])
console.warn("User.authenticate is deprecated. Please use User.login(server, Credentials.SOME-PROVIDER(...)) instead.");
let credentials;
switch (provider.toLowerCase()) {
case 'jwt':
credentials = credentialsMethods.jwt(options.token, 'jwt');
break
case 'password':
credentials = credentialsMethods.usernamePassword(options.username, options.password);
break
default:
credentials = credentialsMethods.custom(provider, options.data, options.user_info || options.userInfo);
break;
}
return this.login(server, credentials);
},
};
const instanceMethods = {
logout() {
this._logout();
const userTimers = refreshTimers[this.identity];
if (userTimers) {
Object.keys(userTimers).forEach((key) => {
clearTimeout(userTimers[key]);
});
delete refreshTimers[this.identity];
}
const url = url_parse(this.server);
url.set('pathname', '/auth/revoke');
const options = {
method: 'POST',
headers: { Authorization: this.token },
body: { token: this.token },
open_timeout: 5000
};
return performFetch(url.href, options)
.catch((e) => print_error('An error occurred while logging out a user', e));
},
serialize() {
if (this.isAdminToken) {
return {
server: this.server,
adminToken: this.token,
}
}
return {
server: this.server,
refreshToken: this.token,
identity: this.identity,
isAdmin: this.isAdmin,
};
},
openManagementRealm() {
let url = url_parse(this.server);
if (url.protocol === 'http:') {
url.set('protocol', 'realm:');
} else if (url.protocol === 'https:') {
url.set('protocol', 'realms:');
} else {
throw new Error(`Unexpected user auth url: ${this.server}`);
}
url.set('pathname', '/~/__management');
return new this.constructor._realmConstructor({
schema: require('./management-schema'),
sync: {
user: this,
url: url.href
}
});
},
retrieveAccount(provider, provider_id) {
checkTypes(arguments, ['string', 'string']);
const url = url_parse(this.server);
url.set('pathname', `/auth/users/${provider}/${provider_id}`);
const options = {
method: 'GET',
headers: { Authorization: this.token },
open_timeout: 5000
};
return performFetch(url.href, options)
.then((response) => {
if (response.status !== 200) {
return response.json()
.then(body => {
throw new AuthError(body);
});
} else {
return response.json();
}
});
},
createConfiguration(config) {
if (config && config.sync) {
if (config.sync.user && console.warn !== undefined) {
console.warn(`'user' property will be overridden by ${this.identity}`);
}
if (config.sync.partial !== undefined && config.sync.fullSynchronization !== undefined) {
throw new Error("'partial' and 'fullSynchronization' were both set. 'partial' has been deprecated, use only 'fullSynchronization'");
}
}
let defaultConfig = {
sync: {
user: this,
},
};
// Set query-based as the default setting if the user doesn't specified any other behaviour.
if (!(config && config.sync && config.sync.partial)) {
defaultConfig.sync.fullSynchronization = false;
}
// Merge default configuration with user provided config. User defined properties should aways win.
// Doing the naive merge in JS break objects that are backed by native objects, so these needs to
// be merged manually. This is currently only `sync.user`.
let mergedConfig = (config === undefined) ? defaultConfig : merge(defaultConfig, config);
mergedConfig.sync.user = this;
// Parsing the URL requires extra handling as some forms of input (e.g. relative URLS) should not completely
// override the default url.
mergedConfig.sync.url = normalizeSyncUrl(this.server, (config && config.sync) ? config.sync.url : undefined);
return mergedConfig;
},
};
class Credentials {
constructor(identityProvider, token, userInfo) {
this.identityProvider = identityProvider;
this.token = token;
this.userInfo = userInfo || {};
}
toJSON() {
return {
data: this.token,
provider: this.identityProvider,
user_info: this.userInfo,
};
}
}
// Append the permission apis
Object.assign(instanceMethods, permissionApis);
module.exports = {
static: staticMethods,
instance: instanceMethods,
credentials: credentialsMethods,
};