-
Notifications
You must be signed in to change notification settings - Fork 555
/
Copy pathindex.js
596 lines (485 loc) · 16.8 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
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 { parseUrl } 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 { processSocialOptions } from '../connection/social/index';
import { clientConnections, hasFreeSubscription } from './client/index';
const {
get,
init,
remove,
reset,
set,
tget,
tset,
tremove
} = dataFns(["core"]);
const { tset: tsetSocial } = dataFns(["social"]);
export function setup(id, clientID, domain, options, hookRunner, emitEventFn) {
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,
oidcConformant: options.oidcConformant || false,
hashCleanup: options.hashCleanup === false ? false : true,
allowedConnections: Immutable.fromJS(options.allowedConnections || []),
ui: extractUIOptions(id, options),
defaultADUsernameFromEmailPrefix: options.defaultADUsernameFromEmailPrefix === false ? false : true
}));
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 oidcConformant(m) {
return get(m, "oidcConformant");
}
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 rendering(m) {
return tget(m, "render", false);
}
export function stopRendering(m) {
return tremove(m, "render");
}
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,
authButtonsTheme: typeof authButtons === "object" ? authButtons : {}
});
}
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"),
rememberLastLogin: m => tget(
m,
"rememberLastLogin",
getUIAttribute(m, "rememberLastLogin")
)
};
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 || {};
let {
oidcConformant
} = options;
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 || window.location.href;
sso = typeof sso === "boolean" ? sso : true;
if (!oidcConformant && trim(params.scope || "") === "openid profile") {
warn(options, "Usage of scope 'openid profile' is not recommended. See https://auth0.com/docs/scopes for more details.");
}
if (oidcConformant && !redirect && responseType.indexOf('id_token') > -1) {
throw new Error("It is not posible to request an 'id_token' while using popup mode.");
}
// for legacy flow, the scope should default to openid
if (!oidcConformant && !params.scope) {
params.scope = 'openid';
}
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;
}
const domainUrl = "https://" + domain;
const hostname = parseUrl(domainUrl).hostname;
const DOT_AUTH0_DOT_COM = ".auth0.com";
const AUTH0_US_CDN_URL = "https://cdn.auth0.com";
if (endsWith(hostname, DOT_AUTH0_DOT_COM)) {
const parts = hostname.split(".");
return parts.length > 3
? "https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM
: AUTH0_US_CDN_URL;
} else {
return domainUrl;
}
}
export function extractTenantBaseUrlOption(opts, domain) {
if (opts.configurationBaseUrl && typeof opts.configurationBaseUrl === "string") {
return urljoin(opts.configurationBaseUrl, 'info-v1.js');
}
if (opts.assetsUrl && typeof opts.assetsUrl === "string") {
return opts.assetsUrl;
}
const domainUrl = "https://" + domain;
const hostname = parseUrl(domainUrl).hostname;
const DOT_AUTH0_DOT_COM = ".auth0.com";
const AUTH0_US_CDN_URL = "https://cdn.auth0.com";
const parts = hostname.split(".");
const tenant_name = parts[0];
var domain;
if (endsWith(hostname, DOT_AUTH0_DOT_COM)) {
domain = parts.length > 3
? "https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM
: AUTH0_US_CDN_URL;
return urljoin(domain, '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 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 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 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.str(m, ["error", "login", "lock.network"]);
}
// Custom rule error (except blocked_user)
if (error.code === "rule_error") {
return error.description
|| i18n.str(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";
}
return i18n.str(m, ["error", "login", code])
|| i18n.str(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.socialButtonStyle) {
let curated = processSocialOptions(opts);
m = tsetSocial(m, "socialButtonStyle", curated.socialButtonStyle);
}
if (opts.flashMessage) {
const key = "success" === opts.flashMessage.type ? "globalSuccess" : "globalError";
m = tset(m, key, 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);
}
return m;
}