-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathuser-record.ts
More file actions
683 lines (609 loc) · 20.2 KB
/
user-record.ts
File metadata and controls
683 lines (609 loc) · 20.2 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
/*!
* @license
* Copyright 2017 Google LLC
*
* 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 { deepCopy } from '../utils/deep-copy';
import { isNonNullObject } from '../utils/validator';
import * as utils from '../utils';
import { AuthClientErrorCode, FirebaseAuthError } from '../utils/error';
/**
* 'REDACTED', encoded as a base64 string.
*/
const B64_REDACTED = Buffer.from('REDACTED').toString('base64');
/**
* Parses a time stamp string or number and returns the corresponding date if valid.
*
* @param time - The unix timestamp string or number in milliseconds.
* @returns The corresponding date as a UTC string, if valid. Otherwise, null.
*/
function parseDate(time: any): string | null {
try {
const date = new Date(parseInt(time, 10));
if (!isNaN(date.getTime())) {
return date.toUTCString();
}
} catch (e) {
// Do nothing. null will be returned.
}
return null;
}
export interface MultiFactorInfoResponse {
mfaEnrollmentId: string;
displayName?: string;
phoneInfo?: string;
totpInfo?: TotpInfoResponse;
enrolledAt?: string;
[key: string]: unknown;
}
export interface TotpInfoResponse {
[key: string]: unknown;
}
export interface ProviderUserInfoResponse {
rawId: string;
displayName?: string;
email?: string;
photoUrl?: string;
phoneNumber?: string;
providerId: string;
federatedId?: string;
}
export interface GetAccountInfoUserResponse {
localId: string;
email?: string;
emailVerified?: boolean;
phoneNumber?: string;
displayName?: string;
photoUrl?: string;
disabled?: boolean;
passwordHash?: string;
salt?: string;
customAttributes?: string;
validSince?: string;
tenantId?: string;
providerUserInfo?: ProviderUserInfoResponse[];
mfaInfo?: MultiFactorInfoResponse[];
createdAt?: string;
lastLoginAt?: string;
lastRefreshAt?: string;
passwordUpdatedAt?: number | string;
[key: string]: any;
}
enum MultiFactorId {
Phone = 'phone',
Totp = 'totp',
}
/**
* Interface representing the common properties of a user-enrolled second factor.
*/
export abstract class MultiFactorInfo {
/**
* The ID of the enrolled second factor. This ID is unique to the user.
*/
public readonly uid: string;
/**
* The optional display name of the enrolled second factor.
*/
public readonly displayName?: string;
/**
* The type identifier of the second factor.
* For SMS second factors, this is `phone`.
* For TOTP second factors, this is `totp`.
*/
public readonly factorId: string;
/**
* The optional date the second factor was enrolled, formatted as a UTC string.
*/
public readonly enrollmentTime?: string;
/**
* Initializes the MultiFactorInfo associated subclass using the server side.
* If no MultiFactorInfo is associated with the response, null is returned.
*
* @param response - The server side response.
* @internal
*/
public static initMultiFactorInfo(response: MultiFactorInfoResponse): MultiFactorInfo | null {
let multiFactorInfo: MultiFactorInfo | null = null;
// PhoneMultiFactorInfo, TotpMultiFactorInfo currently available.
try {
if (response.phoneInfo !== undefined) {
multiFactorInfo = new PhoneMultiFactorInfo(response);
} else if (response.totpInfo !== undefined) {
multiFactorInfo = new TotpMultiFactorInfo(response);
} else {
// Ignore the other SDK unsupported MFA factors to prevent blocking developers using the current SDK.
}
} catch (e) {
// Ignore error.
}
return multiFactorInfo;
}
/**
* Initializes the MultiFactorInfo object using the server side response.
*
* @param response - The server side response.
* @constructor
* @internal
*/
constructor(response: MultiFactorInfoResponse) {
this.initFromServerResponse(response);
}
/**
* Returns a JSON-serializable representation of this object.
*
* @returns A JSON-serializable representation of this object.
*/
public toJSON(): object {
return {
uid: this.uid,
displayName: this.displayName,
factorId: this.factorId,
enrollmentTime: this.enrollmentTime,
};
}
/**
* Returns the factor ID based on the response provided.
*
* @param response - The server side response.
* @returns The multi-factor ID associated with the provided response. If the response is
* not associated with any known multi-factor ID, null is returned.
*
* @internal
*/
protected abstract getFactorId(response: MultiFactorInfoResponse): string | null;
/**
* Initializes the MultiFactorInfo object using the provided server response.
*
* @param response - The server side response.
*/
private initFromServerResponse(response: MultiFactorInfoResponse): void {
const factorId = response && this.getFactorId(response);
if (!factorId || !response || !response.mfaEnrollmentId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid multi-factor info response');
}
utils.addReadonlyGetter(this, 'uid', response.mfaEnrollmentId);
utils.addReadonlyGetter(this, 'factorId', factorId);
utils.addReadonlyGetter(this, 'displayName', response.displayName);
// Encoded using [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format.
// For example, "2017-01-15T01:30:15.01Z".
// This can be parsed directly via Date constructor.
// This can be computed using Data.prototype.toISOString.
if (response.enrolledAt) {
utils.addReadonlyGetter(
this, 'enrollmentTime', new Date(response.enrolledAt).toUTCString());
} else {
utils.addReadonlyGetter(this, 'enrollmentTime', null);
}
}
}
/**
* Interface representing a phone specific user-enrolled second factor.
*/
export class PhoneMultiFactorInfo extends MultiFactorInfo {
/**
* The phone number associated with a phone second factor.
*/
public readonly phoneNumber: string;
/**
* Initializes the PhoneMultiFactorInfo object using the server side response.
*
* @param response - The server side response.
* @constructor
* @internal
*/
constructor(response: MultiFactorInfoResponse) {
super(response);
utils.addReadonlyGetter(this, 'phoneNumber', response.phoneInfo);
}
/**
* {@inheritdoc MultiFactorInfo.toJSON}
*/
public toJSON(): object {
return Object.assign(
super.toJSON(),
{
phoneNumber: this.phoneNumber,
});
}
/**
* Returns the factor ID based on the response provided.
*
* @param response - The server side response.
* @returns The multi-factor ID associated with the provided response. If the response is
* not associated with any known multi-factor ID, null is returned.
*
* @internal
*/
protected getFactorId(response: MultiFactorInfoResponse): string | null {
return (response && response.phoneInfo) ? MultiFactorId.Phone : null;
}
}
/**
* `TotpInfo` struct associated with a second factor
*/
export class TotpInfo {
}
/**
* Interface representing a TOTP specific user-enrolled second factor.
*/
export class TotpMultiFactorInfo extends MultiFactorInfo {
/**
* `TotpInfo` struct associated with a second factor
*/
public readonly totpInfo: TotpInfo;
/**
* Initializes the `TotpMultiFactorInfo` object using the server side response.
*
* @param response - The server side response.
* @constructor
* @internal
*/
constructor(response: MultiFactorInfoResponse) {
super(response);
utils.addReadonlyGetter(this, 'totpInfo', response.totpInfo);
}
/**
* {@inheritdoc MultiFactorInfo.toJSON}
*/
public toJSON(): object {
return Object.assign(
super.toJSON(),
{
totpInfo: this.totpInfo,
});
}
/**
* Returns the factor ID based on the response provided.
*
* @param response - The server side response.
* @returns The multi-factor ID associated with the provided response. If the response is
* not associated with any known multi-factor ID, `null` is returned.
*
* @internal
*/
protected getFactorId(response: MultiFactorInfoResponse): string | null {
return (response && response.totpInfo) ? MultiFactorId.Totp : null;
}
}
/**
* The multi-factor related user settings.
*/
export class MultiFactorSettings {
/**
* List of second factors enrolled with the current user.
* Currently only phone and TOTP second factors are supported.
*/
public enrolledFactors: MultiFactorInfo[];
/**
* Initializes the `MultiFactor` object using the server side or JWT format response.
*
* @param response - The server side response.
* @constructor
* @internal
*/
constructor(response: GetAccountInfoUserResponse) {
const parsedEnrolledFactors: MultiFactorInfo[] = [];
if (!isNonNullObject(response)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid multi-factor response');
} else if (response.mfaInfo) {
response.mfaInfo.forEach((factorResponse) => {
const multiFactorInfo = MultiFactorInfo.initMultiFactorInfo(factorResponse);
if (multiFactorInfo) {
parsedEnrolledFactors.push(multiFactorInfo);
}
});
}
// Make enrolled factors immutable.
utils.addReadonlyGetter(
this, 'enrolledFactors', Object.freeze(parsedEnrolledFactors));
}
/**
* Returns a JSON-serializable representation of this multi-factor object.
*
* @returns A JSON-serializable representation of this multi-factor object.
*/
public toJSON(): object {
return {
enrolledFactors: this.enrolledFactors.map((info) => info.toJSON()),
};
}
}
/**
* Represents a user's metadata.
*/
export class UserMetadata {
/**
* The date the user was created, formatted as a UTC string.
*/
public readonly creationTime: string;
/**
* The date the user last signed in, formatted as a UTC string.
*/
public readonly lastSignInTime: string;
/**
* The time at which the user was last active (ID token refreshed),
* formatted as a UTC Date string (eg 'Sat, 03 Feb 2001 04:05:06 GMT').
* Returns null if the user was never active.
*/
public readonly lastRefreshTime?: string | null;
/**
* The date the user's password was last updated, formatted as a UTC string.
* Returns null if the user has never updated their password.
*/
public readonly passwordUpdatedAt?: string | null;
/**
* @param response - The server side response returned from the `getAccountInfo`
* endpoint.
* @constructor
* @internal
*/
constructor(response: GetAccountInfoUserResponse) {
// Creation date should always be available but due to some backend bugs there
// were cases in the past where users did not have creation date properly set.
// This included legacy Firebase migrating project users and some anonymous users.
// These bugs have already been addressed since then.
utils.addReadonlyGetter(this, 'creationTime', parseDate(response.createdAt));
utils.addReadonlyGetter(this, 'lastSignInTime', parseDate(response.lastLoginAt));
const lastRefreshAt = response.lastRefreshAt ? new Date(response.lastRefreshAt).toUTCString() : null;
utils.addReadonlyGetter(this, 'lastRefreshTime', lastRefreshAt);
utils.addReadonlyGetter(this, 'passwordUpdatedAt', parseDate(response.passwordUpdatedAt));
}
/**
* Returns a JSON-serializable representation of this object.
*
* @returns A JSON-serializable representation of this object.
*/
public toJSON(): object {
return {
lastSignInTime: this.lastSignInTime,
creationTime: this.creationTime,
lastRefreshTime: this.lastRefreshTime,
passwordUpdatedAt: this.passwordUpdatedAt,
};
}
}
/**
* Represents a user's info from a third-party identity provider
* such as Google or Facebook.
*/
export class UserInfo {
/**
* The user identifier for the linked provider.
*/
public readonly uid: string;
/**
* The display name for the linked provider.
*/
public readonly displayName: string;
/**
* The email for the linked provider.
*/
public readonly email: string;
/**
* The photo URL for the linked provider.
*/
public readonly photoURL: string;
/**
* The linked provider ID (for example, "google.com" for the Google provider).
*/
public readonly providerId: string;
/**
* The phone number for the linked provider.
*/
public readonly phoneNumber: string;
/**
* @param response - The server side response returned from the `getAccountInfo`
* endpoint.
* @constructor
* @internal
*/
constructor(response: ProviderUserInfoResponse) {
// Provider user id and provider id are required.
if (!response.rawId || !response.providerId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid user info response');
}
utils.addReadonlyGetter(this, 'uid', response.rawId);
utils.addReadonlyGetter(this, 'displayName', response.displayName);
utils.addReadonlyGetter(this, 'email', response.email);
utils.addReadonlyGetter(this, 'photoURL', response.photoUrl);
utils.addReadonlyGetter(this, 'providerId', response.providerId);
utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber);
}
/**
* Returns a JSON-serializable representation of this object.
*
* @returns A JSON-serializable representation of this object.
*/
public toJSON(): object {
return {
uid: this.uid,
displayName: this.displayName,
email: this.email,
photoURL: this.photoURL,
providerId: this.providerId,
phoneNumber: this.phoneNumber,
};
}
}
/**
* Represents a user.
*/
export class UserRecord {
/**
* The user's `uid`.
*/
public readonly uid: string;
/**
* The user's primary email, if set.
*/
public readonly email?: string;
/**
* Whether or not the user's primary email is verified.
*/
public readonly emailVerified: boolean;
/**
* The user's display name.
*/
public readonly displayName?: string;
/**
* The user's photo URL.
*/
public readonly photoURL?: string;
/**
* The user's primary phone number, if set.
*/
public readonly phoneNumber?: string;
/**
* Whether or not the user is disabled: `true` for disabled; `false` for
* enabled.
*/
public readonly disabled: boolean;
/**
* Additional metadata about the user.
*/
public readonly metadata: UserMetadata;
/**
* An array of providers (for example, Google, Facebook) linked to the user.
*/
public readonly providerData: UserInfo[];
/**
* The user's hashed password (base64-encoded), only if Firebase Auth hashing
* algorithm (SCRYPT) is used. If a different hashing algorithm had been used
* when uploading this user, as is typical when migrating from another Auth
* system, this will be an empty string. If no password is set, this is
* null. This is only available when the user is obtained from
* {@link BaseAuth.listUsers}.
*/
public readonly passwordHash?: string;
/**
* The user's password salt (base64-encoded), only if Firebase Auth hashing
* algorithm (SCRYPT) is used. If a different hashing algorithm had been used to
* upload this user, typical when migrating from another Auth system, this will
* be an empty string. If no password is set, this is null. This is only
* available when the user is obtained from {@link BaseAuth.listUsers}.
*/
public readonly passwordSalt?: string;
/**
* The user's custom claims object if available, typically used to define
* user roles and propagated to an authenticated user's ID token.
* This is set via {@link BaseAuth.setCustomUserClaims}
*/
public readonly customClaims?: {[key: string]: any};
/**
* The ID of the tenant the user belongs to, if available.
*/
public readonly tenantId?: string | null;
/**
* The date the user's tokens are valid after, formatted as a UTC string.
* This is updated every time the user's refresh token are revoked either
* from the {@link BaseAuth.revokeRefreshTokens}
* API or from the Firebase Auth backend on big account changes (password
* resets, password or email updates, etc).
*/
public readonly tokensValidAfterTime?: string;
/**
* The multi-factor related properties for the current user, if available.
*/
public readonly multiFactor?: MultiFactorSettings;
/**
* @param response - The server side response returned from the getAccountInfo
* endpoint.
* @constructor
* @internal
*/
constructor(response: GetAccountInfoUserResponse) {
// The Firebase user id is required.
if (!response.localId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid user response');
}
utils.addReadonlyGetter(this, 'uid', response.localId);
utils.addReadonlyGetter(this, 'email', response.email);
utils.addReadonlyGetter(this, 'emailVerified', !!response.emailVerified);
utils.addReadonlyGetter(this, 'displayName', response.displayName);
utils.addReadonlyGetter(this, 'photoURL', response.photoUrl);
utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber);
// If disabled is not provided, the account is enabled by default.
utils.addReadonlyGetter(this, 'disabled', response.disabled || false);
utils.addReadonlyGetter(this, 'metadata', new UserMetadata(response));
const providerData: UserInfo[] = [];
for (const entry of (response.providerUserInfo || [])) {
providerData.push(new UserInfo(entry));
}
utils.addReadonlyGetter(this, 'providerData', providerData);
// If the password hash is redacted (probably due to missing permissions)
// then clear it out, similar to how the salt is returned. (Otherwise, it
// *looks* like a b64-encoded hash is present, which is confusing.)
if (response.passwordHash === B64_REDACTED) {
utils.addReadonlyGetter(this, 'passwordHash', undefined);
} else {
utils.addReadonlyGetter(this, 'passwordHash', response.passwordHash);
}
utils.addReadonlyGetter(this, 'passwordSalt', response.salt);
if (response.customAttributes) {
utils.addReadonlyGetter(
this, 'customClaims', JSON.parse(response.customAttributes));
}
let validAfterTime: string | null = null;
// Convert validSince first to UTC milliseconds and then to UTC date string.
if (typeof response.validSince !== 'undefined') {
validAfterTime = parseDate(parseInt(response.validSince, 10) * 1000);
}
utils.addReadonlyGetter(this, 'tokensValidAfterTime', validAfterTime || undefined);
utils.addReadonlyGetter(this, 'tenantId', response.tenantId);
const multiFactor = new MultiFactorSettings(response);
if (multiFactor.enrolledFactors.length > 0) {
utils.addReadonlyGetter(this, 'multiFactor', multiFactor);
}
}
/**
* Returns a JSON-serializable representation of this object.
*
* @returns A JSON-serializable representation of this object.
*/
public toJSON(): object {
const json: any = {
uid: this.uid,
email: this.email,
emailVerified: this.emailVerified,
displayName: this.displayName,
photoURL: this.photoURL,
phoneNumber: this.phoneNumber,
disabled: this.disabled,
// Convert metadata to json.
metadata: this.metadata.toJSON(),
passwordHash: this.passwordHash,
passwordSalt: this.passwordSalt,
customClaims: deepCopy(this.customClaims),
tokensValidAfterTime: this.tokensValidAfterTime,
tenantId: this.tenantId,
};
if (this.multiFactor) {
json.multiFactor = this.multiFactor.toJSON();
}
json.providerData = [];
for (const entry of this.providerData) {
// Convert each provider data to json.
json.providerData.push(entry.toJSON());
}
return json;
}
}