forked from firebase/firebaseui-web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthui_test.js
More file actions
5501 lines (5165 loc) · 189 KB
/
authui_test.js
File metadata and controls
5501 lines (5165 loc) · 189 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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/
/**
* @fileoverview Tests for app.js
*/
goog.provide('firebaseui.auth.AuthUITest');
goog.require('firebaseui.auth.ActionCodeUrlBuilder');
goog.require('firebaseui.auth.AuthUI');
goog.require('firebaseui.auth.AuthUIError');
goog.require('firebaseui.auth.GoogleYolo');
goog.require('firebaseui.auth.PendingEmailCredential');
goog.require('firebaseui.auth.RedirectStatus');
goog.require('firebaseui.auth.idp');
goog.require('firebaseui.auth.log');
goog.require('firebaseui.auth.storage');
goog.require('firebaseui.auth.testing.FakeAppClient');
goog.require('firebaseui.auth.testing.FakeCookieStorage');
goog.require('firebaseui.auth.testing.FakeUtil');
goog.require('firebaseui.auth.ui.page.Callback');
goog.require('firebaseui.auth.ui.page.ProviderSignIn');
goog.require('firebaseui.auth.util');
goog.require('firebaseui.auth.widget.Config');
goog.require('firebaseui.auth.widget.dispatcher');
goog.require('firebaseui.auth.widget.handler');
goog.require('firebaseui.auth.widget.handler.common');
/** @suppress {extraRequire} Required for page navigation after form submission
* to work. */
goog.require('firebaseui.auth.widget.handler.handleCallback');
/** @suppress {extraRequire} Required for page navigation after form submission
* to work. */
goog.require('firebaseui.auth.widget.handler.handlePasswordSignIn');
/** @suppress {extraRequire} Required for page navigation after form submission
* to work. */
goog.require('firebaseui.auth.widget.handler.handleProviderSignIn');
goog.require('firebaseui.auth.widget.handler.startSignIn');
goog.require('goog.Promise');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classlist');
goog.require('goog.object');
goog.require('goog.testing.AsyncTestCase');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.mockmatchers');
goog.require('goog.testing.recordFunction');
goog.setTestOnly('firebaseui.auth.AuthUITest');
var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
// Test application instances.
var app;
var app1;
var app2;
var app3;
// Test configuration objects.
var config1;
var config2;
var config3;
var config4;
// Test stubs for handlers and widget dispatcher.
var testStubs = new goog.testing.PropertyReplacer();
// Container elements for sign-in button and widget rendering.
var container1;
var container2;
var container3;
// Test util for goto utilities.
var testUtil;
// Firebase Auth test tokens.
var passwordIdToken1 = 'HEADER1.eyJhdWQiOiAiY2xpZW50X2lkIiwgImVtYWlsIjogInVz' +
'ZXJAZXhhbXBsZS5jb20iLCAiaXNzIjogMTQwNDYzMzQ0MiwgImV4cCI6IDE1MDQ2MzM0NDJ' +
'9.SIGNATURE1';
var passwordIdToken2 = 'HEADER2.eyJhdWQiOiAiY2xpZW50X2lkIiwgImVtYWlsIjogInVz' +
'ZXJAZXhhbXBsZS5jb20iLCAiaXNzIjogMTQwNDYzMzQ0MiwgImV4cCI6IDE1MDQ2MzM0NDJ' +
'9.SIGNATURE2';
var passwordIdToken3 = 'HEADER3.eyJhdWQiOiAiY2xpZW50X2lkIiwgImVtYWlsIjogInVz' +
'ZXJAZXhhbXBsZS5jb20iLCAiaXNzIjogMTQwNDYzMzQ0MiwgImV4cCI6IDE1MDQ2MzM0NDJ' +
'9.SIGNATURE3';
var testApp;
var testApp1;
var testApp2;
var testApp3;
var testAuth;
var testAuth1;
var testAuth2;
var testAuth3;
var firebase = {};
var options = {
'apiKey': 'API_KEY',
'authDomain': 'subdomain.firebaseapp.com'
};
var googYoloClientId = '1234567890.apps.googleusercontent.com';
// Mock googleyolo ID token credential.
var googleYoloIdTokenCredential = {
'credential': 'ID_TOKEN',
'clientId': googYoloClientId,
};
var mockControl;
var ignoreArgument;
var expectedUser = {
uid: '1234567890',
email: 'user@example.com',
displayName: 'Federated User',
providerData: [{
'uid': 'FED_ID',
'email': 'user@example.com',
'displayName': 'Federated User',
'providerId': 'google.com'
}, {
'uid': 'user@example.com',
'email': 'user@example.com',
'providerId': 'password'
}]
};
var expectedCredential =
{'accessToken': 'googleAccessToken', 'providerId': 'google.com'};
var expectedAdditionalUserInfo = {
'profile': {
'kind': 'plus#person',
'displayName': 'John Doe',
'name': {
'givenName': 'John',
'familyName': 'Doe'
}
},
'providerId': 'google.com',
'isNewUser': false
};
var expectedUserCredential = {
'user': expectedUser,
'credential': expectedCredential,
'operationType': 'signIn',
'additionalUserInfo': expectedAdditionalUserInfo
};
var pendingCredential = null;
var pendingEmailCredential = null;
var expectedProvider = null;
var anonymousUpgradeConfig = null;
var anonymousUser = {
uid: '1234567890',
isAnonymous: true
};
var emailLinkSignInConfig = null;
var testCookieStorage;
var mockClock = new goog.testing.MockClock();
/**
* @param {!Element} container The container element to check.
* @param {string} cssName The css class name to check for.
* Asserts the element provided has a child with the provided css name.
*/
function assertHasCssClass(container, cssName) {
var page = container.children[0];
assertTrue(goog.dom.classlist.contains(page, goog.getCssName(cssName)));
}
/**
* Asserts that two errors are equivalent. Plain assertObjectEquals cannot be
* used as Internet Explorer adds the stack trace as a property of the object.
* @param {!firebaseui.auth.AuthUIError} expected
* @param {!firebaseui.auth.AuthUIError} actual
*/
function assertErrorEquals(expected, actual) {
assertObjectEquals(expected.toPlainObject(), actual.toPlainObject());
}
function setUp() {
testCookieStorage = new firebaseui.auth.testing.FakeCookieStorage().install();
mockClock.install();
// Used to initialize internal Auth instance.
firebase = {};
firebase.instances_ = {};
firebase.initializeApp = function(options, name) {
// Throw an error if a FirebaseApp already exists for the specified name.
var key = name || '[DEFAULT]';
if (firebase.instances_[key]) {
throw new Error('An app instance already exists for ' + key);
} else {
firebase.instances_[key] =
new firebaseui.auth.testing.FakeAppClient(options, name);
}
var firebaseApp = firebase.instances_[key];
// Make sure auth instance is installed.
// This is needed to confirm auth API calls on internal instance in the
// AuthUI constructor.
firebaseApp.auth().install();
return firebaseApp;
};
// Define firebase.auth.Auth.Persistence enum.
firebase.auth = firebase.auth || {};
firebase.auth.Auth = firebase.auth.Auth || {};
firebase.auth.Auth.Persistence = firebase.auth.Auth.Persistence || {
LOCAL: 'local',
NONE: 'none',
SESSION: 'session'
};
// On FirebaseApp deletion, confirm instance not already deleted and then
// remove it from firebase.instances_.
testStubs.replace(
firebaseui.auth.testing.FakeAppClient.prototype,
'delete',
function() {
// Already deleted.
if (!firebase.instances_[this['name']]) {
throw new Error('Instance ' + key + ' already deleted!');
}
delete firebase.instances_[this['name']];
return goog.Promise.resolve();
});
testStubs.replace(
firebaseui.auth.util,
'generateRandomAlphaNumericString',
function(size) {
assertEquals(32, size);
return 'SESSIONID';
});
// Create all test elements and append to document.
container1 = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'element1'});
document.body.appendChild(container1);
container2 = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'element2'});
document.body.appendChild(container2);
container3 = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'element3'});
document.body.appendChild(container3);
// Record all handler functions and widget dispatch functions.
testStubs.set(
firebaseui.auth.widget.handler,
'startSignIn',
goog.testing.recordFunction());
testStubs.set(
firebaseui.auth.widget.dispatcher,
'dispatchOperation',
goog.testing.recordFunction());
// Install fake test utilities.
testUtil = new firebaseui.auth.testing.FakeUtil().install();
ignoreArgument = goog.testing.mockmatchers.ignoreArgument;
mockControl = new goog.testing.MockControl();
// Build mock auth providers.
for (var key in firebaseui.auth.idp.AuthProviders) {
firebase['auth'][firebaseui.auth.idp.AuthProviders[key]] = function() {
this.scopes = [];
this.customParameters = {};
};
firebase['auth'][firebaseui.auth.idp.AuthProviders[key]].PROVIDER_ID = key;
if (key != 'twitter.com' && key != 'password') {
firebase['auth'][firebaseui.auth.idp.AuthProviders[key]]
.prototype.addScope = function(scope) {
this.scopes.push(scope);
return this;
};
}
if (key != 'password') {
// Record setCustomParameters for all OAuth providers.
firebase['auth'][firebaseui.auth.idp.AuthProviders[key]]
.prototype.setCustomParameters = function(customParameters) {
this.customParameters = customParameters;
return this;
};
}
if (key == 'password') {
// Mock credential initializer for Email/password credentials.
firebase['auth'][firebaseui.auth.idp.AuthProviders[key]]['credential'] =
function(email, password) {
return {
'email': email,
'password': password,
'providerId': 'password'
};
};
firebase.auth.EmailAuthProvider.credentialWithLink =
function(email, link) {
return {
email: email,
link: link,
providerId: 'password',
signInMethod: 'emailLink'
};
};
firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = 'emailLink';
firebase.auth.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD =
'password';
} else if (key == 'facebook.com') {
// Mock credential initializer for Facebook credentials.
firebase['auth'][firebaseui.auth.idp.AuthProviders[key]]['credential'] =
function(accessToken) {
return {
'accessToken': accessToken,
'providerId': 'facebook.com',
'signInMethod': 'facebook.com',
'toJSON': function() {
return {
'accessToken': accessToken,
'providerId': 'facebook.com',
'signInMethod': 'facebook.com'
};
}
};
};
}
}
firebase['auth']['AuthCredential'] = {
'fromJSON': function(json) {
return createMockCredential(json);
}
};
pendingCredential = createMockCredential(
{'accessToken': 'fbAccessToken', 'providerId': 'facebook.com'});
pendingEmailCredential = new firebaseui.auth.PendingEmailCredential(
expectedUser.email, pendingCredential);
expectedProvider = new firebase.auth.GoogleAuthProvider();
anonymousUpgradeConfig = {
'autoUpgradeAnonymousUsers': true,
'callbacks': {
'signInSuccess': goog.testing.recordFunction(function() {
return false;
}),
'signInFailure': goog.testing.recordFunction(function() {
return goog.Promise.resolve();
})
}
};
emailLinkSignInConfig = {
'signInOptions': [{
'provider': 'password',
'signInMethod': firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD,
'emailLinkSignIn': function() {
return {
'url': 'https://www.example.com/completeSignIn',
'handleCodeInApp': true
};
}
}],
'callbacks': {
'signInSuccess': goog.testing.recordFunction(function() {
return false;
}),
'signInFailure': goog.testing.recordFunction(function() {
return goog.Promise.resolve();
})
}
};
}
function tearDown() {
mockClock.reset();
mockClock.uninstall();
testApp = null;
testApp1 = null;
testApp2 = null;
testApp3 = null;
// Delete all application instances.
// Uninstall internal and external Auth instances.
if (app1) {
app1.getAuth().assertSignOut([]);
app1.getAuth().uninstall();
app1.getExternalAuth().uninstall();
app1.reset();
}
app1 = null;
if (app2) {
app2.getAuth().assertSignOut([]);
app2.getAuth().uninstall();
app2.getExternalAuth().uninstall();
app2.reset();
}
app2 = null;
if (app3) {
app3.getAuth().assertSignOut([]);
app3.getAuth().uninstall();
app3.getExternalAuth().uninstall();
app3.reset();
}
app3 = null;
// Reset internals.
firebaseui.auth.AuthUI.resetAllInternals();
// Clear all web storage.
window.localStorage.clear();
window.sessionStorage.clear();
// Remove all test containers from document.
goog.dom.removeNode(container1);
goog.dom.removeNode(container2);
goog.dom.removeNode(container3);
// Reset test stubs.
testStubs.reset();
testUtil.uninstall();
testAuth.uninstall();
if (testAuth1) {
testAuth1.uninstall();
}
if (testAuth2) {
testAuth2.uninstall();
}
if (testAuth3) {
testAuth3.uninstall();
}
if (app) {
app.getAuth().assertSignOut([]);
app.getAuth().uninstall();
app.getExternalAuth().uninstall();
app.reset();
app = null;
}
mockControl.$verifyAll();
mockControl.$tearDown();
}
/**
* Returns a mock credential object with toJSON method.
* @param {!Object} credentialObject
* @return {!Object} The fake Auth credential.
*/
function createMockCredential(credentialObject) {
var copy = goog.object.clone(credentialObject);
goog.object.extend(credentialObject, {
'toJSON': function() {
return copy;
}
});
return credentialObject;
}
/** Creates and installs all auth, app and AuthUI instances for tests. */
function createAndInstallTestInstances() {
// Create and install the developer provided Auth instances.
testApp = new firebaseui.auth.testing.FakeAppClient(options);
testAuth = testApp.auth();
testAuth.install();
testApp1 = new firebaseui.auth.testing.FakeAppClient(options, 'testapp1');
testAuth1 = testApp1.auth();
testAuth1.install();
testApp2 = new firebaseui.auth.testing.FakeAppClient(options, 'testapp2');
testAuth2 = testApp2.auth();
testAuth2.install();
testApp3 = new firebaseui.auth.testing.FakeAppClient(options, 'testapp3');
testAuth3 = testApp3.auth();
testAuth3.install();
// Initialize all test apps. Do not supply an app id for third instance.
app1 = new firebaseui.auth.AuthUI(testAuth1, 'id1');
// Install all internal instances.
app1.getAuth().assertSetPersistence(['session'], null);
app2 = new firebaseui.auth.AuthUI(testAuth2, 'id2');
app2.getAuth().assertSetPersistence(['session'], null);
app3 = new firebaseui.auth.AuthUI(testAuth3);
app3.getAuth().assertSetPersistence(['session'], null);
// Initialize config objects.
config1 = {
'signInSuccessUrl': 'http://localhost/home1',
'widgetUrl': 'http://localhost/firebase1',
};
config2 = {
'signInSuccessUrl': 'http://localhost/home2',
'widgetUrl': 'http://localhost/firebase2',
};
config3 = {
'signInSuccessUrl': 'http://localhost/home3',
'widgetUrl': 'http://localhost/firebase3',
};
config4 = {
'signInSuccessUrl': 'http://localhost/home4',
'widgetUrl': 'http://localhost/firebase4',
};
// Set application configurations.
app1.setConfig(config1);
app2.setConfig(config2);
app3.setConfig(config3);
}
function testGetExternalAuth() {
createAndInstallTestInstances();
// Confirm correct Auth instance stored for each app.
assertEquals(testAuth1, app1.getExternalAuth());
assertEquals(testAuth2, app2.getExternalAuth());
assertEquals(testAuth3, app3.getExternalAuth());
// Confirm internal instances have same options as external.
assertEquals(testAuth1.app.options.apiKey, app1.getAuth().app.options.apiKey);
assertEquals('API_KEY', app1.getAuth().app.options.apiKey);
assertEquals(
'subdomain.firebaseapp.com', app1.getAuth().app.options.authDomain);
assertEquals(
testAuth1.app.options.authDomain, app1.getAuth().app.options.authDomain);
// Confirm correct name used for temp instance.
assertEquals('testapp1-firebaseui-temp', app1.getAuth().app.name);
assertEquals('testapp2-firebaseui-temp', app2.getAuth().app.name);
}
function testTempAuth_sessionPersistence() {
createAndInstallTestInstances();
// Initialize app.
testAuth.install();
app = new firebaseui.auth.AuthUI(testAuth, 'id0');
// Confirm correct name used for temp instance.
assertEquals('testapp1-firebaseui-temp', app1.getAuth().app.name);
// Confirm session persistence set on internal instance.
app.getAuth().assertSetPersistence(['session'], null);
}
function testTempAuth_emulatorConfig() {
createAndInstallTestInstances();
// Initialize app.
testAuth.install();
testAuth.useEmulator('http://localhost:1234');
app = new firebaseui.auth.AuthUI(testAuth, 'id0');
// Confirm correct name used for temp instance.
assertEquals('testapp1-firebaseui-temp', app1.getAuth().app.name);
// Confirm emulator config properly set on internal instance.
assertObjectEquals({
protocol: 'http',
host: 'localhost',
port: 1234,
options: {
disableWarnings: false,
}
}, app.getAuth().emulatorConfig);
}
function testTempAuth_emulatorConfig_handlesIPV6Hosts() {
createAndInstallTestInstances();
// Initialize app.
testAuth.install();
testAuth.useEmulator(
'http://[0:0:0:0:0:0:0:0]:1234', {disableWarnings: true});
app = new firebaseui.auth.AuthUI(testAuth, 'id0');
// Confirm correct name used for temp instance.
assertEquals('testapp1-firebaseui-temp', app1.getAuth().app.name);
// Confirm emulator config hasn't double-quoted IPv6 address.
assertObjectEquals({
protocol: 'http',
host: '[0:0:0:0:0:0:0:0]',
port: 1234,
options: {
disableWarnings: true,
}
}, app.getAuth().emulatorConfig);
}
function testAppId() {
createAndInstallTestInstances();
// Confirm correct app id stored for each app.
assertEquals('id1', app1.getAppId());
assertEquals('id2', app2.getAppId());
assertUndefined(app3.getAppId());
}
function testGetInstance() {
// Initially all instances should be null.
assertNull(firebaseui.auth.AuthUI.getInstance());
assertNull(firebaseui.auth.AuthUI.getInstance('id0'));
assertNull(firebaseui.auth.AuthUI.getInstance('id1'));
assertNull(firebaseui.auth.AuthUI.getInstance('id2'));
// Create and install test instances.
createAndInstallTestInstances();
// Confirm expected app instances returned for getInstance().
assertEquals(app1, firebaseui.auth.AuthUI.getInstance('id1'));
assertEquals(app2, firebaseui.auth.AuthUI.getInstance('id2'));
assertEquals(app3, firebaseui.auth.AuthUI.getInstance());
assertNull(firebaseui.auth.AuthUI.getInstance('id0'));
// Trying to create a new instance with an existing appId wil throw the
// expected error.
var error = assertThrows(function() {
new firebaseui.auth.AuthUI(testAuth1, 'id1');
});
assertEquals(
'An AuthUI instance already exists for the key "id1"', error.message);
}
function testIsPending() {
createAndInstallTestInstances();
assertFalse(app1.isPending());
assertFalse(app2.isPending());
assertFalse(app3.isPending());
var pendingEmailCredential =
new firebaseui.auth.PendingEmailCredential('test@gmail.com');
firebaseui.auth.storage.setPendingEmailCredential(pendingEmailCredential);
assertFalse(app1.isPending());
assertFalse(app2.isPending());
assertTrue(app3.isPending());
firebaseui.auth.storage.setPendingEmailCredential(
pendingEmailCredential, 'id1');
assertTrue(app1.isPending());
assertFalse(app2.isPending());
assertTrue(app3.isPending());
firebaseui.auth.storage.setPendingEmailCredential(
pendingEmailCredential, 'id2');
assertTrue(app1.isPending());
assertTrue(app2.isPending());
assertTrue(app3.isPending());
}
function testIsPendingRedirect() {
var currentUrl = 'https://www.example.com';
testStubs.replace(
firebaseui.auth.util,
'getCurrentUrl',
function() {
return currentUrl;
});
// Simulate clearEmailSignInState() will strip URL from oob code query string.
testStubs.replace(
firebaseui.auth.AuthUI.prototype,
'clearEmailSignInState',
goog.testing.recordFunction(function() {
currentUrl = 'https://www.example.com';
}));
createAndInstallTestInstances();
// No pending redirect status by default.
assertFalse(app1.isPendingRedirect());
assertFalse(app2.isPendingRedirect());
assertFalse(app3.isPendingRedirect());
// Set pending redirect status on app3 (default app).
var redirectStatus = new firebaseui.auth.RedirectStatus();
firebaseui.auth.storage.setRedirectStatus(redirectStatus);
// Confirm app3 pending redirect.
assertFalse(app1.isPendingRedirect());
assertFalse(app2.isPendingRedirect());
assertTrue(app3.isPendingRedirect());
// Set pending redirect status on app1.
firebaseui.auth.storage.setRedirectStatus(redirectStatus, 'id1');
// Confirm app1 pending redirect.
assertTrue(app1.isPendingRedirect());
assertFalse(app2.isPendingRedirect());
assertTrue(app3.isPendingRedirect());
// Set pending redirect status on app2.
var redirectStatus2 = new firebaseui.auth.RedirectStatus('TENANT_ID');
firebaseui.auth.storage.setRedirectStatus(redirectStatus2, 'id2');
// Confirm app2 pending redirect.
assertTrue(app1.isPendingRedirect());
assertTrue(app2.isPendingRedirect());
assertTrue(app3.isPendingRedirect());
// Remove pending redirect status for all.
firebaseui.auth.storage.removeRedirectStatus();
firebaseui.auth.storage.removeRedirectStatus('id1');
firebaseui.auth.storage.removeRedirectStatus('id2');
// Confirm no pending redirect status for all.
assertFalse(app1.isPendingRedirect());
assertFalse(app2.isPendingRedirect());
assertFalse(app3.isPendingRedirect());
// Note that currently email link sign-in does not have AuthUI specific
// identifier. This will set pending redirect status for all apps.
currentUrl =
'https://www.example.com/?apiKey=API_KEY&mode=signIn&oobCode=OOB_CODE';
assertTrue(app1.isPendingRedirect());
assertTrue(app2.isPendingRedirect());
assertTrue(app3.isPendingRedirect());
// Reset current URL will remove pending redirect status for all.
currentUrl = 'https://www.example.com';
assertFalse(app1.isPendingRedirect());
assertFalse(app2.isPendingRedirect());
assertFalse(app3.isPendingRedirect());
// Confirm reset calls clearEmailSignInState() and removes pending redirect
// status for all.
currentUrl =
'https://www.example.com/?apiKey=API_KEY&mode=signIn&oobCode=OOB_CODE';
assertEquals(0, app1.clearEmailSignInState.getCallCount());
app1.reset();
// signOut is called on reset().
app1.getAuth().assertSignOut([]);
// clearEmailSignInState() should be called on app1.
assertEquals(1, app1.clearEmailSignInState.getCallCount());
// isPendingRedirect() should now be false for all instances.
assertFalse(app1.isPendingRedirect());
assertFalse(app2.isPendingRedirect());
assertFalse(app3.isPendingRedirect());
}
function testGetSetTenantId() {
createAndInstallTestInstances();
assertNull(app1.getTenantId());
// Pass the tenant ID on external instance initially.
testAuth1.tenantId = 'TENANT_ID1';
app1.start(container1, config4);
assertEquals('TENANT_ID1', app1.getExternalAuth().tenantId);
assertEquals('TENANT_ID1', testAuth1.tenantId);
assertEquals('TENANT_ID1', app1.getTenantId());
// Update the tenant ID after the UI being rendered.
app1.setTenantId('TENANT_ID2');
assertEquals('TENANT_ID2', app1.getTenantId());
assertEquals('TENANT_ID2', app1.getExternalAuth().tenantId);
assertEquals('TENANT_ID2', testAuth1.tenantId);
}
function testClearEmailSignInState() {
var currentUrl = 'https://www.example.com/?' +
'apiKey=API_KEY&mode=signIn&oobCode=OOB_CODE&ui_sid=SESSIONID&lang=en';
createAndInstallTestInstances();
app1.clearEmailSignInState(currentUrl);
// Confirm history state replaced.
testUtil.assertReplaceHistoryState(
{
'state': 'signIn',
'mode': 'emailLink',
'operation': 'clear'
},
// Same document title should be kept.
document.title,
// URL should be cleared from email sign-in related query params.
'https://www.example.com/?lang=en');
}
function testStart() {
createAndInstallTestInstances();
// Test multiple rendering for the widget in different apps.
asyncTestCase.waitForSignals(1);
var resetWarning = 'UI Widget is already rendered on the page and is pend' +
'ing some user interaction. Only one widget instance can be rendered ' +
'per page. The previous instance has been automatically reset.';
testStubs.reset();
// Record log console warnings.
testStubs.set(
firebaseui.auth.log,
'warning',
goog.testing.recordFunction());
// No rendered AuthUI.
assertNull(app1.getAuthUiGetter()());
testStubs.set(
firebaseui.auth.widget.dispatcher,
'dispatchOperation',
goog.testing.recordFunction(
firebaseui.auth.widget.dispatcher.dispatchOperation));
// Assume pending credential set in app1.
// This will be cleared when app2 interrupts and resets app1.
var pendingEmailCredential =
new firebaseui.auth.PendingEmailCredential('test@gmail.com');
firebaseui.auth.storage.setPendingEmailCredential(
pendingEmailCredential, app1.getAppId());
assertNull(app1.getCurrentComponent());
var redirectStatus = new firebaseui.auth.RedirectStatus();
firebaseui.auth.storage.setRedirectStatus(redirectStatus, app1.getAppId());
assertTrue(firebaseui.auth.storage.hasRedirectStatus(app1.getAppId()));
// Start widget for app1, override configuration for that.
app1.start(container1, config4);
app1.getExternalAuth().runAuthChangeHandler();
assertFalse(
firebaseui.auth.storage.hasRedirectStatus(app1.getAppId()));
// Confirm getCurrentComponent returns the expected callback component.
assertTrue(
app1.getCurrentComponent() instanceof firebaseui.auth.ui.page.Callback);
// No automatic reset warning is logged.
assertEquals(0, firebaseui.auth.log.warning.getCallCount());
// Confirm configuration updated to config4.
assertConfigEquals(
config4,
app1.getConfig());
// Current rendered AuthUI should be set correctly.
assertEquals(app1, firebaseui.auth.AuthUI.getAuthUi());
assertEquals(app1, app1.getAuthUiGetter()());
// Dispatch operation should be called.
assertEquals(1,
firebaseui.auth.widget.dispatcher.dispatchOperation.getCallCount());
// app1 instance should be passed.
assertEquals(
app1,
firebaseui.auth.widget.dispatcher.dispatchOperation.getLastCall()
.getArgument(0));
// Container1 should be passed.
assertEquals(
container1,
firebaseui.auth.widget.dispatcher.dispatchOperation.getLastCall()
.getArgument(1));
// Callback page rendered in first app container1.
assertHasCssClass(container1, 'firebaseui-id-page-callback');
firebaseui.auth.storage.setRedirectStatus(redirectStatus, app2.getAppId());
assertTrue(firebaseui.auth.storage.hasRedirectStatus(app2.getAppId()));
// Try to render another widget. This should reset first app widget.
app2.start(container2, config2);
app2.getExternalAuth().runAuthChangeHandler();
assertFalse(
firebaseui.auth.storage.hasRedirectStatus(app2.getAppId()));
app1.getAuth().assertSignOut([]);
// App1 pending creds cleared.
assertFalse(
firebaseui.auth.storage.hasPendingEmailCredential(app1.getAppId()));
// Automatic reset warning is logged since app1 is still pending.
assertEquals(1, firebaseui.auth.log.warning.getCallCount());
/** @suppress {missingRequire} */
assertEquals(
resetWarning,
firebaseui.auth.log.warning.getLastCall().getArgument(0));
// Current rendered AuthUi should be set correctly.
assertEquals(app2, firebaseui.auth.AuthUI.getAuthUi());
assertEquals(app2, app1.getAuthUiGetter()());
// Dispatch operation should be called.
/** @suppress {missingRequire} */
assertEquals(2,
firebaseui.auth.widget.dispatcher.dispatchOperation.getCallCount());
// app2 instance should be passed.
assertEquals(
app2,
firebaseui.auth.widget.dispatcher.dispatchOperation.getLastCall()
.getArgument(0));
// Container2 should be passed.
/** @suppress {missingRequire} */
assertEquals(
container2,
firebaseui.auth.widget.dispatcher.dispatchOperation.getLastCall()
.getArgument(1));
// First widget container should be reset.
assertEquals(0, container1.children.length);
// Callback rendered on second app.
assertHasCssClass(container2, 'firebaseui-id-page-callback');
// For a specific AuthUI, only the first getRedirectResult will be obtained
// from Auth instance. The next requests will use an empty promise to force
// provider sign-in screen to show for widget re-rendering.
app2.getAuth().assertGetRedirectResult(
[],
{
'user': null,
'credential': null
});
app2.getAuth().process().then(function() {
// Provider sign-in rendered at this stage.
assertHasCssClass(container2, 'firebaseui-id-page-provider-sign-in');
// Confirm getCurrentComponent returns the expected ProviderSignIn
// component.
assertTrue(
app2.getCurrentComponent() instanceof
firebaseui.auth.ui.page.ProviderSignIn);
// Try rendering again same app widget. This should not call auth
// getRedirectResult anymore since if there is a pending redirect, it will
// process it and not display the widget.
app2.start(container2, config2);
app2.getExternalAuth().runAuthChangeHandler();
app2.getAuth().assertSignOut([]);
// No additional Automatic reset warning is logged.
/** @suppress {missingRequire} */
assertEquals(1, firebaseui.auth.log.warning.getCallCount());
assertHasCssClass(container2, 'firebaseui-id-page-provider-sign-in');
// After reset, currentComponent is set to null.
app2.getAuth().assertSignOut([]);
app2.reset();
// Confirm current component is null after reset.
assertNull(app2.getCurrentComponent());
asyncTestCase.signal();
});
}
function testStart_immediateFederatedRedirect_startRedirect() {
// Verify when immediateFederatedRedirect is enabled, redirect status is set
// correctly before redirecting to IdPs.
createAndInstallTestInstances();
testStubs.reset();
asyncTestCase.waitForSignals(1);
assertFalse(firebaseui.auth.storage.hasRedirectStatus(app1.getAppId()));
// Enable immediateFederatedRedirect and start sign-in.
app1.start(container1, {
'immediateFederatedRedirect': true,
'signInOptions': [{
'provider': 'google.com',
}],
'signInFlow':'redirect'
});
app1.getExternalAuth().runAuthChangeHandler();
app1.getAuth().assertSignInWithRedirect([expectedProvider]);
app1.getExternalAuth().process().then(() => {
return app1.getAuth().process();
}).then(() => {
// Federated redirect page should be rendered.
assertHasCssClass(container1, 'firebaseui-id-page-blank');
// Redirect status should be set correctly.
assertTrue(firebaseui.auth.storage.hasRedirectStatus(app1.getAppId()));
asyncTestCase.signal();
});
}
function testStart_immediateFederatedRedirect_finishRedirect() {
// Verify when immediateFederatedRedirect is enabled, redirect status is
// cleared after sign-in is completed.
createAndInstallTestInstances();
testStubs.reset();
asyncTestCase.waitForSignals(1);
// Mock widget coming back from IdP page where the redirect status is set.
const redirectStatus = new firebaseui.auth.RedirectStatus();
firebaseui.auth.storage.setRedirectStatus(redirectStatus, app1.getAppId());
assertTrue(firebaseui.auth.storage.hasRedirectStatus(app1.getAppId()));
// Enable immediateFederatedRedirect and start sign-in.
app1.start(container1, {
'immediateFederatedRedirect': true,
'signInOptions': [{
'provider': 'google.com',
}],
'signInFlow':'redirect'
});
app1.getExternalAuth().runAuthChangeHandler();
app1.getAuth().assertGetRedirectResult(
[],
function() {
app1.getAuth().setUser(expectedUser);
return expectedUserCredential;
});
app1.getExternalAuth().process().then(() => {
return app1.getAuth().process();
}).then(() => {
// Callback page should be rendered to handle redirecting back.
assertHasCssClass(container1, 'firebaseui-id-page-callback');
// Redirect status should be cleared after sign-in is finished.
assertFalse(firebaseui.auth.storage.hasRedirectStatus(app1.getAppId()));
app1.getAuth().assertSignOut([]);
asyncTestCase.signal();
});
}
function testSetLang() {
testStubs.replace(goog, 'LOCALE', 'de');
// Language code of auth instance is set to goog.LOCALE at initialization.
// Replace goog.LOCALE and then install instance.
createAndInstallTestInstances();
app1.start(container1, config1);
app1.getExternalAuth().runAuthChangeHandler();
assertEquals('de', container1.getAttribute('lang'));
assertEquals('de', app1.getAuth().languageCode);
assertEquals('de', app1.getExternalAuth().languageCode);
app1.getAuth().assertSignOut([]);
app1.reset();
assertFalse(container1.hasAttribute('lang'));
}
function testSetLang_codeWithdash() {
testStubs.replace(goog, 'LOCALE', 'zh-CN');
// Language code of auth instance is set to goog.LOCALE at initialization.
// Replace goog.LOCALE and then install instance.
createAndInstallTestInstances();
app1.start(container1, config1);
app1.getExternalAuth().runAuthChangeHandler();
assertEquals('zh-CN', container1.getAttribute('lang'));
assertEquals('zh-CN', app1.getAuth().languageCode);
assertEquals('zh-CN', app1.getExternalAuth().languageCode);
app1.getAuth().assertSignOut([]);
app1.reset();
assertFalse(container1.hasAttribute('lang'));
}
function testSetLang_codeWithUnderscore() {
testStubs.replace(goog, 'LOCALE', 'zh_CN');
// Language code of auth instance is set to goog.LOCALE at initialization.
// Replace goog.LOCALE and then install instance.
createAndInstallTestInstances();
app1.start(container1, config1);