-
Notifications
You must be signed in to change notification settings - Fork 385
/
Copy pathauth.spec.ts
3317 lines (3081 loc) · 123 KB
/
auth.spec.ts
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 2018 Google 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.
*/
import * as url from 'url';
import * as crypto from 'crypto';
import * as bcrypt from 'bcrypt';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import firebase from '@firebase/app-compat';
import '@firebase/auth-compat';
import { clone } from 'lodash';
import { User, FirebaseAuth } from '@firebase/auth-types';
import {
generateRandomString, projectId, apiKey, noServiceAccountApp, cmdArgs,
} from './setup';
import * as mocks from '../resources/mocks';
import { deepExtend, deepCopy } from '../../src/utils/deep-copy';
import {
AuthProviderConfig, CreateTenantRequest, DeleteUsersResult, PhoneMultiFactorInfo,
TenantAwareAuth, UpdatePhoneMultiFactorInfoRequest, UpdateTenantRequest, UserImportOptions,
UserImportRecord, UserRecord, getAuth, UpdateProjectConfigRequest, UserMetadata, MultiFactorConfig,
PasswordPolicyConfig, SmsRegionConfig,
} from '../../lib/auth/index';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';
const chalk = require('chalk'); // eslint-disable-line @typescript-eslint/no-var-requires
chai.should();
chai.use(sinonChai);
chai.use(chaiAsPromised);
const expect = chai.expect;
const authEmulatorHost = process.env.FIREBASE_AUTH_EMULATOR_HOST;
const newUserUid = generateRandomString(20);
const nonexistentUid = generateRandomString(20);
const newMultiFactorUserUid = generateRandomString(20);
const sessionCookieUids = [
generateRandomString(20),
generateRandomString(20),
generateRandomString(20),
generateRandomString(20),
];
const testPhoneNumber = '+11234567890';
const testPhoneNumber2 = '+16505550101';
const nonexistentPhoneNumber = '+18888888888';
const updatedEmail = generateRandomString(20).toLowerCase() + '@example.com';
const updatedPhone = '+16505550102';
const customClaims: { [key: string]: any } = {
admin: true,
groupId: '1234',
};
const uids = [newUserUid + '-1', newUserUid + '-2', newUserUid + '-3'];
const mockUserData = {
email: newUserUid.toLowerCase() + '@example.com',
emailVerified: false,
phoneNumber: testPhoneNumber,
password: 'password',
displayName: 'Random User ' + newUserUid,
photoURL: 'http://www.example.com/' + newUserUid + '/photo.png',
disabled: false,
};
const actionCodeSettings = {
url: 'http://localhost/?a=1&b=2#c=3',
handleCodeInApp: false,
};
let deleteQueue = Promise.resolve();
interface UserImportTest {
name: string;
importOptions: UserImportOptions;
rawPassword: string;
rawSalt?: string;
computePasswordHash(userImportTest: UserImportTest): Buffer;
}
/** @return Random generated SAML provider ID. */
function randomSamlProviderId(): string {
return 'saml.' + generateRandomString(10, false).toLowerCase();
}
/** @return Random generated OIDC provider ID. */
function randomOidcProviderId(): string {
return 'oidc.' + generateRandomString(10, false).toLowerCase();
}
function clientAuth(): FirebaseAuth {
expect(firebase.auth).to.be.ok;
return firebase.auth!();
}
describe('admin.auth', () => {
let uidFromCreateUserWithoutUid: string;
const processWarningSpy = sinon.spy();
before(() => {
firebase.initializeApp({
apiKey,
authDomain: projectId + '.firebaseapp.com',
});
if (authEmulatorHost) {
(clientAuth() as any).useEmulator('http://' + authEmulatorHost);
}
process.on('warning', processWarningSpy);
return cleanup();
});
afterEach(() => {
expect(
processWarningSpy.neverCalledWith(
sinon.match(
(warning: Error) => warning.name === 'MaxListenersExceededWarning'
)
),
'process.on("warning") was called with an unexpected MaxListenersExceededWarning.'
).to.be.true;
processWarningSpy.resetHistory();
});
after(() => {
process.removeListener('warning', processWarningSpy);
return cleanup();
});
it('createUser() creates a new user when called without a UID', () => {
const newUserData = clone(mockUserData);
newUserData.email = generateRandomString(20).toLowerCase() + '@example.com';
newUserData.phoneNumber = testPhoneNumber2;
return getAuth().createUser(newUserData)
.then((userRecord) => {
uidFromCreateUserWithoutUid = userRecord.uid;
expect(typeof userRecord.uid).to.equal('string');
// Confirm expected email.
expect(userRecord.email).to.equal(newUserData.email);
// Confirm expected phone number.
expect(userRecord.phoneNumber).to.equal(newUserData.phoneNumber);
});
});
it('createUser() creates a new user with the specified UID', () => {
const newUserData: any = clone(mockUserData);
newUserData.uid = newUserUid;
return getAuth().createUser(newUserData)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
// Confirm expected email.
expect(userRecord.email).to.equal(newUserData.email);
// Confirm expected phone number.
expect(userRecord.phoneNumber).to.equal(newUserData.phoneNumber);
});
});
it('createUser() creates a new user with enrolled second factors', function () {
if (authEmulatorHost) {
return this.skip(); // Not yet supported in Auth Emulator.
}
const enrolledFactors = [
{
phoneNumber: '+16505550001',
displayName: 'Work phone number',
factorId: 'phone',
},
{
phoneNumber: '+16505550002',
displayName: 'Personal phone number',
factorId: 'phone',
},
];
const newUserData: any = {
uid: newMultiFactorUserUid,
email: generateRandomString(20).toLowerCase() + '@example.com',
emailVerified: true,
password: 'password',
multiFactor: {
enrolledFactors,
},
};
return getAuth().createUser(newUserData)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newMultiFactorUserUid);
// Confirm expected email.
expect(userRecord.email).to.equal(newUserData.email);
// Confirm second factors added to user.
expect(userRecord.multiFactor!.enrolledFactors.length).to.equal(2);
// Confirm first enrolled second factor.
const firstMultiFactor = userRecord.multiFactor!.enrolledFactors[0];
expect(firstMultiFactor.uid).not.to.be.undefined;
expect(firstMultiFactor.enrollmentTime).not.to.be.undefined;
expect((firstMultiFactor as PhoneMultiFactorInfo).phoneNumber).to.equal(
enrolledFactors[0].phoneNumber);
expect(firstMultiFactor.displayName).to.equal(enrolledFactors[0].displayName);
expect(firstMultiFactor.factorId).to.equal(enrolledFactors[0].factorId);
// Confirm second enrolled second factor.
const secondMultiFactor = userRecord.multiFactor!.enrolledFactors[1];
expect(secondMultiFactor.uid).not.to.be.undefined;
expect(secondMultiFactor.enrollmentTime).not.to.be.undefined;
expect((secondMultiFactor as PhoneMultiFactorInfo).phoneNumber).to.equal(
enrolledFactors[1].phoneNumber);
expect(secondMultiFactor.displayName).to.equal(enrolledFactors[1].displayName);
expect(secondMultiFactor.factorId).to.equal(enrolledFactors[1].factorId);
});
});
it('createUser() fails when the UID is already in use', () => {
const newUserData: any = clone(mockUserData);
newUserData.uid = newUserUid;
return getAuth().createUser(newUserData)
.should.eventually.be.rejected.and.have.property('code', 'auth/uid-already-exists');
});
it('getUser() returns a user record with the matching UID', () => {
return getAuth().getUser(newUserUid)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByEmail() returns a user record with the matching email', () => {
return getAuth().getUserByEmail(mockUserData.email)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByPhoneNumber() returns a user record with the matching phone number', () => {
return getAuth().getUserByPhoneNumber(mockUserData.phoneNumber)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByProviderUid() returns a user record with the matching provider id', async () => {
// TODO(rsgowman): Once we can link a provider id with a user, just do that
// here instead of creating a new user.
const randomUid = 'import_' + generateRandomString(20).toLowerCase();
const importUser: UserImportRecord = {
uid: randomUid,
email: '[email protected]',
phoneNumber: '+15555550000',
emailVerified: true,
disabled: false,
metadata: {
lastSignInTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
creationTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
},
providerData: [{
displayName: 'User Name',
email: '[email protected]',
phoneNumber: '+15555550000',
photoURL: 'http://example.com/user',
providerId: 'google.com',
uid: 'google_uid',
}],
};
await getAuth().importUsers([importUser]);
try {
await getAuth().getUserByProviderUid('google.com', 'google_uid')
.then((userRecord) => {
expect(userRecord.uid).to.equal(importUser.uid);
});
} finally {
await safeDelete(importUser.uid);
}
});
it('getUserByProviderUid() redirects to getUserByEmail if given an email', () => {
return getAuth().getUserByProviderUid('email', mockUserData.email)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByProviderUid() redirects to getUserByPhoneNumber if given a phone number', () => {
return getAuth().getUserByProviderUid('phone', mockUserData.phoneNumber)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByProviderUid() returns a user record with the matching provider id', async () => {
// TODO(rsgowman): Once we can link a provider id with a user, just do that
// here instead of creating a new user.
const randomUid = 'import_' + generateRandomString(20).toLowerCase();
const importUser: UserImportRecord = {
uid: randomUid,
email: '[email protected]',
phoneNumber: '+15555550000',
emailVerified: true,
disabled: false,
metadata: {
lastSignInTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
creationTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
},
providerData: [{
displayName: 'User Name',
email: '[email protected]',
phoneNumber: '+15555550000',
photoURL: 'http://example.com/user',
providerId: 'google.com',
uid: 'google_uid',
}],
};
await getAuth().importUsers([importUser]);
try {
await getAuth().getUserByProviderUid('google.com', 'google_uid')
.then((userRecord) => {
expect(userRecord.uid).to.equal(importUser.uid);
});
} finally {
await safeDelete(importUser.uid);
}
});
it('getUserByProviderUid() redirects to getUserByEmail if given an email', () => {
return getAuth().getUserByProviderUid('email', mockUserData.email)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByProviderUid() redirects to getUserByPhoneNumber if given a phone number', () => {
return getAuth().getUserByProviderUid('phone', mockUserData.phoneNumber)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByProviderUid() returns a user record with the matching provider id', async () => {
// TODO(rsgowman): Once we can link a provider id with a user, just do that
// here instead of creating a new user.
const randomUid = 'import_' + generateRandomString(20).toLowerCase();
const importUser: UserImportRecord = {
uid: randomUid,
email: '[email protected]',
phoneNumber: '+15555550000',
emailVerified: true,
disabled: false,
metadata: {
lastSignInTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
creationTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
},
providerData: [{
displayName: 'User Name',
email: '[email protected]',
phoneNumber: '+15555550000',
photoURL: 'http://example.com/user',
providerId: 'google.com',
uid: 'google_uid',
}],
};
await getAuth().importUsers([importUser]);
try {
await getAuth().getUserByProviderUid('google.com', 'google_uid')
.then((userRecord) => {
expect(userRecord.uid).to.equal(importUser.uid);
});
} finally {
await safeDelete(importUser.uid);
}
});
it('getUserByProviderUid() redirects to getUserByEmail if given an email', () => {
return getAuth().getUserByProviderUid('email', mockUserData.email)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByProviderUid() redirects to getUserByPhoneNumber if given a phone number', () => {
return getAuth().getUserByProviderUid('phone', mockUserData.phoneNumber)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByProviderUid() returns a user record with the matching provider id', async () => {
// TODO(rsgowman): Once we can link a provider id with a user, just do that
// here instead of creating a new user.
const randomUid = 'import_' + generateRandomString(20).toLowerCase();
const importUser: UserImportRecord = {
uid: randomUid,
email: '[email protected]',
phoneNumber: '+15555550000',
emailVerified: true,
disabled: false,
metadata: {
lastSignInTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
creationTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
},
providerData: [{
displayName: 'User Name',
email: '[email protected]',
phoneNumber: '+15555550000',
photoURL: 'http://example.com/user',
providerId: 'google.com',
uid: 'google_uid',
}],
};
await getAuth().importUsers([importUser]);
try {
await getAuth().getUserByProviderUid('google.com', 'google_uid')
.then((userRecord) => {
expect(userRecord.uid).to.equal(importUser.uid);
});
} finally {
await safeDelete(importUser.uid);
}
});
it('getUserByProviderUid() redirects to getUserByEmail if given an email', () => {
return getAuth().getUserByProviderUid('email', mockUserData.email)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByProviderUid() redirects to getUserByPhoneNumber if given a phone number', () => {
return getAuth().getUserByProviderUid('phone', mockUserData.phoneNumber)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
describe('getUsers()', () => {
/**
* Filters a list of object to another list of objects that only contains
* the uid, email, and phoneNumber fields. Works with at least UserRecord
* and UserImportRecord instances.
*/
function mapUserRecordsToUidEmailPhones(
values: Array<{ uid: string; email?: string; phoneNumber?: string }>
): Array<{ uid: string; email?: string; phoneNumber?: string }> {
return values.map((ur) => ({ uid: ur.uid, email: ur.email, phoneNumber: ur.phoneNumber }));
}
const testUser1 = { uid: 'uid1', email: '[email protected]', phoneNumber: '+15555550001' };
const testUser2 = { uid: 'uid2', email: '[email protected]', phoneNumber: '+15555550002' };
const testUser3 = { uid: 'uid3', email: '[email protected]', phoneNumber: '+15555550003' };
const usersToCreate = [testUser1, testUser2, testUser3];
// Also create a user with a provider config. (You can't create a user with
// a provider config. But you *can* import one.)
const importUser1: UserImportRecord = {
uid: 'uid4',
email: '[email protected]',
phoneNumber: '+15555550004',
emailVerified: true,
disabled: false,
metadata: {
lastSignInTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
creationTime: 'Thu, 01 Jan 1970 00:00:00 UTC',
},
providerData: [{
displayName: 'User Four',
email: '[email protected]',
phoneNumber: '+15555550004',
photoURL: 'http://example.com/user4',
providerId: 'google.com',
uid: 'google_uid4',
}],
};
const testUser4 = mapUserRecordsToUidEmailPhones([importUser1])[0];
before(async () => {
// Delete all the users that we're about to create (in case they were
// left over from a prior run).
const uidsToDelete = usersToCreate.map((user) => user.uid);
uidsToDelete.push(importUser1.uid);
await deleteUsersWithDelay(uidsToDelete);
// Create/import users required by these tests
await Promise.all(usersToCreate.map((user) => getAuth().createUser(user)));
await getAuth().importUsers([importUser1]);
});
after(async () => {
const uidsToDelete = usersToCreate.map((user) => user.uid);
uidsToDelete.push(importUser1.uid);
await deleteUsersWithDelay(uidsToDelete);
});
it('returns users by various identifier types in a single call', async () => {
const users = await getAuth().getUsers([
{ uid: 'uid1' },
{ email: '[email protected]' },
{ phoneNumber: '+15555550003' },
{ providerId: 'google.com', providerUid: 'google_uid4' },
])
.then((getUsersResult) => getUsersResult.users)
.then(mapUserRecordsToUidEmailPhones);
expect(users).to.have.deep.members([testUser1, testUser2, testUser3, testUser4]);
});
it('returns found users and ignores non-existing users', async () => {
const users = await getAuth().getUsers([
{ uid: 'uid1' },
{ uid: 'uid_that_doesnt_exist' },
{ uid: 'uid3' },
]);
expect(users.notFound).to.have.deep.members([{ uid: 'uid_that_doesnt_exist' }]);
const foundUsers = mapUserRecordsToUidEmailPhones(users.users);
expect(foundUsers).to.have.deep.members([testUser1, testUser3]);
});
it('returns nothing when queried for only non-existing users', async () => {
const notFoundIds = [{ uid: 'non-existing user' }];
const users = await getAuth().getUsers(notFoundIds);
expect(users.users).to.be.empty;
expect(users.notFound).to.deep.equal(notFoundIds);
});
it('de-dups duplicate users', async () => {
const users = await getAuth().getUsers([
{ uid: 'uid1' },
{ uid: 'uid1' },
])
.then((getUsersResult) => getUsersResult.users)
.then(mapUserRecordsToUidEmailPhones);
expect(users).to.deep.equal([testUser1]);
});
it('returns users with a lastRefreshTime', async () => {
const isUTCString = (s: string): boolean => {
return new Date(s).toUTCString() === s;
};
const newUserRecord = await getAuth().createUser({
uid: 'lastRefreshTimeUser',
email: '[email protected]',
password: 'p4ssword',
});
try {
// New users should not have a lastRefreshTime set.
expect(newUserRecord.metadata.lastRefreshTime).to.be.null;
// Login to set the lastRefreshTime.
await firebase.auth!().signInWithEmailAndPassword('[email protected]', 'p4ssword')
.then(async () => {
// Attempt to retrieve the user 3 times (with a small delay between
// each attempt). Occassionally, this call retrieves the user data
// without the lastLoginTime/lastRefreshTime set; possibly because
// it's hitting a different server than the login request uses.
let userRecord: UserRecord | null = null;
for (let i = 0; i < 3; i++) {
userRecord = await getAuth().getUser('lastRefreshTimeUser');
if (userRecord!['metadata']['lastRefreshTime']) {
break;
}
await new Promise((resolve) => {
setTimeout(resolve, 1000 * Math.pow(2, i));
});
}
const metadata = userRecord!['metadata'];
expect(metadata['lastRefreshTime']).to.exist;
expect(isUTCString(metadata['lastRefreshTime']!)).to.be.true;
const creationTime = new Date(metadata['creationTime']).getTime();
const lastRefreshTime = new Date(metadata['lastRefreshTime']!).getTime();
expect(creationTime).lte(lastRefreshTime);
expect(lastRefreshTime).lte(creationTime + 3600 * 1000);
});
} finally {
getAuth().deleteUser('lastRefreshTimeUser');
}
});
});
it('listUsers() returns up to the specified number of users', () => {
const promises: Array<Promise<UserRecord>> = [];
uids.forEach((uid) => {
const tempUserData = {
uid,
password: 'password',
};
promises.push(getAuth().createUser(tempUserData));
});
return Promise.all(promises)
.then(() => {
// Return 2 users with the provided page token.
// This test will fail if other users are created in between.
return getAuth().listUsers(2, uids[0]);
})
.then((listUsersResult) => {
// Confirm expected number of users.
expect(listUsersResult.users.length).to.equal(2);
// Confirm next page token present.
expect(typeof listUsersResult.pageToken).to.equal('string');
// Confirm each user's uid and the hashed passwords.
expect(listUsersResult.users[0].uid).to.equal(uids[1]);
expect(
listUsersResult.users[0].passwordHash,
'Missing passwordHash field. A common cause would be forgetting to '
+ 'add the "Firebase Authentication Admin" permission. See '
+ 'instructions in CONTRIBUTING.md',
).to.be.ok;
expect(listUsersResult.users[0].passwordHash!.length).greaterThan(0);
expect(
listUsersResult.users[0].passwordSalt,
'Missing passwordSalt field. A common cause would be forgetting to '
+ 'add the "Firebase Authentication Admin" permission. See '
+ 'instructions in CONTRIBUTING.md',
).to.be.ok;
expect(listUsersResult.users[0].passwordSalt!.length).greaterThan(0);
expect(listUsersResult.users[1].uid).to.equal(uids[2]);
expect(listUsersResult.users[1].passwordHash!.length).greaterThan(0);
expect(listUsersResult.users[1].passwordSalt!.length).greaterThan(0);
});
});
it('revokeRefreshTokens() invalidates existing sessions and ID tokens', async () => {
let currentIdToken: string;
let currentUser: User;
// Sign in with an email and password account.
return clientAuth().signInWithEmailAndPassword(mockUserData.email, mockUserData.password)
.then(({ user }) => {
expect(user).to.exist;
currentUser = user!;
// Get user's ID token.
return user!.getIdToken();
})
.then((idToken) => {
currentIdToken = idToken;
// Verify that user's ID token while checking for revocation.
return getAuth().verifyIdToken(currentIdToken, true);
})
.then((decodedIdToken) => {
// Verification should succeed. Revoke that user's session.
return new Promise((resolve) => setTimeout(() => resolve(
getAuth().revokeRefreshTokens(decodedIdToken.sub),
), 1000));
})
.then(() => {
const verifyingIdToken = getAuth().verifyIdToken(currentIdToken)
if (authEmulatorHost) {
// Check revocation is forced in emulator-mode and this should throw.
return verifyingIdToken.should.eventually.be.rejected;
} else {
// verifyIdToken without checking revocation should still succeed.
return verifyingIdToken.should.eventually.be.fulfilled;
}
})
.then(() => {
// verifyIdToken while checking for revocation should fail.
return getAuth().verifyIdToken(currentIdToken, true)
.should.eventually.be.rejected.and.have.property('code', 'auth/id-token-revoked');
})
.then(() => {
// Confirm token revoked on client.
return currentUser.reload()
.should.eventually.be.rejected.and.have.property('code', 'auth/user-token-expired');
})
.then(() => {
// New sign-in should succeed.
return clientAuth().signInWithEmailAndPassword(
mockUserData.email, mockUserData.password);
})
.then(({ user }) => {
// Get new session's ID token.
expect(user).to.exist;
return user!.getIdToken();
})
.then((idToken) => {
// ID token for new session should be valid even with revocation check.
return getAuth().verifyIdToken(idToken, true)
.should.eventually.be.fulfilled;
});
});
it('setCustomUserClaims() sets claims that are accessible via user\'s ID token', () => {
// Set custom claims on the user.
return getAuth().setCustomUserClaims(newUserUid, customClaims)
.then(() => {
return getAuth().getUser(newUserUid);
})
.then((userRecord) => {
// Confirm custom claims set on the UserRecord.
expect(userRecord.customClaims).to.deep.equal(customClaims);
expect(userRecord.email).to.exist;
return clientAuth().signInWithEmailAndPassword(
userRecord.email!, mockUserData.password);
})
.then(({ user }) => {
// Get the user's ID token.
expect(user).to.exist;
return user!.getIdToken();
})
.then((idToken) => {
// Verify ID token contents.
return getAuth().verifyIdToken(idToken);
})
.then((decodedIdToken: { [key: string]: any }) => {
// Confirm expected claims set on the user's ID token.
for (const key in customClaims) {
if (Object.prototype.hasOwnProperty.call(customClaims, key)) {
expect(decodedIdToken[key]).to.equal(customClaims[key]);
}
}
// Test clearing of custom claims.
return getAuth().setCustomUserClaims(newUserUid, null);
})
.then(() => {
return getAuth().getUser(newUserUid);
})
.then((userRecord) => {
// Custom claims should be cleared.
expect(userRecord.customClaims).to.deep.equal({});
// Force token refresh. All claims should be cleared.
expect(clientAuth().currentUser).to.exist;
return clientAuth().currentUser!.getIdToken(true);
})
.then((idToken) => {
// Verify ID token contents.
return getAuth().verifyIdToken(idToken);
})
.then((decodedIdToken: { [key: string]: any }) => {
// Confirm all custom claims are cleared.
for (const key in customClaims) {
if (Object.prototype.hasOwnProperty.call(customClaims, key)) {
expect(decodedIdToken[key]).to.be.undefined;
}
}
});
});
describe('updateUser()', () => {
/**
* Creates a new user for testing purposes. The user's uid will be
* '$name_$tenRandomChars' and email will be
* '[email protected]'.
*/
// TODO(rsgowman): This function could usefully be employed throughout this file.
function createTestUser(name: string): Promise<UserRecord> {
const tenRandomChars = generateRandomString(10);
return getAuth().createUser({
uid: name + '_' + tenRandomChars,
displayName: name,
email: name + '_' + tenRandomChars + '@example.com',
});
}
let updateUser: UserRecord;
before(async () => {
updateUser = await createTestUser('UpdateUser');
});
after(() => {
return safeDelete(updateUser.uid);
});
it('updates the user record with the given parameters', () => {
const updatedDisplayName = 'Updated User ' + updateUser.uid;
return getAuth().updateUser(updateUser.uid, {
email: updatedEmail,
phoneNumber: updatedPhone,
emailVerified: true,
displayName: updatedDisplayName,
})
.then((userRecord) => {
expect(userRecord.emailVerified).to.be.true;
expect(userRecord.displayName).to.equal(updatedDisplayName);
// Confirm expected email.
expect(userRecord.email).to.equal(updatedEmail);
// Confirm expected phone number.
expect(userRecord.phoneNumber).to.equal(updatedPhone);
});
});
it('sets claims that are accessible via user\'s ID token', () => {
// Set custom claims on the user.
return getAuth().updateUser(updateUser.uid, { customUserClaims: customClaims })
.then((userRecord) => {
// Confirm custom claims set on the UserRecord.
expect(userRecord.customClaims).to.deep.equal(customClaims);
expect(userRecord.email).to.exist;
return clientAuth().signInWithEmailAndPassword(
userRecord.email!, mockUserData.password);
})
.then(({ user }) => {
// Get the user's ID token.
expect(user).to.exist;
return user!.getIdToken();
})
.then((idToken) => {
// Verify ID token contents.
return getAuth().verifyIdToken(idToken);
})
.then((decodedIdToken: { [key: string]: any }) => {
// Confirm expected claims set on the user's ID token.
for (const key in customClaims) {
if (Object.prototype.hasOwnProperty.call(customClaims, key)) {
expect(decodedIdToken[key]).to.equal(customClaims[key]);
}
}
// Test clearing of custom claims.
return getAuth().updateUser(newUserUid, { customUserClaims: null });
})
.then((userRecord) => {
// Custom claims should be cleared.
expect(userRecord.customClaims).to.deep.equal({});
// Force token refresh. All claims should be cleared.
expect(clientAuth().currentUser).to.exist;
return clientAuth().currentUser!.getIdToken(true);
})
.then((idToken) => {
// Verify ID token contents.
return getAuth().verifyIdToken(idToken);
})
.then((decodedIdToken: { [key: string]: any }) => {
// Confirm all custom claims are cleared.
for (const key in customClaims) {
if (Object.prototype.hasOwnProperty.call(customClaims, key)) {
expect(decodedIdToken[key]).to.be.undefined;
}
}
});
});
it('creates, updates, and removes second factors', function () {
if (authEmulatorHost) {
return this.skip(); // Not yet supported in Auth Emulator.
}
const now = new Date(1476235905000).toUTCString();
// Update user with enrolled second factors.
const enrolledFactors = [
{
uid: 'mfaUid1',
phoneNumber: '+16505550001',
displayName: 'Work phone number',
factorId: 'phone',
enrollmentTime: now,
},
{
uid: 'mfaUid2',
phoneNumber: '+16505550002',
displayName: 'Personal phone number',
factorId: 'phone',
enrollmentTime: now,
},
];
return getAuth().updateUser(updateUser.uid, {
multiFactor: {
enrolledFactors,
},
})
.then((userRecord) => {
// Confirm second factors added to user.
const actualUserRecord: { [key: string]: any } = userRecord.toJSON();
expect(actualUserRecord.multiFactor.enrolledFactors.length).to.equal(2);
expect(actualUserRecord.multiFactor.enrolledFactors).to.deep.equal(enrolledFactors);
// Update list of second factors.
return getAuth().updateUser(updateUser.uid, {
multiFactor: {
enrolledFactors: [enrolledFactors[0]],
},
});
})
.then((userRecord) => {
expect(userRecord.multiFactor!.enrolledFactors.length).to.equal(1);
const actualUserRecord: { [key: string]: any } = userRecord.toJSON();
expect(actualUserRecord.multiFactor.enrolledFactors[0]).to.deep.equal(enrolledFactors[0]);
// Remove all second factors.
return getAuth().updateUser(updateUser.uid, {
multiFactor: {
enrolledFactors: null,
},
});
})
.then((userRecord) => {
// Confirm all second factors removed.
expect(userRecord.multiFactor).to.be.undefined;
});
});
it('can link/unlink with a federated provider', async function () {
if (authEmulatorHost) {
return this.skip(); // Not yet supported in Auth Emulator.
}
const googleFederatedUid = 'google_uid_' + generateRandomString(10);
let userRecord = await getAuth().updateUser(updateUser.uid, {
providerToLink: {
providerId: 'google.com',
uid: googleFederatedUid,
},
});
let providerUids = userRecord.providerData.map((userInfo) => userInfo.uid);
let providerIds = userRecord.providerData.map((userInfo) => userInfo.providerId);
expect(providerUids).to.deep.include(googleFederatedUid);
expect(providerIds).to.deep.include('google.com');
userRecord = await getAuth().updateUser(updateUser.uid, {
providersToUnlink: ['google.com'],
});
providerUids = userRecord.providerData.map((userInfo) => userInfo.uid);
providerIds = userRecord.providerData.map((userInfo) => userInfo.providerId);
expect(providerUids).to.not.deep.include(googleFederatedUid);
expect(providerIds).to.not.deep.include('google.com');
});
it('can unlink multiple providers at once, incl a non-federated provider', async function () {
if (authEmulatorHost) {
return this.skip(); // Not yet supported in Auth Emulator.
}
await deletePhoneNumberUser('+15555550001');
const googleFederatedUid = 'google_uid_' + generateRandomString(10);
const facebookFederatedUid = 'facebook_uid_' + generateRandomString(10);
let userRecord = await getAuth().updateUser(updateUser.uid, {
phoneNumber: '+15555550001',
providerToLink: {
providerId: 'google.com',
uid: googleFederatedUid,
},
});
userRecord = await getAuth().updateUser(updateUser.uid, {
providerToLink: {
providerId: 'facebook.com',
uid: facebookFederatedUid,
},
});
let providerUids = userRecord.providerData.map((userInfo) => userInfo.uid);
let providerIds = userRecord.providerData.map((userInfo) => userInfo.providerId);
expect(providerUids).to.deep.include.members([googleFederatedUid, facebookFederatedUid, '+15555550001']);
expect(providerIds).to.deep.include.members(['google.com', 'facebook.com', 'phone']);
userRecord = await getAuth().updateUser(updateUser.uid, {
providersToUnlink: ['google.com', 'facebook.com', 'phone'],
});
providerUids = userRecord.providerData.map((userInfo) => userInfo.uid);
providerIds = userRecord.providerData.map((userInfo) => userInfo.providerId);
expect(providerUids).to.not.deep.include.members([googleFederatedUid, facebookFederatedUid, '+15555550001']);
expect(providerIds).to.not.deep.include.members(['google.com', 'facebook.com', 'phone']);
});
it('noops successfully when given an empty providersToUnlink list', async () => {
const userRecord = await createTestUser('NoopWithEmptyProvidersToDeleteUser');
try {
const updatedUserRecord = await getAuth().updateUser(userRecord.uid, {
providersToUnlink: [],
});
expect(updatedUserRecord).to.deep.equal(userRecord);
} finally {
safeDelete(userRecord.uid);
}
});
it('A user with user record disabled is unable to sign in', async () => {
const password = 'password';
const email = '[email protected]';
return getAuth().updateUser(updateUser.uid, { disabled: true, password, email })
.then(() => {
return clientAuth().signInWithEmailAndPassword(email, password);
})
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
expect(error).to.have.property('code', 'auth/user-disabled');
});
});