forked from firebase/quickstart-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmfa-password.js
545 lines (502 loc) · 17.4 KB
/
mfa-password.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/**
* @license
* Copyright 2019 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.
*/
/**
* @fileoverview The quickstart app for using phone number as second factor.
*/
var mfaResolver = null;
var phoneVerificationId = null;
var recaptchaVerifier = null;
var recaptchaWidgetId = null;
var grecaptcha;
/**
* Signs in the user with email and password.
*/
function passwordSignIn() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// Sign in with email and password.
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function() {
alertMessage('User signed in!');
})
.catch(function(error) {
// Handle second factor sign-in.
if (error.code === 'auth/multi-factor-auth-required') {
mfaResolver = error.resolver;
showMfaDialog();
return;
}
displayError(error);
});
}
/**
* Creates a user with email and password.
*/
function passwordSignUp() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// Sign up with email and password.
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function() {
alertMessage('New user created!');
}).catch(displayError);
}
/**
* Signs out the current user.
*/
function signOut() {
firebase.auth().signOut().then(function() {
alertMessage('User signed out!');
}).catch(displayError);
}
/**
* Sends an email verification to the current user.
*/
function sendEmailVerification() {
if (firebase.auth().currentUser) {
firebase.auth().currentUser.sendEmailVerification().then(function() {
alertMessage('Email Verification Sent!');
}).catch(displayError);
}
}
/**
* Sends a password reset email to the user.
*/
function sendPasswordReset() {
var email = document.getElementById('email').value;
firebase.auth().sendPasswordResetEmail(email).then(function() {
alertMessage('Password Reset Email Sent!');
}).catch(displayError);
}
/**
* Updates the multi-factor dialog UI for enrollment/sign-in flows.
*/
function updateMfaDialog() {
hideElement('mfa-error-message');
// For multi-factor sign-in.
if (mfaResolver) {
showElement('mfa-sign-in-modal');
hideElement('mfa-enroll-modal');
if (phoneVerificationId) {
// Display verify code form.
clearAppVerifier();
hideElement('sign-in-send-code-form');
showElement('sign-in-verification-code-form');
} else {
// Display send code form.
updateMfaSignInHints(mfaResolver.hints);
showElement('sign-in-send-code-form');
hideElement('sign-in-verification-code-form');
renderRecaptcha('sign-in-recaptcha-container');
updateSignInSendCodeButtonUI();
}
// For multi-factor enrollment.
} else {
hideElement('mfa-sign-in-modal');
showElement('mfa-enroll-modal');
if (phoneVerificationId) {
// Display verify code form.
clearAppVerifier();
hideElement('enroll-send-code-form');
showElement('enroll-verification-code-form');
} else {
// Display send code form.
showElement('enroll-send-code-form');
hideElement('enroll-verification-code-form');
renderRecaptcha('enroll-recaptcha-container');
updateEnrollSendCodeButtonUI();
}
}
}
/**
* Handles the enroll button click.
*/
function onEnrollClick() {
if (firebase.auth().currentUser) {
firebase.auth().currentUser.reload().then(function() {
showMfaDialog();
}).catch(displayError);
}
}
/**
* Displays the multi-factor dialog.
*/
function showMfaDialog() {
updateMfaDialog();
document.getElementById('mfa-modal').show();
}
/**
* Displays Recaptcha verifier in the provided container.
* @param {!Element|string} container The reCAPTCHA container.
*/
function renderRecaptcha(container) {
recaptchaVerifier = new firebase.auth.RecaptchaVerifier(container, {
'size': 'normal',
'callback': function(response) {
// reCAPTCHA solved, allow send code for enrollment/sign-in.
updateEnrollSendCodeButtonUI();
updateSignInSendCodeButtonUI();
},
'expired-callback': function() {
// Response expired. Ask user to solve reCAPTCHA again.
updateEnrollSendCodeButtonUI();
updateSignInSendCodeButtonUI();
}
});
recaptchaVerifier.render().then(function(widgetId) {
recaptchaWidgetId = widgetId;
});
}
/**
* Displays the account details of the current user.
* @param {?firebase.User} user The current signed in user.
*/
function showAccountDetails(user) {
var accountDetails = user ? JSON.stringify(user, null, ' ') : null;
document.getElementById('quickstart-account-details').textContent = accountDetails;
}
/**
* Displays the enrolled second factors of the current user.
* @param {!Array<!firebase.auth.MultiFactorInfo>} enrolledFactors The
* enrolled second factors of the current user.
*/
function showEnrolledFactors(enrolledFactors) {
var listGroup = document.getElementById('mfa-enrolled-factors');
// Clear the list.
listGroup.innerHTML = '';
if (enrolledFactors.length == 0) {
listGroup.innerHTML = 'N/A';
}
enrolledFactors.forEach(function(value, i) {
// Append entry to list.
var displayName = value.displayName || 'N/A';
var phoneNumber = value.phoneNumber;
var node = document.createElement('li');
node.classList.add('mdl-list__item');
node.setAttribute('data-val', i);
node.textContent = phoneNumber + ' ' + displayName;
// Append delete icon.
var icon = document.createElement('i');
icon.classList.add('material-icons');
icon.classList.add('mdl-list__item-icon');
icon.textContent = 'delete';
icon.addEventListener('click', onUnenroll);
node.appendChild(icon);
listGroup.appendChild(node);
});
}
/**
* Updates the second factor dropdown options for sign-in.
* @param {!Array<!firebase.auth.MultiFactorInfo>} hints The sign-in
* second factor hints.
*/
function updateMfaSignInHints(hints) {
var listGroup = document.getElementById('mfa-hints');
// Clear the list.
listGroup.innerHTML = '';
listGroup.appendChild(document.createElement('option'));
hints.forEach(function(value, i) {
// Append entry to list.
var node = document.createElement('option');
node.setAttribute('data-val', i);
node.textContent = value.phoneNumber;
listGroup.appendChild(node);
});
}
/**
* Handles the multi-factor hints selection for sign-in.
* @param {!Event} e The phone number dropdown on change event.
*/
function onSelect(e) {
var label = document.getElementById('mfa-hint-label');
label.className = label.className.replace(' is-active', '');
if (e.target.value) {
label.className += ' is-active';
}
}
/**
* Handles send code button click for second factor enrollment.
* @param {!Event} e The send code for enrollment on click event.
*/
function onEnrollSendCode(e) {
e.preventDefault();
if (isCaptchaOK() && isPhoneNumberValid() && firebase.auth().currentUser) {
var phoneNumber = document.getElementById('phone-number').value;
var provider = new firebase.auth.PhoneAuthProvider(firebase.auth());
firebase.auth().currentUser.multiFactor.getSession()
.then(function(multiFactorSession) {
var phoneInfoOptions = {
'phoneNumber': phoneNumber,
'session': multiFactorSession
};
// Send code for enrollment.
return provider.verifyPhoneNumber(
phoneInfoOptions, recaptchaVerifier);
}).then(function(verificationId) {
phoneVerificationId = verificationId;
// Update the multi-factor dialog to verify the sent code.
updateMfaDialog();
}, function(error) {
updateEnrollSendCodeButtonUI();
displayMfaError(error);
});
}
}
/**
* Handles verify code button click for second factor enrollment.
* @param {!Event} e The verify code for enrollment on click event.
*/
function onEnrollVerifyCode(e) {
e.preventDefault();
if (firebase.auth().currentUser && phoneVerificationId) {
var code = document.getElementById('enroll-verification-code').value;
var credential = firebase.auth.PhoneAuthProvider.credential(
phoneVerificationId, code);
var multiFactorAssertion =
firebase.auth.PhoneMultiFactorGenerator.assertion(credential);
var displayName = document.getElementById('enroll-display-name').value || undefined;
// Enroll the phone second factor.
firebase.auth().currentUser.multiFactor.enroll(multiFactorAssertion, displayName)
.then(function () {
showAccountDetails(firebase.auth().currentUser);
var enrolledFactors = firebase.auth().currentUser.multiFactor.enrolledFactors;
showEnrolledFactors(enrolledFactors);
clearMfaDialog();
alertMessage('Second factor enrolled!');
}).catch(displayMfaError);
}
}
/**
* Handles send code button click for second factor sign-in.
* @param {!Event} e The send code for sign-in on click event.
*/
function onSignInSendCode(e) {
e.preventDefault();
if (isCaptchaOK() && mfaResolver) {
var node = document.getElementById('mfa-hints');
var index = parseInt(node.options[node.selectedIndex].getAttribute('data-val'), 10);
var info = mfaResolver.hints[index];
var provider = new firebase.auth.PhoneAuthProvider(firebase.auth());
var signInRequest = {
multiFactorHint: info,
session: mfaResolver.session
};
provider.verifyPhoneNumber(signInRequest, recaptchaVerifier)
.then(function(verificationId) {
phoneVerificationId = verificationId;
updateMfaDialog();
}, function(error) {
updateSignInSendCodeButtonUI();
displayMfaError(error);
});
}
}
/**
* Handles verify code button click for second factor sign-in.
* @param {!Event} e The verify code for sign-in on click event.
*/
function onSignInVerifyCode(e) {
e.preventDefault();
if (mfaResolver && phoneVerificationId) {
var code = document.getElementById('sign-in-verification-code').value;
var credential = firebase.auth.PhoneAuthProvider.credential(
phoneVerificationId, code);
var multiFactorAssertion =
firebase.auth.PhoneMultiFactorGenerator.assertion(credential);
mfaResolver.resolveSignIn(multiFactorAssertion).then(function () {
alertMessage('Signed in with second factor!');
clearMfaDialog();
var enrolledFactors = firebase.auth().currentUser.multiFactor.enrolledFactors;
showEnrolledFactors(enrolledFactors);
}).catch(displayMfaError);
}
}
/**
* Handles unenroll icon click for enrolled second factors.
* @param {!Event} e The unenroll on click event.
*/
function onUnenroll(e) {
var index = parseInt(e.target.parentNode.getAttribute('data-val'), 10);
if (firebase.auth().currentUser) {
var info = firebase.auth().currentUser.multiFactor.enrolledFactors[index];
if (info) {
firebase.auth().currentUser.multiFactor.unenroll(info).then(function() {
alertMessage(info.phoneNumber + ' has been unenrolled!');
showAccountDetails(firebase.auth().currentUser);
var enrolledFactors = (firebase.auth().currentUser &&
firebase.auth().currentUser.multiFactor.enrolledFactors) || [];
showEnrolledFactors(enrolledFactors);
}).catch(displayError);
}
}
}
/**
* Handles cancel button click.
* @param {!Event} e The cancel on click event.
*/
function onCancel(e) {
e.preventDefault();
clearMfaDialog();
}
/**
* Returns true if the input of phone number entry is valid.
* @return {boolean} Whether the phone number is valid.
*/
function isPhoneNumberValid() {
var pattern = /^\+[0-9\s\-()]+$/;
var phoneNumber = document.getElementById('phone-number').value;
return phoneNumber.search(pattern) !== -1;
}
/**
* Returns true if the ReCaptcha is in an OK state.
* @return {boolean} Whether the ReCaptcha is in OK state.
*/
function isCaptchaOK() {
if (typeof grecaptcha !== 'undefined' &&
recaptchaWidgetId !== null) {
var recaptchaResponse = grecaptcha.getResponse(recaptchaWidgetId);
return !!recaptchaResponse;
}
return false;
}
/**
* Updates the enroll send code button state depending on form values state.
*/
function updateEnrollSendCodeButtonUI() {
document.getElementById('enroll-send-code-button').disabled =
!isCaptchaOK() || !isPhoneNumberValid();
}
/**
* Updates the sign in send code button state depending on form values state.
*/
function updateSignInSendCodeButtonUI() {
document.getElementById('sign-in-send-code-button').disabled = !isCaptchaOK();
}
/**
* Clears the application verifier.
*/
function clearAppVerifier() {
if (recaptchaVerifier) {
recaptchaVerifier.clear();
recaptchaVerifier = null;
}
recaptchaWidgetId = null;
}
/**
* Clears the multi-factor dialog.
*/
function clearMfaDialog() {
mfaResolver = null;
phoneVerificationId = null;
document.getElementById('mfa-modal').close();
clearAppVerifier();
}
/**
* Shows the element by ID.
* @param {string} elementId The ID of the element.
*/
function showElement(elementId) {
var element = document.getElementById(elementId);
if (element) {
element.style.display = 'block';
}
}
/**
* Hides the element by ID.
* @param {string} elementId The ID of the element.
*/
function hideElement(elementId) {
var element = document.getElementById(elementId);
if (element) {
element.style.display = 'none';
}
}
/**
* Alerts the error message in the toast and logs the error in the console.
* @param {!Error} error The error to display.
*/
function displayError(error) {
alertMessage(error.message);
console.error(error);
}
/**
* Displays the error message in the mfa dialog and logs the error in the console.
* @param {!Error} error The mfa error.
*/
function displayMfaError(error) {
console.error(error);
document.getElementById('mfa-error-message').textContent = error.message;
showElement('mfa-error-message');
}
/**
* Displays the alert message in the toast.
*/
function alertMessage(msg) {
var snackbarContainer = document.getElementById('quickstart-snackbar');
var data = {
message: msg
};
snackbarContainer.MaterialSnackbar.showSnackbar(data);
}
/**
* initApp handles setting up UI event listeners and registering Firebase auth listeners:
* - firebase.auth().onAuthStateChanged: This listener is called when the user is signed in or
* out, and that is where we update the UI.
*/
function initApp() {
// Listening for Auth state changes.
firebase.auth().onAuthStateChanged(function(user) {
document.getElementById('quickstart-sign-out').disabled = true;
document.getElementById('quickstart-enroll').disabled = true;
document.getElementById('quickstart-verify-email').disabled = true;
if (user) {
document.getElementById('quickstart-sign-in-status').textContent = 'Signed in';
document.getElementById('quickstart-sign-out').disabled = false;
document.getElementById('quickstart-enroll').disabled = false;
if (!user.emailVerified) {
document.getElementById('quickstart-verify-email').disabled = false;
}
showAccountDetails(user);
showEnrolledFactors(user.multiFactor.enrolledFactors);
} else {
// User is signed out.
document.getElementById('quickstart-sign-in-status').textContent = 'Signed out';
showAccountDetails(null);
showEnrolledFactors([]);
}
});
document.getElementById('quickstart-sign-in').addEventListener('click', passwordSignIn);
document.getElementById('quickstart-sign-up').addEventListener('click', passwordSignUp);
document.getElementById('quickstart-sign-out').addEventListener('click', signOut);
document.getElementById('quickstart-verify-email').addEventListener('click', sendEmailVerification);
document.getElementById('quickstart-password-reset').addEventListener('click', sendPasswordReset);
document.getElementById('quickstart-enroll').addEventListener('click', onEnrollClick);
document.getElementById('phone-number').addEventListener('keyup', updateEnrollSendCodeButtonUI);
document.getElementById('phone-number').addEventListener('change', updateEnrollSendCodeButtonUI);
document.getElementById('enroll-send-code-form').addEventListener('submit', onEnrollSendCode);
document.getElementById('enroll-cancel-send-code-button').addEventListener('click', onCancel);
document.getElementById('enroll-verification-code-form').addEventListener('submit', onEnrollVerifyCode);
document.getElementById('enroll-cancel-verify-code-button').addEventListener('click', onCancel);
document.getElementById('sign-in-send-code-form').addEventListener('submit', onSignInSendCode);
document.getElementById('sign-in-cancel-send-code-button').addEventListener('click', onCancel);
document.getElementById('mfa-hints').addEventListener('change', onSelect);
document.getElementById('sign-in-verification-code-form').addEventListener('submit', onSignInVerifyCode);
document.getElementById('sign-in-cancel-verify-code-button').addEventListener('click', onCancel);
}
window.onload = function() {
initApp();
};