-
Notifications
You must be signed in to change notification settings - Fork 554
/
index.js
678 lines (559 loc) · 20.5 KB
/
index.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
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
import urljoin from 'url-join';
import Immutable, { List, Map, Set } from 'immutable';
import { isSmallScreen } from '../utils/media_utils';
import { endsWith } from '../utils/string_utils';
import { getLocationFromUrl, getOriginFromUrl } from '../utils/url_utils';
import * as i18n from '../i18n';
import trim from 'trim';
import * as gp from '../avatar/gravatar_provider';
import { dataFns } from '../utils/data_utils';
import { clientConnections, hasFreeSubscription } from './client/index';
import * as captchaField from '../field/captcha';
const { get, init, remove, reset, set, tget, tset, tremove } = dataFns(['core']);
export const validPublicHooks = ['loggingIn', 'signingUp'];
export function setup(id, clientID, domain, options, hookRunner, emitEventFn, handleEventFn) {
let m = init(
id,
Immutable.fromJS({
clientBaseUrl: extractClientBaseUrlOption(options, domain),
tenantBaseUrl: extractTenantBaseUrlOption(options, domain),
languageBaseUrl: extractLanguageBaseUrlOption(options, domain),
auth: extractAuthOptions(options),
clientID: clientID,
domain: domain,
emitEventFn: emitEventFn,
hookRunner: hookRunner,
useTenantInfo: options.__useTenantInfo || false,
hashCleanup: options.hashCleanup === false ? false : true,
allowedConnections: Immutable.fromJS(options.allowedConnections || []),
useCustomPasswordlessConnection:
options.useCustomPasswordlessConnection === true ? true : false,
ui: extractUIOptions(id, options),
defaultADUsernameFromEmailPrefix:
options.defaultADUsernameFromEmailPrefix === false ? false : true,
prefill: options.prefill || {},
connectionResolver: options.connectionResolver,
handleEventFn: handleEventFn,
hooks: extractHookOptions(options)
})
);
m = i18n.initI18n(m);
return m;
}
export function id(m) {
return m.get('id');
}
export function clientID(m) {
return get(m, 'clientID');
}
export function domain(m) {
return get(m, 'domain');
}
export function clientBaseUrl(m) {
return get(m, 'clientBaseUrl');
}
export function tenantBaseUrl(m) {
return get(m, 'tenantBaseUrl');
}
export function useTenantInfo(m) {
return get(m, 'useTenantInfo');
}
export function connectionResolver(m) {
return get(m, 'connectionResolver');
}
export function setResolvedConnection(m, resolvedConnection) {
if (!resolvedConnection) {
return set(m, 'resolvedConnection', undefined);
}
if (!resolvedConnection.type || !resolvedConnection.name) {
throw new Error(
'Invalid connection object. The resolved connection must look like: `{ type: "database", name: "connection name" }`.'
);
}
if (resolvedConnection.type !== 'database') {
throw new Error(
'Invalid connection type. Only database connections can be resolved with a custom resolver.'
);
}
return set(m, 'resolvedConnection', Immutable.fromJS(resolvedConnection));
}
export function resolvedConnection(m) {
const resolvedConnection = get(m, 'resolvedConnection');
if (!resolvedConnection) {
return undefined;
}
return findConnection(m, resolvedConnection.get('name'));
}
export function languageBaseUrl(m) {
return get(m, 'languageBaseUrl');
}
export function setSubmitting(m, value, error = '') {
m = tset(m, 'submitting', value);
m = clearGlobalSuccess(m);
m = error && !value ? setGlobalError(m, error) : clearGlobalError(m);
return m;
}
export function submitting(m) {
return tget(m, 'submitting', false);
}
export function setGlobalError(m, str) {
return tset(m, 'globalError', str);
}
export function globalError(m) {
return tget(m, 'globalError', '');
}
export function clearGlobalError(m) {
return tremove(m, 'globalError');
}
export function setGlobalSuccess(m, str) {
return tset(m, 'globalSuccess', str);
}
export function globalSuccess(m) {
return tget(m, 'globalSuccess', '');
}
export function clearGlobalSuccess(m) {
return tremove(m, 'globalSuccess');
}
export function setGlobalInfo(m, str) {
return tset(m, 'globalInfo', str);
}
export function globalInfo(m) {
return tget(m, 'globalInfo', '');
}
export function clearGlobalInfo(m) {
return tremove(m, 'globalInfo');
}
export function rendering(m) {
return tget(m, 'render', false);
}
export function stopRendering(m) {
return tremove(m, 'render');
}
export function setSupressSubmitOverlay(m, b) {
return set(m, 'suppressSubmitOverlay', b);
}
export function suppressSubmitOverlay(m) {
return get(m, 'suppressSubmitOverlay');
}
export function hooks(m) {
return get(m, 'hooks');
}
function extractUIOptions(id, options) {
const closable = options.container
? false
: undefined === options.closable
? true
: !!options.closable;
const theme = options.theme || {};
const { labeledSubmitButton, hideMainScreenTitle, logo, primaryColor, authButtons } = theme;
const avatar = options.avatar !== null;
const customAvatarProvider =
options.avatar &&
typeof options.avatar.url === 'function' &&
typeof options.avatar.displayName === 'function' &&
options.avatar;
const avatarProvider = customAvatarProvider || gp;
return new Immutable.fromJS({
containerID: options.container || `auth0-lock-container-${id}`,
appendContainer: !options.container,
autoclose: undefined === options.autoclose ? false : closable && options.autoclose,
autofocus:
undefined === options.autofocus
? !(options.container || isSmallScreen())
: !!options.autofocus,
avatar: avatar,
avatarProvider: avatarProvider,
logo: typeof logo === 'string' ? logo : undefined,
closable: closable,
hideMainScreenTitle: !!hideMainScreenTitle,
labeledSubmitButton: undefined === labeledSubmitButton ? true : !!labeledSubmitButton,
language: undefined === options.language ? 'en' : trim(options.language || '').toLowerCase(),
dict: typeof options.languageDictionary === 'object' ? options.languageDictionary : {},
disableWarnings: options.disableWarnings === undefined ? false : !!options.disableWarnings,
mobile: undefined === options.mobile ? false : !!options.mobile,
popupOptions: undefined === options.popupOptions ? {} : options.popupOptions,
primaryColor: typeof primaryColor === 'string' ? primaryColor : undefined,
rememberLastLogin: undefined === options.rememberLastLogin ? true : !!options.rememberLastLogin,
allowAutocomplete: !!options.allowAutocomplete,
preferConnectionDisplayName: !!options.preferConnectionDisplayName,
authButtonsTheme: typeof authButtons === 'object' ? authButtons : {},
allowShowPassword: !!options.allowShowPassword,
allowPasswordAutocomplete: !!options.allowPasswordAutocomplete,
scrollGlobalMessagesIntoView:
undefined === options.scrollGlobalMessagesIntoView
? true
: !!options.scrollGlobalMessagesIntoView,
forceAutoHeight: !!options.forceAutoHeight
});
}
function extractHookOptions(options) {
const hooks = {};
validPublicHooks.forEach(hookName => {
if (options.hooks && typeof options.hooks[hookName] === 'function') {
hooks[hookName] = options.hooks[hookName];
}
});
return new Immutable.fromJS(hooks);
}
const { get: getUI, set: setUI } = dataFns(['core', 'ui']);
const { get: tgetUI, set: tsetUI } = dataFns(['core', 'transient', 'ui']);
const getUIAttribute = (m, attribute) => {
return tgetUI(m, attribute) || getUI(m, attribute);
};
export const ui = {
containerID: lock => getUIAttribute(lock, 'containerID'),
appendContainer: lock => getUIAttribute(lock, 'appendContainer'),
autoclose: lock => getUIAttribute(lock, 'autoclose'),
autofocus: lock => getUIAttribute(lock, 'autofocus'),
avatar: lock => getUIAttribute(lock, 'avatar'),
avatarProvider: lock => getUIAttribute(lock, 'avatarProvider'),
closable: lock => getUIAttribute(lock, 'closable'),
dict: lock => getUIAttribute(lock, 'dict'),
disableWarnings: lock => getUIAttribute(lock, 'disableWarnings'),
labeledSubmitButton: lock => getUIAttribute(lock, 'labeledSubmitButton'),
hideMainScreenTitle: lock => getUIAttribute(lock, 'hideMainScreenTitle'),
language: lock => getUIAttribute(lock, 'language'),
logo: lock => getUIAttribute(lock, 'logo'),
mobile: lock => getUIAttribute(lock, 'mobile'),
popupOptions: lock => getUIAttribute(lock, 'popupOptions'),
primaryColor: lock => getUIAttribute(lock, 'primaryColor'),
authButtonsTheme: lock => getUIAttribute(lock, 'authButtonsTheme'),
preferConnectionDisplayName: lock => getUIAttribute(lock, 'preferConnectionDisplayName'),
rememberLastLogin: m => tget(m, 'rememberLastLogin', getUIAttribute(m, 'rememberLastLogin')),
allowAutocomplete: m => tget(m, 'allowAutocomplete', getUIAttribute(m, 'allowAutocomplete')),
scrollGlobalMessagesIntoView: lock => getUIAttribute(lock, 'scrollGlobalMessagesIntoView'),
allowShowPassword: m => tget(m, 'allowShowPassword', getUIAttribute(m, 'allowShowPassword')),
allowPasswordAutocomplete: m =>
tget(m, 'allowPasswordAutocomplete', getUIAttribute(m, 'allowPasswordAutocomplete')),
forceAutoHeight: m => tget(m, 'forceAutoHeight', getUIAttribute(m, 'forceAutoHeight'))
};
const { get: getAuthAttribute } = dataFns(['core', 'auth']);
export const auth = {
connectionScopes: m => getAuthAttribute(m, 'connectionScopes'),
params: m => tget(m, 'authParams') || getAuthAttribute(m, 'params'),
autoParseHash: lock => getAuthAttribute(lock, 'autoParseHash'),
redirect: lock => getAuthAttribute(lock, 'redirect'),
redirectUrl: lock => getAuthAttribute(lock, 'redirectUrl'),
responseType: lock => getAuthAttribute(lock, 'responseType'),
sso: lock => getAuthAttribute(lock, 'sso')
};
function extractAuthOptions(options) {
let {
audience,
connectionScopes,
params,
autoParseHash,
redirect,
redirectUrl,
responseMode,
responseType,
sso,
state,
nonce
} = options.auth || {};
if (options.auth && options.auth.redirectUri) {
console.warn(
"You're sending an `auth` option named `redirectUri`. This option will be ignored. Use `redirectUrl` instead."
);
}
audience = typeof audience === 'string' ? audience : undefined;
connectionScopes = typeof connectionScopes === 'object' ? connectionScopes : {};
params = typeof params === 'object' ? params : {};
// by default is null because we need to know if it was set when we curate the responseType
redirectUrl = typeof redirectUrl === 'string' && redirectUrl ? redirectUrl : null;
autoParseHash = typeof autoParseHash === 'boolean' ? autoParseHash : true;
redirect = typeof redirect === 'boolean' ? redirect : true;
responseMode = typeof responseMode === 'string' ? responseMode : undefined;
state = typeof state === 'string' ? state : undefined;
nonce = typeof nonce === 'string' ? nonce : undefined;
// if responseType was not set and there is a redirectUrl, it defaults to code. Otherwise token.
responseType = typeof responseType === 'string' ? responseType : redirectUrl ? 'code' : 'token';
// now we set the default because we already did the validation
redirectUrl =
redirectUrl || `${getOriginFromUrl(window.location.href)}${window.location.pathname}`;
sso = typeof sso === 'boolean' ? sso : true;
if (!params.scope) {
params.scope = 'openid profile email';
}
return Immutable.fromJS({
audience,
connectionScopes,
params,
autoParseHash,
redirect,
redirectUrl,
responseMode,
responseType,
sso,
state,
nonce
});
}
export function withAuthOptions(m, opts) {
return Immutable.fromJS(opts).merge(get(m, 'auth')).toJS();
}
function extractClientBaseUrlOption(opts, domain) {
if (opts.clientBaseUrl && typeof opts.clientBaseUrl === 'string') {
return opts.clientBaseUrl;
}
if (opts.configurationBaseUrl && typeof opts.configurationBaseUrl === 'string') {
return opts.configurationBaseUrl;
}
if (opts.assetsUrl && typeof opts.assetsUrl === 'string') {
return opts.assetsUrl;
}
return `https://${domain}`;
}
export function extractTenantBaseUrlOption(opts, domain) {
if (opts.configurationBaseUrl && typeof opts.configurationBaseUrl === 'string') {
if (opts.overrides && opts.overrides.__tenant) {
// When using a custom domain and a configuration URL hosted in auth0's cdn
return urljoin(opts.configurationBaseUrl, 'tenants', 'v1', `${opts.overrides.__tenant}.js`);
}
return urljoin(opts.configurationBaseUrl, 'info-v1.js');
}
if (opts.assetsUrl && typeof opts.assetsUrl === 'string') {
return opts.assetsUrl;
}
const domainUrl = 'https://' + domain;
const hostname = getLocationFromUrl(domainUrl).hostname;
const DOT_AUTH0_DOT_COM = '.auth0.com';
// prettier-ignore
if (endsWith(hostname, DOT_AUTH0_DOT_COM)) { // lgtm [js/incomplete-url-substring-sanitization]
const parts = hostname.split('.');
const tenant_name = parts[0];
return urljoin(domainUrl, 'tenants', 'v1', `${tenant_name}.js`);
} else {
return urljoin(domainUrl, 'info-v1.js');
}
}
function extractLanguageBaseUrlOption(opts, domain) {
if (opts.languageBaseUrl && typeof opts.languageBaseUrl === 'string') {
return opts.languageBaseUrl;
}
if (opts.assetsUrl && typeof opts.assetsUrl === 'string') {
return opts.assetsUrl;
}
return 'https://cdn.auth0.com';
}
export function render(m) {
return tset(m, 'render', true);
}
export { reset };
export function setLoggedIn(m, value) {
return tset(m, 'loggedIn', value);
}
export function loggedIn(m) {
return tget(m, 'loggedIn', false);
}
export function defaultADUsernameFromEmailPrefix(m) {
return get(m, 'defaultADUsernameFromEmailPrefix', true);
}
export function setCaptcha(m, value, wasInvalid) {
m = captchaField.reset(m, wasInvalid);
return set(m, 'captcha', Immutable.fromJS(value));
}
export function captcha(m) {
//some tests send an string as model.
// https://github.com/auth0/lock/blob/82f56187698528699478bd429858cf91e387763c/src/__tests__/engine/classic/sign_up_pane.test.jsx#L28
if (typeof m !== 'object') {
return;
}
return get(m, 'captcha');
}
export function prefill(m) {
return get(m, 'prefill', {});
}
export function warn(x, str) {
const shouldOutput = Map.isMap(x) ? !ui.disableWarnings(x) : !x.disableWarnings;
if (shouldOutput && console && console.warn) {
console.warn(str);
}
}
export function error(x, str) {
const shouldOutput = Map.isMap(x) ? !ui.disableWarnings(x) : !x.disableWarnings;
if (shouldOutput && console && console.error) {
console.error(str);
}
}
export function allowedConnections(m) {
return tget(m, 'allowedConnections') || get(m, 'allowedConnections');
}
export function connections(m, type = undefined, ...strategies) {
if (arguments.length === 1) {
return tget(m, 'connections', Map())
.filter((v, k) => k !== 'unknown')
.valueSeq()
.flatten(true);
}
const xs = tget(m, ['connections', type], List());
return strategies.length > 0 ? xs.filter(x => ~strategies.indexOf(x.get('strategy'))) : xs;
}
export function connection(m, type = undefined, ...strategies) {
return connections(m, type, ...strategies).get(0);
}
export function hasOneConnection(m, type = undefined) {
const xs = connections(m);
return xs.count() === 1 && (!type || xs.getIn([0, 'type']) === type);
}
export function hasOnlyConnections(m, type = undefined, ...strategies) {
const all = connections(m).count();
const filtered = connections(m, type, ...strategies).count();
return all > 0 && all === filtered;
}
export function hasSomeConnections(m, type = undefined, ...strategies) {
return countConnections(m, type, ...strategies) > 0;
}
export function countConnections(m, type = undefined, ...strategies) {
return connections(m, type, ...strategies).count();
}
export function findConnection(m, name) {
return connections(m).find(m1 => m1.get('name') === name);
}
export function hasConnection(m, name) {
return !!findConnection(m, name);
}
export function filterConnections(m) {
const allowed = allowedConnections(m);
const order = allowed.count() === 0 ? _ => 0 : c => allowed.indexOf(c.get('name'));
return tset(
m,
'connections',
clientConnections(m).map(cs => {
return cs.filter(c => order(c) >= 0).sort((c1, c2) => order(c1) - order(c2));
})
);
}
export function useCustomPasswordlessConnection(m) {
return get(m, 'useCustomPasswordlessConnection');
}
export function runHook(m, str, ...args) {
return get(m, 'hookRunner')(str, m, ...args);
}
export function emitEvent(m, str, ...args) {
setTimeout(() => {
const emitEventFn = get(m, 'emitEventFn');
const hadListener = emitEventFn(str, ...args);
// Handle uncaught custom error
if (str === 'unrecoverable_error' && !hadListener) {
throw new Error(...args);
}
}, 0);
}
export function handleEvent(m, str, ...args) {
const handleEventFn = get(m, 'handleEventFn');
handleEventFn(str, ...args);
}
export function loginErrorMessage(m, error, type) {
// NOTE: previous version of lock checked for status codes and, at
// some point, if the status code was 401 it defaults to an
// "invalid_user_password" error (actually the
// "wrongEmailPasswordErrorText" dict entry) instead of checking
// explicitly. We should figure out if there was a reason for that.
if (error.status === 0) {
return i18n.html(m, ['error', 'login', 'lock.network']);
}
// Custom rule or hook error (except blocked_user)
if (error.code === 'rule_error' || error.code === 'hook_error') {
return error.description || i18n.html(m, ['error', 'login', 'lock.fallback']);
}
const INVALID_MAP = {
code: 'lock.invalid_code',
email: 'lock.invalid_email_password',
username: 'lock.invalid_username_password'
};
let code = error.error || error.code;
if (code === 'invalid_user_password' && INVALID_MAP[type]) {
code = INVALID_MAP[type];
}
if (code === 'a0.mfa_registration_required') {
code = 'lock.mfa_registration_required';
}
if (code === 'a0.mfa_invalid_code') {
code = 'lock.mfa_invalid_code';
}
if (code === 'password_expired') {
code = 'password_change_required';
}
if (code === 'invalid_captcha') {
const currentCaptcha = get(m, 'captcha');
if (currentCaptcha && currentCaptcha.get('provider') === 'recaptcha_v2') {
code = 'invalid_recaptcha';
}
}
return (
i18n.html(m, ['error', 'login', code]) || i18n.html(m, ['error', 'login', 'lock.fallback'])
);
}
// TODO: rename to something less generic that is easier to grep
export function stop(m, error) {
if (error) {
setTimeout(() => emitEvent(m, 'unrecoverable_error', error), 17);
}
return set(m, 'stopped', true);
}
export function hasStopped(m) {
return get(m, 'stopped');
}
export function hashCleanup(m) {
return get(m, 'hashCleanup');
}
export function emitHashParsedEvent(m, parsedHash) {
emitEvent(m, 'hash_parsed', parsedHash);
}
export function emitAuthenticatedEvent(m, result) {
emitEvent(m, 'authenticated', result);
}
export function emitAuthorizationErrorEvent(m, error) {
emitEvent(m, 'authorization_error', error);
}
export function emitUnrecoverableErrorEvent(m, error) {
emitEvent(m, 'unrecoverable_error', error);
}
export function showBadge(m) {
return hasFreeSubscription(m) || false;
}
export function overrideOptions(m, opts) {
if (!opts) opts = {};
if (opts.allowedConnections) {
m = tset(m, 'allowedConnections', Immutable.fromJS(opts.allowedConnections));
}
if (opts.flashMessage) {
const { type } = opts.flashMessage;
const typeCapitalized = type.charAt(0).toUpperCase() + type.slice(1);
m = tset(m, `global${typeCapitalized}`, opts.flashMessage.text);
}
if (opts.auth && opts.auth.params) {
m = tset(m, 'authParams', Immutable.fromJS(opts.auth.params));
}
if (opts.theme) {
if (opts.theme.primaryColor) {
m = tset(m, ['ui', 'primaryColor'], opts.theme.primaryColor);
}
if (opts.theme.logo) {
m = tset(m, ['ui', 'logo'], opts.theme.logo);
}
}
if (opts.language || opts.languageDictionary) {
if (opts.language) {
m = tset(m, ['ui', 'language'], opts.language);
}
if (opts.languageDictionary) {
m = tset(m, ['ui', 'dict'], opts.languageDictionary);
}
m = i18n.initI18n(m);
}
if (typeof opts.rememberLastLogin === 'boolean') {
m = tset(m, 'rememberLastLogin', opts.rememberLastLogin);
}
if (typeof opts.allowAutocomplete === 'boolean') {
m = tset(m, 'allowAutocomplete', opts.allowAutocomplete);
}
if (typeof opts.allowShowPassword === 'boolean') {
m = tset(m, 'allowShowPassword', opts.allowShowPassword);
}
if (typeof opts.allowPasswordAutocomplete === 'boolean') {
m = tset(m, 'allowPasswordAutocomplete', opts.allowPasswordAutocomplete);
}
return m;
}