From 45a4f6626d11fb6854cbc2d6c5ef916205525565 Mon Sep 17 00:00:00 2001 From: Rin Arakaki Date: Sun, 20 Oct 2024 17:55:57 +0900 Subject: [PATCH 01/15] Update .eslintrc.json --- .eslintrc.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.eslintrc.json b/.eslintrc.json index 7e4337ee..7aafea9e 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -2,7 +2,7 @@ "env": { "browser": true, "commonjs": true, - "es2021": true + "es2022": true }, "parserOptions": { "ecmaVersion": 12, From 474e66fa32b867a3ea83047b98fc17c0ec26aabb Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:05:21 +0000 Subject: [PATCH 02/15] Update auth-next/email.js --- auth-next/email.js | 75 +++++++++---------- .../email/auth_send_email_verification.js | 8 +- .../email/auth_send_password_reset.js | 19 +++-- .../auth-next/email/auth_signin_password.js | 19 +++-- .../auth-next/email/auth_signup_password.js | 21 +++--- 5 files changed, 66 insertions(+), 76 deletions(-) diff --git a/auth-next/email.js b/auth-next/email.js index 26391f81..3959f70a 100644 --- a/auth-next/email.js +++ b/auth-next/email.js @@ -1,7 +1,7 @@ // [SNIPPET_REGISTRY disabled] // [SNIPPETS_SEPARATION enabled] -function signInWithEmailPassword() { +async function signInWithEmailPassword() { const email = "test@example.com"; const password = "hunter2"; @@ -9,20 +9,19 @@ function signInWithEmailPassword() { const { getAuth, signInWithEmailAndPassword } = require("firebase/auth"); const auth = getAuth(); - signInWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // Signed in - const user = userCredential.user; - // ... - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - }); + try { + const userCredential = await signInWithEmailAndPassword(auth, email, password); + // Signed in + const user = userCredential.user; + // ... + } catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + } // [END auth_signin_password] } -function signUpWithEmailPassword() { +async function signUpWithEmailPassword() { const email = "test@example.com"; const password = "hunter2"; @@ -30,49 +29,45 @@ function signUpWithEmailPassword() { const { getAuth, createUserWithEmailAndPassword } = require("firebase/auth"); const auth = getAuth(); - createUserWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // Signed up - const user = userCredential.user; - // ... - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // .. - }); + try { + const userCredential = await createUserWithEmailAndPassword(auth, email, password); + // Signed up + const user = userCredential.user; + // ... + } catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // .. + } // [END auth_signup_password] } -function sendEmailVerification() { +async function sendEmailVerification() { // [START auth_send_email_verification] const { getAuth, sendEmailVerification } = require("firebase/auth"); const auth = getAuth(); - sendEmailVerification(auth.currentUser) - .then(() => { - // Email verification sent! - // ... - }); + await sendEmailVerification(auth.currentUser); + // Email verification sent! + // ... // [END auth_send_email_verification] } -function sendPasswordReset() { +async function sendPasswordReset() { const email = "sam@example.com"; // [START auth_send_password_reset] const { getAuth, sendPasswordResetEmail } = require("firebase/auth"); const auth = getAuth(); - sendPasswordResetEmail(auth, email) - .then(() => { - // Password reset email sent! - // .. - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // .. - }); + try { + await sendPasswordResetEmail(auth, email); + // Password reset email sent! + // .. + } catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // .. + } // [END auth_send_password_reset] } diff --git a/snippets/auth-next/email/auth_send_email_verification.js b/snippets/auth-next/email/auth_send_email_verification.js index 9290a421..7ad8128c 100644 --- a/snippets/auth-next/email/auth_send_email_verification.js +++ b/snippets/auth-next/email/auth_send_email_verification.js @@ -8,9 +8,7 @@ import { getAuth, sendEmailVerification } from "firebase/auth"; const auth = getAuth(); -sendEmailVerification(auth.currentUser) - .then(() => { - // Email verification sent! - // ... - }); +await sendEmailVerification(auth.currentUser); +// Email verification sent! +// ... // [END auth_send_email_verification_modular] \ No newline at end of file diff --git a/snippets/auth-next/email/auth_send_password_reset.js b/snippets/auth-next/email/auth_send_password_reset.js index e8e18a58..525de896 100644 --- a/snippets/auth-next/email/auth_send_password_reset.js +++ b/snippets/auth-next/email/auth_send_password_reset.js @@ -8,14 +8,13 @@ import { getAuth, sendPasswordResetEmail } from "firebase/auth"; const auth = getAuth(); -sendPasswordResetEmail(auth, email) - .then(() => { - // Password reset email sent! - // .. - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // .. - }); +try { + await sendPasswordResetEmail(auth, email); + // Password reset email sent! + // .. +} catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // .. +} // [END auth_send_password_reset_modular] \ No newline at end of file diff --git a/snippets/auth-next/email/auth_signin_password.js b/snippets/auth-next/email/auth_signin_password.js index f0a211d5..79f1305f 100644 --- a/snippets/auth-next/email/auth_signin_password.js +++ b/snippets/auth-next/email/auth_signin_password.js @@ -8,14 +8,13 @@ import { getAuth, signInWithEmailAndPassword } from "firebase/auth"; const auth = getAuth(); -signInWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // Signed in - const user = userCredential.user; - // ... - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - }); +try { + const userCredential = await signInWithEmailAndPassword(auth, email, password); + // Signed in + const user = userCredential.user; + // ... +} catch (error) { + const errorCode = error.code; + const errorMessage = error.message; +} // [END auth_signin_password_modular] \ No newline at end of file diff --git a/snippets/auth-next/email/auth_signup_password.js b/snippets/auth-next/email/auth_signup_password.js index 936b64ce..0c87dc8e 100644 --- a/snippets/auth-next/email/auth_signup_password.js +++ b/snippets/auth-next/email/auth_signup_password.js @@ -8,15 +8,14 @@ import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"; const auth = getAuth(); -createUserWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // Signed up - const user = userCredential.user; - // ... - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // .. - }); +try { + const userCredential = await createUserWithEmailAndPassword(auth, email, password); + // Signed up + const user = userCredential.user; + // ... +} catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // .. +} // [END auth_signup_password_modular] \ No newline at end of file From 2cf518a585f2257795aa32557ef762f5f30503a9 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:12:42 +0000 Subject: [PATCH 03/15] Update auth-next/index.js --- auth-next/index.js | 36 +++++++++---------- snippets/auth-next/index/auth_sign_out.js | 7 ++-- .../auth-next/index/auth_signin_credential.js | 25 +++++++------ 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/auth-next/index.js b/auth-next/index.js index 04ac7d03..4ebcf592 100644 --- a/auth-next/index.js +++ b/auth-next/index.js @@ -31,16 +31,17 @@ function makeEmailCredential(email, password) { // [END auth_make_email_credential] } -function signOut() { +async function signOut() { // [START auth_sign_out] const { getAuth, signOut } = require("firebase/auth"); const auth = getAuth(); - signOut(auth).then(() => { + try { + await signOut(auth); // Sign-out successful. - }).catch((error) => { + } catch (error) { // An error happened. - }); + } // [END auth_sign_out] } @@ -91,25 +92,24 @@ function setLanguageCode() { // [END auth_set_language_code] } -function authWithCredential(credential) { +async function authWithCredential(credential) { // [START auth_signin_credential] const { getAuth, signInWithCredential } = require("firebase/auth"); // Sign in with the credential from the user. const auth = getAuth(); - signInWithCredential(auth, credential) - .then((result) => { - // Signed in - // ... - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // ... - }); + try { + const result = await signInWithCredential(auth, credential); + // Signed in + // ... + } catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // ... + } // [END auth_signin_credential] } diff --git a/snippets/auth-next/index/auth_sign_out.js b/snippets/auth-next/index/auth_sign_out.js index 4cef4757..35263562 100644 --- a/snippets/auth-next/index/auth_sign_out.js +++ b/snippets/auth-next/index/auth_sign_out.js @@ -8,9 +8,10 @@ import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); -signOut(auth).then(() => { +try { + await signOut(auth); // Sign-out successful. -}).catch((error) => { +} catch (error) { // An error happened. -}); +} // [END auth_sign_out_modular] \ No newline at end of file diff --git a/snippets/auth-next/index/auth_signin_credential.js b/snippets/auth-next/index/auth_signin_credential.js index c2b027a3..110972d6 100644 --- a/snippets/auth-next/index/auth_signin_credential.js +++ b/snippets/auth-next/index/auth_signin_credential.js @@ -9,17 +9,16 @@ import { getAuth, signInWithCredential } from "firebase/auth"; // Sign in with the credential from the user. const auth = getAuth(); -signInWithCredential(auth, credential) - .then((result) => { - // Signed in - // ... - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // ... - }); +try { + const result = await signInWithCredential(auth, credential); + // Signed in + // ... +} catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // ... +} // [END auth_signin_credential_modular] \ No newline at end of file From 654504a36d0d3ae2d54f3d0095cc0efde616e7bb Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:18:20 +0000 Subject: [PATCH 04/15] Update auth-next/manage.js --- auth-next/manage.js | 78 ++++++++++--------- snippets/auth-next/manage/auth_delete_user.js | 7 +- .../manage/auth_reauth_with_credential.js | 7 +- .../manage/auth_send_password_reset.js | 7 +- .../auth-next/manage/auth_update_password.js | 7 +- .../manage/auth_update_user_email.js | 7 +- .../manage/auth_update_user_profile.js | 12 +-- .../manage/send_email_verification.js | 7 +- 8 files changed, 74 insertions(+), 58 deletions(-) diff --git a/auth-next/manage.js b/auth-next/manage.js index bf603ccc..5fd68c98 100644 --- a/auth-next/manage.js +++ b/auth-next/manage.js @@ -41,107 +41,114 @@ function getUserProfileProvider() { // [END auth_get_user_profile_provider] } -function updateUserProfile() { +async function updateUserProfile() { // [START auth_update_user_profile] const { getAuth, updateProfile } = require("firebase/auth"); const auth = getAuth(); - updateProfile(auth.currentUser, { - displayName: "Jane Q. User", photoURL: "https://example.com/jane-q-user/profile.jpg" - }).then(() => { + try { + await updateProfile(auth.currentUser, { + displayName: "Jane Q. User", + photoURL: "https://example.com/jane-q-user/profile.jpg", + }); // Profile updated! // ... - }).catch((error) => { + } catch (error) { // An error occurred // ... - }); + } // [END auth_update_user_profile] } -function updateUserEmail() { +async function updateUserEmail() { // [START auth_update_user_email] const { getAuth, updateEmail } = require("firebase/auth"); const auth = getAuth(); - updateEmail(auth.currentUser, "user@example.com").then(() => { + try { + await updateEmail(auth.currentUser, "user@example.com"); // Email updated! // ... - }).catch((error) => { + } catch (error) { // An error occurred // ... - }); + } // [END auth_update_user_email] } -function sendEmailVerification() { +async function sendEmailVerification() { // [START send_email_verification] const { getAuth, sendEmailVerification } = require("firebase/auth"); - + const auth = getAuth(); const user = auth.currentUser; - sendEmailVerification(user).then(() => { + try { + await sendEmailVerification(user); // Email sent. - }).catch((error) => { + } catch (error) { // An error ocurred // ... - }); + } // [END send_email_verification] } -function updatePassword() { +async function updatePassword() { function getASecureRandomPassword() { return "correcthorsebatterystaple"; } // [START auth_update_password] const { getAuth, updatePassword } = require("firebase/auth"); - + const auth = getAuth(); const user = auth.currentUser; const newPassword = getASecureRandomPassword(); - updatePassword(user, newPassword).then(() => { + try { + await updatePassword(user, newPassword); // Update successful. - }).catch((error) => { + } catch (error) { // An error ocurred // ... - }); + } // [END auth_update_password] } -function sendPasswordReset() { +async function sendPasswordReset() { // [START auth_send_password_reset] const { getAuth, sendPasswordResetEmail } = require("firebase/auth"); - + const auth = getAuth(); const emailAddress = "user@example.com"; - sendPasswordResetEmail(auth, emailAddress).then(() => { + try { + await sendPasswordResetEmail(auth, emailAddress); // Email sent. - }).catch((error) => { + } catch (error) { // An error ocurred // ... - }); + } // [END auth_send_password_reset] } -function deleteUser() { +async function deleteUser() { // [START auth_delete_user] const { getAuth, deleteUser } = require("firebase/auth"); - + const auth = getAuth(); const user = auth.currentUser; - deleteUser(user).then(() => { + try { + await deleteUser(user); // User deleted. - }).catch((error) => { + } catch (error) { // An error ocurred // ... - }); + } // [END auth_delete_user] } -function reauthenticateWithCredential() { +async function reauthenticateWithCredential() { /** * @returns {object} */ @@ -151,18 +158,19 @@ function reauthenticateWithCredential() { // [START auth_reauth_with_credential] const { getAuth, reauthenticateWithCredential } = require("firebase/auth"); - + const auth = getAuth(); const user = auth.currentUser; // TODO(you): prompt the user to re-provide their sign-in credentials const credential = promptForCredentials(); - reauthenticateWithCredential(user, credential).then(() => { + try { + await reauthenticateWithCredential(user, credential); // User re-authenticated. - }).catch((error) => { + } catch (error) { // An error ocurred // ... - }); + } // [END auth_reauth_with_credential] } diff --git a/snippets/auth-next/manage/auth_delete_user.js b/snippets/auth-next/manage/auth_delete_user.js index 389a0852..127de80f 100644 --- a/snippets/auth-next/manage/auth_delete_user.js +++ b/snippets/auth-next/manage/auth_delete_user.js @@ -10,10 +10,11 @@ import { getAuth, deleteUser } from "firebase/auth"; const auth = getAuth(); const user = auth.currentUser; -deleteUser(user).then(() => { +try { + await deleteUser(user); // User deleted. -}).catch((error) => { +} catch (error) { // An error ocurred // ... -}); +} // [END auth_delete_user_modular] \ No newline at end of file diff --git a/snippets/auth-next/manage/auth_reauth_with_credential.js b/snippets/auth-next/manage/auth_reauth_with_credential.js index 74e84732..1b024ebd 100644 --- a/snippets/auth-next/manage/auth_reauth_with_credential.js +++ b/snippets/auth-next/manage/auth_reauth_with_credential.js @@ -13,10 +13,11 @@ const user = auth.currentUser; // TODO(you): prompt the user to re-provide their sign-in credentials const credential = promptForCredentials(); -reauthenticateWithCredential(user, credential).then(() => { +try { + await reauthenticateWithCredential(user, credential); // User re-authenticated. -}).catch((error) => { +} catch (error) { // An error ocurred // ... -}); +} // [END auth_reauth_with_credential_modular] \ No newline at end of file diff --git a/snippets/auth-next/manage/auth_send_password_reset.js b/snippets/auth-next/manage/auth_send_password_reset.js index 9e8f2c3c..39e2e881 100644 --- a/snippets/auth-next/manage/auth_send_password_reset.js +++ b/snippets/auth-next/manage/auth_send_password_reset.js @@ -10,10 +10,11 @@ import { getAuth, sendPasswordResetEmail } from "firebase/auth"; const auth = getAuth(); const emailAddress = "user@example.com"; -sendPasswordResetEmail(auth, emailAddress).then(() => { +try { + await sendPasswordResetEmail(auth, emailAddress); // Email sent. -}).catch((error) => { +} catch (error) { // An error ocurred // ... -}); +} // [END auth_send_password_reset_modular] \ No newline at end of file diff --git a/snippets/auth-next/manage/auth_update_password.js b/snippets/auth-next/manage/auth_update_password.js index 56e578b9..6567bdaa 100644 --- a/snippets/auth-next/manage/auth_update_password.js +++ b/snippets/auth-next/manage/auth_update_password.js @@ -12,10 +12,11 @@ const auth = getAuth(); const user = auth.currentUser; const newPassword = getASecureRandomPassword(); -updatePassword(user, newPassword).then(() => { +try { + await updatePassword(user, newPassword); // Update successful. -}).catch((error) => { +} catch (error) { // An error ocurred // ... -}); +} // [END auth_update_password_modular] \ No newline at end of file diff --git a/snippets/auth-next/manage/auth_update_user_email.js b/snippets/auth-next/manage/auth_update_user_email.js index d3607f75..3ccf6967 100644 --- a/snippets/auth-next/manage/auth_update_user_email.js +++ b/snippets/auth-next/manage/auth_update_user_email.js @@ -7,11 +7,12 @@ // [START auth_update_user_email_modular] import { getAuth, updateEmail } from "firebase/auth"; const auth = getAuth(); -updateEmail(auth.currentUser, "user@example.com").then(() => { +try { + await updateEmail(auth.currentUser, "user@example.com"); // Email updated! // ... -}).catch((error) => { +} catch (error) { // An error occurred // ... -}); +} // [END auth_update_user_email_modular] \ No newline at end of file diff --git a/snippets/auth-next/manage/auth_update_user_profile.js b/snippets/auth-next/manage/auth_update_user_profile.js index 2af9185a..e7d1326c 100644 --- a/snippets/auth-next/manage/auth_update_user_profile.js +++ b/snippets/auth-next/manage/auth_update_user_profile.js @@ -7,13 +7,15 @@ // [START auth_update_user_profile_modular] import { getAuth, updateProfile } from "firebase/auth"; const auth = getAuth(); -updateProfile(auth.currentUser, { - displayName: "Jane Q. User", photoURL: "https://example.com/jane-q-user/profile.jpg" -}).then(() => { +try { + await updateProfile(auth.currentUser, { + displayName: "Jane Q. User", + photoURL: "https://example.com/jane-q-user/profile.jpg", + }); // Profile updated! // ... -}).catch((error) => { +} catch (error) { // An error occurred // ... -}); +} // [END auth_update_user_profile_modular] \ No newline at end of file diff --git a/snippets/auth-next/manage/send_email_verification.js b/snippets/auth-next/manage/send_email_verification.js index 34f06fdb..ce7ad0be 100644 --- a/snippets/auth-next/manage/send_email_verification.js +++ b/snippets/auth-next/manage/send_email_verification.js @@ -10,10 +10,11 @@ import { getAuth, sendEmailVerification } from "firebase/auth"; const auth = getAuth(); const user = auth.currentUser; -sendEmailVerification(user).then(() => { +try { + await sendEmailVerification(user); // Email sent. -}).catch((error) => { +} catch (error) { // An error ocurred // ... -}); +} // [END send_email_verification_modular] \ No newline at end of file From 16e7b7484bcc89018875991a2b87dbedcd2871c9 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:27:08 +0000 Subject: [PATCH 05/15] Update auth-next/email-link-auth.js --- auth-next/email-link-auth.js | 135 +++++++++--------- .../email-link-auth/auth_email_link_link.js | 15 +- .../email-link-auth/auth_email_link_reauth.js | 15 +- .../email-link-auth/auth_email_link_send.js | 25 ++-- .../email-link-auth/email_link_complete.js | 33 +++-- .../email_link_diferentiate.js | 37 +++-- 6 files changed, 125 insertions(+), 135 deletions(-) diff --git a/auth-next/email-link-auth.js b/auth-next/email-link-auth.js index 4748e699..81eb53ce 100644 --- a/auth-next/email-link-auth.js +++ b/auth-next/email-link-auth.js @@ -24,28 +24,27 @@ function emailLinkActionCodeSettings() { // [END auth_email_link_actioncode_settings] } -function emailLinkSend(email, actionCodeSettings) { +async function emailLinkSend(email, actionCodeSettings) { // [START auth_email_link_send] const { getAuth, sendSignInLinkToEmail } = require("firebase/auth"); const auth = getAuth(); - sendSignInLinkToEmail(auth, email, actionCodeSettings) - .then(() => { - // The link was successfully sent. Inform the user. - // Save the email locally so you don't need to ask the user for it again - // if they open the link on the same device. - window.localStorage.setItem('emailForSignIn', email); - // ... - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // ... - }); + try { + await sendSignInLinkToEmail(auth, email, actionCodeSettings); + // The link was successfully sent. Inform the user. + // Save the email locally so you don't need to ask the user for it again + // if they open the link on the same device. + window.localStorage.setItem('emailForSignIn', email); + // ... + } catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // ... + } // [END auth_email_link_send] } -function emailLinkComplete() { +async function emailLinkComplete() { // [START email_link_complete] const { getAuth, isSignInWithEmailLink, signInWithEmailLink } = require("firebase/auth"); @@ -63,28 +62,27 @@ function emailLinkComplete() { // attacks, ask the user to provide the associated email again. For example: email = window.prompt('Please provide your email for confirmation'); } - // The client SDK will parse the code from the link for you. - signInWithEmailLink(auth, email, window.location.href) - .then((result) => { - // Clear email from storage. - window.localStorage.removeItem('emailForSignIn'); - // You can access the new user by importing getAdditionalUserInfo - // and calling it with result: - // getAdditionalUserInfo(result) - // You can access the user's profile via: - // getAdditionalUserInfo(result)?.profile - // You can check if the user is new or existing: - // getAdditionalUserInfo(result)?.isNewUser - }) - .catch((error) => { - // Some error occurred, you can inspect the code: error.code - // Common errors could be invalid email and invalid or expired OTPs. - }); + try { + // The client SDK will parse the code from the link for you. + const result = await signInWithEmailLink(auth, email, window.location.href); + // Clear email from storage. + window.localStorage.removeItem('emailForSignIn'); + // You can access the new user by importing getAdditionalUserInfo + // and calling it with result: + // getAdditionalUserInfo(result) + // You can access the user's profile via: + // getAdditionalUserInfo(result)?.profile + // You can check if the user is new or existing: + // getAdditionalUserInfo(result)?.isNewUser + } catch (error) { + // Some error occurred, you can inspect the code: error.code + // Common errors could be invalid email and invalid or expired OTPs. + } } // [END email_link_complete] } -function emailLinkLink(email) { +async function emailLinkLink(email) { // [START auth_email_link_link] const { getAuth, linkWithCredential, EmailAuthProvider } = require("firebase/auth"); @@ -94,18 +92,17 @@ function emailLinkLink(email) { // Link the credential to the current user. const auth = getAuth(); - linkWithCredential(auth.currentUser, credential) - .then((usercred) => { - // The provider is now successfully linked. - // The phone user can now sign in with their phone number or email. - }) - .catch((error) => { - // Some error occurred. - }); + try { + const usercred = await linkWithCredential(auth.currentUser, credential); + // The provider is now successfully linked. + // The phone user can now sign in with their phone number or email. + } catch (error) { + // Some error occurred. + } // [END auth_email_link_link] } -function emailLinkReauth(email) { +async function emailLinkReauth(email) { // [START auth_email_link_reauth] const { getAuth, reauthenticateWithCredential, EmailAuthProvider } = require("firebase/auth"); @@ -115,42 +112,40 @@ function emailLinkReauth(email) { // Re-authenticate the user with this credential. const auth = getAuth(); - reauthenticateWithCredential(auth.currentUser, credential) - .then((usercred) => { - // The user is now successfully re-authenticated and can execute sensitive - // operations. - }) - .catch((error) => { - // Some error occurred. - }); + try { + const usercred = await reauthenticateWithCredential(auth.currentUser, credential); + // The user is now successfully re-authenticated and can execute sensitive + // operations. + } catch (error) { + // Some error occurred. + } // [END auth_email_link_reauth] } -function emailLinkDifferentiate() { +async function emailLinkDifferentiate() { // [START email_link_diferentiate] - const { getAuth, fetchSignInMethodsForEmail, EmailAuthProvider} = require("firebase/auth"); + const { getAuth, fetchSignInMethodsForEmail, EmailAuthProvider } = require("firebase/auth"); // After asking the user for their email. const email = window.prompt('Please provide your email'); const auth = getAuth(); - fetchSignInMethodsForEmail(auth, email) - .then((signInMethods) => { - // This returns the same array as fetchProvidersForEmail but for email - // provider identified by 'password' string, signInMethods would contain 2 - // different strings: - // 'emailLink' if the user previously signed in with an email/link - // 'password' if the user has a password. - // A user could have both. - if (signInMethods.indexOf(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) != -1) { - // User can sign in with email/password. - } - if (signInMethods.indexOf(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD) != -1) { - // User can sign in with email/link. - } - }) - .catch((error) => { - // Some error occurred, you can inspect the code: error.code - }); + try { + const signInMethods = await fetchSignInMethodsForEmail(auth, email); + // This returns the same array as fetchProvidersForEmail but for email + // provider identified by 'password' string, signInMethods would contain 2 + // different strings: + // 'emailLink' if the user previously signed in with an email/link + // 'password' if the user has a password. + // A user could have both. + if (signInMethods.indexOf(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) != -1) { + // User can sign in with email/password. + } + if (signInMethods.indexOf(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD) != -1) { + // User can sign in with email/link. + } + } catch (error) { + // Some error occurred, you can inspect the code: error.code + } // [END email_link_diferentiate] } diff --git a/snippets/auth-next/email-link-auth/auth_email_link_link.js b/snippets/auth-next/email-link-auth/auth_email_link_link.js index a49b979f..dd7c77d3 100644 --- a/snippets/auth-next/email-link-auth/auth_email_link_link.js +++ b/snippets/auth-next/email-link-auth/auth_email_link_link.js @@ -13,12 +13,11 @@ const credential = EmailAuthProvider.credentialWithLink( // Link the credential to the current user. const auth = getAuth(); -linkWithCredential(auth.currentUser, credential) - .then((usercred) => { - // The provider is now successfully linked. - // The phone user can now sign in with their phone number or email. - }) - .catch((error) => { - // Some error occurred. - }); +try { + const usercred = await linkWithCredential(auth.currentUser, credential); + // The provider is now successfully linked. + // The phone user can now sign in with their phone number or email. +} catch (error) { + // Some error occurred. +} // [END auth_email_link_link_modular] \ No newline at end of file diff --git a/snippets/auth-next/email-link-auth/auth_email_link_reauth.js b/snippets/auth-next/email-link-auth/auth_email_link_reauth.js index 128650cb..ffe4480c 100644 --- a/snippets/auth-next/email-link-auth/auth_email_link_reauth.js +++ b/snippets/auth-next/email-link-auth/auth_email_link_reauth.js @@ -13,12 +13,11 @@ const credential = EmailAuthProvider.credentialWithLink( // Re-authenticate the user with this credential. const auth = getAuth(); -reauthenticateWithCredential(auth.currentUser, credential) - .then((usercred) => { - // The user is now successfully re-authenticated and can execute sensitive - // operations. - }) - .catch((error) => { - // Some error occurred. - }); +try { + const usercred = await reauthenticateWithCredential(auth.currentUser, credential); + // The user is now successfully re-authenticated and can execute sensitive + // operations. +} catch (error) { + // Some error occurred. +} // [END auth_email_link_reauth_modular] \ No newline at end of file diff --git a/snippets/auth-next/email-link-auth/auth_email_link_send.js b/snippets/auth-next/email-link-auth/auth_email_link_send.js index 5b97d87f..72101014 100644 --- a/snippets/auth-next/email-link-auth/auth_email_link_send.js +++ b/snippets/auth-next/email-link-auth/auth_email_link_send.js @@ -8,17 +8,16 @@ import { getAuth, sendSignInLinkToEmail } from "firebase/auth"; const auth = getAuth(); -sendSignInLinkToEmail(auth, email, actionCodeSettings) - .then(() => { - // The link was successfully sent. Inform the user. - // Save the email locally so you don't need to ask the user for it again - // if they open the link on the same device. - window.localStorage.setItem('emailForSignIn', email); - // ... - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // ... - }); +try { + await sendSignInLinkToEmail(auth, email, actionCodeSettings); + // The link was successfully sent. Inform the user. + // Save the email locally so you don't need to ask the user for it again + // if they open the link on the same device. + window.localStorage.setItem('emailForSignIn', email); + // ... +} catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // ... +} // [END auth_email_link_send_modular] \ No newline at end of file diff --git a/snippets/auth-next/email-link-auth/email_link_complete.js b/snippets/auth-next/email-link-auth/email_link_complete.js index dbe1143d..2f329009 100644 --- a/snippets/auth-next/email-link-auth/email_link_complete.js +++ b/snippets/auth-next/email-link-auth/email_link_complete.js @@ -21,22 +21,21 @@ if (isSignInWithEmailLink(auth, window.location.href)) { // attacks, ask the user to provide the associated email again. For example: email = window.prompt('Please provide your email for confirmation'); } - // The client SDK will parse the code from the link for you. - signInWithEmailLink(auth, email, window.location.href) - .then((result) => { - // Clear email from storage. - window.localStorage.removeItem('emailForSignIn'); - // You can access the new user by importing getAdditionalUserInfo - // and calling it with result: - // getAdditionalUserInfo(result) - // You can access the user's profile via: - // getAdditionalUserInfo(result)?.profile - // You can check if the user is new or existing: - // getAdditionalUserInfo(result)?.isNewUser - }) - .catch((error) => { - // Some error occurred, you can inspect the code: error.code - // Common errors could be invalid email and invalid or expired OTPs. - }); + try { + // The client SDK will parse the code from the link for you. + const result = await signInWithEmailLink(auth, email, window.location.href); + // Clear email from storage. + window.localStorage.removeItem('emailForSignIn'); + // You can access the new user by importing getAdditionalUserInfo + // and calling it with result: + // getAdditionalUserInfo(result) + // You can access the user's profile via: + // getAdditionalUserInfo(result)?.profile + // You can check if the user is new or existing: + // getAdditionalUserInfo(result)?.isNewUser + } catch (error) { + // Some error occurred, you can inspect the code: error.code + // Common errors could be invalid email and invalid or expired OTPs. + } } // [END email_link_complete_modular] \ No newline at end of file diff --git a/snippets/auth-next/email-link-auth/email_link_diferentiate.js b/snippets/auth-next/email-link-auth/email_link_diferentiate.js index 4fc06b41..846a0938 100644 --- a/snippets/auth-next/email-link-auth/email_link_diferentiate.js +++ b/snippets/auth-next/email-link-auth/email_link_diferentiate.js @@ -5,28 +5,27 @@ // 'npm run snippets'. // [START email_link_diferentiate_modular] -import { getAuth, fetchSignInMethodsForEmail, EmailAuthProvider} from "firebase/auth"; +import { getAuth, fetchSignInMethodsForEmail, EmailAuthProvider } from "firebase/auth"; // After asking the user for their email. const email = window.prompt('Please provide your email'); const auth = getAuth(); -fetchSignInMethodsForEmail(auth, email) - .then((signInMethods) => { - // This returns the same array as fetchProvidersForEmail but for email - // provider identified by 'password' string, signInMethods would contain 2 - // different strings: - // 'emailLink' if the user previously signed in with an email/link - // 'password' if the user has a password. - // A user could have both. - if (signInMethods.indexOf(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) != -1) { - // User can sign in with email/password. - } - if (signInMethods.indexOf(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD) != -1) { - // User can sign in with email/link. - } - }) - .catch((error) => { - // Some error occurred, you can inspect the code: error.code - }); +try { + const signInMethods = await fetchSignInMethodsForEmail(auth, email); + // This returns the same array as fetchProvidersForEmail but for email + // provider identified by 'password' string, signInMethods would contain 2 + // different strings: + // 'emailLink' if the user previously signed in with an email/link + // 'password' if the user has a password. + // A user could have both. + if (signInMethods.indexOf(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) != -1) { + // User can sign in with email/password. + } + if (signInMethods.indexOf(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD) != -1) { + // User can sign in with email/link. + } +} catch (error) { + // Some error occurred, you can inspect the code: error.code +} // [END email_link_diferentiate_modular] \ No newline at end of file From 9cbfd316b93cb52a3117650e2fbd9516177db928 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:28:40 +0000 Subject: [PATCH 06/15] Update auth-next/anonymous.js --- auth-next/anonymous.js | 19 +++++++++---------- .../auth-next/anonymous/auth_anon_sign_in.js | 17 ++++++++--------- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/auth-next/anonymous.js b/auth-next/anonymous.js index 33d5a936..fdf19525 100644 --- a/auth-next/anonymous.js +++ b/auth-next/anonymous.js @@ -1,19 +1,18 @@ // [SNIPPET_REGISTRY disabled] // [SNIPPETS_SEPARATION enabled] -function anonSignIn() { +async function anonSignIn() { // [START auth_anon_sign_in] const { getAuth, signInAnonymously } = require("firebase/auth"); const auth = getAuth(); - signInAnonymously(auth) - .then(() => { - // Signed in.. - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // ... - }); + try { + await signInAnonymously(auth); + // Signed in.. + } catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // ... + } // [END auth_anon_sign_in] } diff --git a/snippets/auth-next/anonymous/auth_anon_sign_in.js b/snippets/auth-next/anonymous/auth_anon_sign_in.js index 3db81772..fac2385c 100644 --- a/snippets/auth-next/anonymous/auth_anon_sign_in.js +++ b/snippets/auth-next/anonymous/auth_anon_sign_in.js @@ -8,13 +8,12 @@ import { getAuth, signInAnonymously } from "firebase/auth"; const auth = getAuth(); -signInAnonymously(auth) - .then(() => { - // Signed in.. - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // ... - }); +try { + await signInAnonymously(auth); + // Signed in.. +} catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // ... +} // [END auth_anon_sign_in_modular] \ No newline at end of file From 55954d30133d423f9d482ebea96925f61d2a5aa8 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:33:39 +0000 Subject: [PATCH 07/15] Update auth-next/oidc.js --- auth-next/oidc.js | 106 +++++++++--------- .../oidc/auth_oidc_direct_sign_in.js | 33 +++--- .../auth-next/oidc/auth_oidc_signin_popup.js | 32 +++--- .../oidc/auth_oidc_signin_redirect_result.js | 33 +++--- 4 files changed, 100 insertions(+), 104 deletions(-) diff --git a/auth-next/oidc.js b/auth-next/oidc.js index dae69fe9..7e0570c1 100644 --- a/auth-next/oidc.js +++ b/auth-next/oidc.js @@ -9,27 +9,27 @@ function oidcProvider() { // [END auth_oidc_provider_create] } -function oidcSignInPopup(provider) { +async function oidcSignInPopup(provider) { // [START auth_oidc_signin_popup] const { getAuth, signInWithPopup, OAuthProvider } = require("firebase/auth"); const auth = getAuth(); - signInWithPopup(auth, provider) - .then((result) => { - // User is signed in. - const credential = OAuthProvider.credentialFromResult(result); - // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider - }).catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = OAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); + try { + const result = await signInWithPopup(auth, provider); + // User is signed in. + const credential = OAuthProvider.credentialFromResult(result); + // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider + } catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = OAuthProvider.credentialFromError(error); + // Handle / display error. + // ... + } // [END auth_oidc_signin_popup] } @@ -42,32 +42,31 @@ function oidcSignInRedirect(provider) { // [END auth_oidc_signin_redirect] } -function oidcSignInRedirectResult(provider) { +async function oidcSignInRedirectResult(provider) { // [START auth_oidc_signin_redirect_result] const { getAuth, getRedirectResult, OAuthProvider } = require("firebase/auth"); const auth = getAuth(); - getRedirectResult(auth) - .then((result) => { - // User is signed in. - const credential = OAuthProvider.credentialFromResult(result); - // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = OAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); + try { + const result = await getRedirectResult(auth); + // User is signed in. + const credential = OAuthProvider.credentialFromResult(result); + // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider + } catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = OAuthProvider.credentialFromError(error); + // Handle / display error. + // ... + } // [END auth_oidc_signin_redirect_result] } -function oidcDirectSignIn(provider, oidcIdToken) { +async function oidcDirectSignIn(provider, oidcIdToken) { // [START auth_oidc_direct_sign_in] const { getAuth, OAuthProvider, signInWithCredential } = require("firebase/auth"); @@ -75,22 +74,21 @@ function oidcDirectSignIn(provider, oidcIdToken) { const credential = provider.credential({ idToken: oidcIdToken, }); - signInWithCredential(auth, credential) - .then((result) => { - // User is signed in. - const newCredential = OAuthProvider.credentialFromResult(result); - // This gives you a new access token for the OIDC provider. You can use it to directly interact with that provider. - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = OAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); + try { + const result = await signInWithCredential(auth, credential); + // User is signed in. + const newCredential = OAuthProvider.credentialFromResult(result); + // This gives you a new access token for the OIDC provider. You can use it to directly interact with that provider. + } catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = OAuthProvider.credentialFromError(error); + // Handle / display error. + // ... + } // [END auth_oidc_direct_sign_in] -} \ No newline at end of file +} diff --git a/snippets/auth-next/oidc/auth_oidc_direct_sign_in.js b/snippets/auth-next/oidc/auth_oidc_direct_sign_in.js index 558fd915..275dc9ca 100644 --- a/snippets/auth-next/oidc/auth_oidc_direct_sign_in.js +++ b/snippets/auth-next/oidc/auth_oidc_direct_sign_in.js @@ -11,21 +11,20 @@ const auth = getAuth(); const credential = provider.credential({ idToken: oidcIdToken, }); -signInWithCredential(auth, credential) - .then((result) => { - // User is signed in. - const newCredential = OAuthProvider.credentialFromResult(result); - // This gives you a new access token for the OIDC provider. You can use it to directly interact with that provider. - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = OAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); +try { + const result = await signInWithCredential(auth, credential); + // User is signed in. + const newCredential = OAuthProvider.credentialFromResult(result); + // This gives you a new access token for the OIDC provider. You can use it to directly interact with that provider. +} catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = OAuthProvider.credentialFromError(error); + // Handle / display error. + // ... +} // [END auth_oidc_direct_sign_in_modular] \ No newline at end of file diff --git a/snippets/auth-next/oidc/auth_oidc_signin_popup.js b/snippets/auth-next/oidc/auth_oidc_signin_popup.js index 130d617e..8df18762 100644 --- a/snippets/auth-next/oidc/auth_oidc_signin_popup.js +++ b/snippets/auth-next/oidc/auth_oidc_signin_popup.js @@ -8,20 +8,20 @@ import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth"; const auth = getAuth(); -signInWithPopup(auth, provider) - .then((result) => { - // User is signed in. - const credential = OAuthProvider.credentialFromResult(result); - // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider - }).catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = OAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); +try { + const result = await signInWithPopup(auth, provider); + // User is signed in. + const credential = OAuthProvider.credentialFromResult(result); + // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider +} catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = OAuthProvider.credentialFromError(error); + // Handle / display error. + // ... +} // [END auth_oidc_signin_popup_modular] \ No newline at end of file diff --git a/snippets/auth-next/oidc/auth_oidc_signin_redirect_result.js b/snippets/auth-next/oidc/auth_oidc_signin_redirect_result.js index bc76a620..30008af9 100644 --- a/snippets/auth-next/oidc/auth_oidc_signin_redirect_result.js +++ b/snippets/auth-next/oidc/auth_oidc_signin_redirect_result.js @@ -8,21 +8,20 @@ import { getAuth, getRedirectResult, OAuthProvider } from "firebase/auth"; const auth = getAuth(); -getRedirectResult(auth) - .then((result) => { - // User is signed in. - const credential = OAuthProvider.credentialFromResult(result); - // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = OAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); +try { + const result = await getRedirectResult(auth); + // User is signed in. + const credential = OAuthProvider.credentialFromResult(result); + // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider +} catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = OAuthProvider.credentialFromError(error); + // Handle / display error. + // ... +} // [END auth_oidc_signin_redirect_result_modular] \ No newline at end of file From 400528d6f0fefde057e9e5ff04fd2a68c8845362 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:35:59 +0000 Subject: [PATCH 08/15] Update auth-next/auth-state-persistence.js --- auth-next/auth-state-persistence.js | 56 +++++++++---------- .../auth_set_persistence_none.js | 25 ++++----- .../auth_set_persistence_session.js | 27 +++++---- 3 files changed, 52 insertions(+), 56 deletions(-) diff --git a/auth-next/auth-state-persistence.js b/auth-next/auth-state-persistence.js index 2d36c429..cb5d86dc 100644 --- a/auth-next/auth-state-persistence.js +++ b/auth-next/auth-state-persistence.js @@ -1,7 +1,7 @@ // [SNIPPET_REGISTRY disabled] // [SNIPPETS_SEPARATION enabled] -function setPersistenceSession() { +async function setPersistenceSession() { const email = "..."; const password = "..."; @@ -9,40 +9,38 @@ function setPersistenceSession() { const { getAuth, setPersistence, signInWithEmailAndPassword, browserSessionPersistence } = require("firebase/auth"); const auth = getAuth(); - setPersistence(auth, browserSessionPersistence) - .then(() => { - // Existing and future Auth states are now persisted in the current - // session only. Closing the window would clear any existing state even - // if a user forgets to sign out. - // ... - // New sign-in will be persisted with session persistence. - return signInWithEmailAndPassword(auth, email, password); - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - }); + try { + await setPersistence(auth, browserSessionPersistence); + // Existing and future Auth states are now persisted in the current + // session only. Closing the window would clear any existing state even + // if a user forgets to sign out. + // ... + // New sign-in will be persisted with session persistence. + return signInWithEmailAndPassword(auth, email, password); + } catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + } // [END auth_set_persistence_session] } -function setPersistenceNone() { +async function setPersistenceNone() { // [START auth_set_persistence_none] const { getAuth, setPersistence, signInWithRedirect, inMemoryPersistence, GoogleAuthProvider } = require("firebase/auth"); const auth = getAuth(); - setPersistence(auth, inMemoryPersistence) - .then(() => { - const provider = new GoogleAuthProvider(); - // In memory persistence will be applied to the signed in Google user - // even though the persistence was set to 'none' and a page redirect - // occurred. - return signInWithRedirect(auth, provider); - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - }); + try { + await setPersistence(auth, inMemoryPersistence); + const provider = new GoogleAuthProvider(); + // In memory persistence will be applied to the signed in Google user + // even though the persistence was set to 'none' and a page redirect + // occurred. + return signInWithRedirect(auth, provider); + } catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + } // [END auth_set_persistence_none] } diff --git a/snippets/auth-next/auth-state-persistence/auth_set_persistence_none.js b/snippets/auth-next/auth-state-persistence/auth_set_persistence_none.js index 5224cc21..1abe2b0c 100644 --- a/snippets/auth-next/auth-state-persistence/auth_set_persistence_none.js +++ b/snippets/auth-next/auth-state-persistence/auth_set_persistence_none.js @@ -8,17 +8,16 @@ import { getAuth, setPersistence, signInWithRedirect, inMemoryPersistence, GoogleAuthProvider } from "firebase/auth"; const auth = getAuth(); -setPersistence(auth, inMemoryPersistence) - .then(() => { - const provider = new GoogleAuthProvider(); - // In memory persistence will be applied to the signed in Google user - // even though the persistence was set to 'none' and a page redirect - // occurred. - return signInWithRedirect(auth, provider); - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - }); +try { + await setPersistence(auth, inMemoryPersistence); + const provider = new GoogleAuthProvider(); + // In memory persistence will be applied to the signed in Google user + // even though the persistence was set to 'none' and a page redirect + // occurred. + return signInWithRedirect(auth, provider); +} catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; +} // [END auth_set_persistence_none_modular] \ No newline at end of file diff --git a/snippets/auth-next/auth-state-persistence/auth_set_persistence_session.js b/snippets/auth-next/auth-state-persistence/auth_set_persistence_session.js index d21183ff..0f2b6d57 100644 --- a/snippets/auth-next/auth-state-persistence/auth_set_persistence_session.js +++ b/snippets/auth-next/auth-state-persistence/auth_set_persistence_session.js @@ -8,18 +8,17 @@ import { getAuth, setPersistence, signInWithEmailAndPassword, browserSessionPersistence } from "firebase/auth"; const auth = getAuth(); -setPersistence(auth, browserSessionPersistence) - .then(() => { - // Existing and future Auth states are now persisted in the current - // session only. Closing the window would clear any existing state even - // if a user forgets to sign out. - // ... - // New sign-in will be persisted with session persistence. - return signInWithEmailAndPassword(auth, email, password); - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - }); +try { + await setPersistence(auth, browserSessionPersistence); + // Existing and future Auth states are now persisted in the current + // session only. Closing the window would clear any existing state even + // if a user forgets to sign out. + // ... + // New sign-in will be persisted with session persistence. + return signInWithEmailAndPassword(auth, email, password); +} catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; +} // [END auth_set_persistence_session_modular] \ No newline at end of file From c671730fd660d25d33a02ae47b554ea5f5f20103 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:36:57 +0000 Subject: [PATCH 09/15] Update auth-next/custom.js --- auth-next/custom.js | 23 +++++++++---------- .../auth-next/custom/auth_sign_in_custom.js | 21 ++++++++--------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/auth-next/custom.js b/auth-next/custom.js index 8975672e..aaed75e0 100644 --- a/auth-next/custom.js +++ b/auth-next/custom.js @@ -1,23 +1,22 @@ // [SNIPPET_REGISTRY disabled] // [SNIPPETS_SEPARATION enabled] -function signInCustom() { +async function signInCustom() { const token = "token123"; // [START auth_sign_in_custom] const { getAuth, signInWithCustomToken } = require("firebase/auth"); const auth = getAuth(); - signInWithCustomToken(auth, token) - .then((userCredential) => { - // Signed in - const user = userCredential.user; - // ... - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // ... - }); + try { + const userCredential = await signInWithCustomToken(auth, token); + // Signed in + const user = userCredential.user; + // ... + } catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // ... + } // [END auth_sign_in_custom] } diff --git a/snippets/auth-next/custom/auth_sign_in_custom.js b/snippets/auth-next/custom/auth_sign_in_custom.js index c345c0ce..3aa6bc54 100644 --- a/snippets/auth-next/custom/auth_sign_in_custom.js +++ b/snippets/auth-next/custom/auth_sign_in_custom.js @@ -8,15 +8,14 @@ import { getAuth, signInWithCustomToken } from "firebase/auth"; const auth = getAuth(); -signInWithCustomToken(auth, token) - .then((userCredential) => { - // Signed in - const user = userCredential.user; - // ... - }) - .catch((error) => { - const errorCode = error.code; - const errorMessage = error.message; - // ... - }); +try { + const userCredential = await signInWithCustomToken(auth, token); + // Signed in + const user = userCredential.user; + // ... +} catch (error) { + const errorCode = error.code; + const errorMessage = error.message; + // ... +} // [END auth_sign_in_custom_modular] \ No newline at end of file From 80f21150c2cf7092e08500b6d377d94bbda30057 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:50:14 +0000 Subject: [PATCH 10/15] Update auth-next/link-multiple-accounts.js --- auth-next/link-multiple-accounts.js | 173 +++++++++--------- .../account_exists_popup.js | 40 ++-- .../auth_anonymous_link.js | 14 +- .../auth_get_redirect_result.js | 7 +- .../auth_link_with_popup.js | 7 +- .../auth_link_with_redirect.js | 9 +- .../auth_merge_accounts.js | 7 +- .../auth_simple_link.js | 14 +- .../auth_unlink_provider.js | 7 +- 9 files changed, 144 insertions(+), 134 deletions(-) diff --git a/auth-next/link-multiple-accounts.js b/auth-next/link-multiple-accounts.js index 1938aafc..dbb269ee 100644 --- a/auth-next/link-multiple-accounts.js +++ b/auth-next/link-multiple-accounts.js @@ -1,9 +1,9 @@ // [SNIPPET_REGISTRY disabled] // [SNIPPETS_SEPARATION enabled] -const MyUserDataRepo = function() {}; +const MyUserDataRepo = function () { }; -MyUserDataRepo.prototype.merge = function(data1, data2) { +MyUserDataRepo.prototype.merge = function (data1, data2) { // TODO(you): How you implement this is specific to your application! return { ...data1, @@ -11,15 +11,15 @@ MyUserDataRepo.prototype.merge = function(data1, data2) { }; }; -MyUserDataRepo.prototype.set = function(user, data) { +MyUserDataRepo.prototype.set = function (user, data) { // TODO(you): How you implement this is specific to your application! }; -MyUserDataRepo.prototype.delete = function(user) { +MyUserDataRepo.prototype.delete = function (user) { // TODO(you): How you implement this is specific to your application! }; -MyUserDataRepo.prototype.get = function(user) { +MyUserDataRepo.prototype.get = function (user) { // TODO(you): How you implement this is specific to your application! return {}; }; @@ -35,82 +35,87 @@ function getProviders() { // [END auth_get_providers] } -function simpleLink(credential) { +async function simpleLink(credential) { // [START auth_simple_link] const { getAuth, linkWithCredential } = require("firebase/auth"); const auth = getAuth(); - linkWithCredential(auth.currentUser, credential) - .then((usercred) => { - const user = usercred.user; - console.log("Account linking success", user); - }).catch((error) => { - console.log("Account linking error", error); - }); + try { + const usercred = await linkWithCredential(auth.currentUser, credential); + const user = usercred.user; + console.log("Account linking success", user); + } catch (error) { + console.log("Account linking error", error); + } // [END auth_simple_link] } -function anonymousLink(credential) { +async function anonymousLink(credential) { // [START auth_anonymous_link] const { getAuth, linkWithCredential } = require("firebase/auth"); const auth = getAuth(); - linkWithCredential(auth.currentUser, credential) - .then((usercred) => { - const user = usercred.user; - console.log("Anonymous account successfully upgraded", user); - }).catch((error) => { - console.log("Error upgrading anonymous account", error); - }); + try { + const usercred = await linkWithCredential(auth.currentUser, credential); + const user = usercred.user; + console.log("Anonymous account successfully upgraded", user); + } catch (error) { + console.log("Error upgrading anonymous account", error); + } // [END auth_anonymous_link] } -function linkWithPopup() { +async function linkWithPopup() { // [START auth_link_with_popup] const { getAuth, linkWithPopup, GoogleAuthProvider } = require("firebase/auth"); const provider = new GoogleAuthProvider(); const auth = getAuth(); - linkWithPopup(auth.currentUser, provider).then((result) => { + try { + const result = await linkWithPopup(auth.currentUser, provider); // Accounts successfully linked. const credential = GoogleAuthProvider.credentialFromResult(result); const user = result.user; // ... - }).catch((error) => { + } catch (error) { // Handle Errors here. // ... - }); + } // [END auth_link_with_popup] } -function linkWithRedirect() { +async function linkWithRedirect() { // [START auth_link_with_redirect] const { getAuth, linkWithRedirect, GoogleAuthProvider } = require("firebase/auth"); const provider = new GoogleAuthProvider(); const auth = getAuth(); - linkWithRedirect(auth.currentUser, provider) - .then(/* ... */) - .catch(/* ... */); + try { + await linkWithRedirect(auth.currentUser, provider); + /* ... */ + } catch (error) { + /* ... */ + } // [END auth_link_with_redirect] // [START auth_get_redirect_result] const { getRedirectResult } = require("firebase/auth"); - getRedirectResult(auth).then((result) => { + try { + const result = await getRedirectResult(auth); const credential = GoogleAuthProvider.credentialFromResult(result); if (credential) { // Accounts successfully linked. const user = result.user; // ... } - }).catch((error) => { + } catch (error) { // Handle Errors here. // ... - }); + } // [END auth_get_redirect_result] } -function mergeAccounts(newCredential) { +async function mergeAccounts(newCredential) { // [START auth_merge_accounts] const { getAuth, signInWithCredential, linkWithCredential, OAuthProvider } = require("firebase/auth"); @@ -129,7 +134,8 @@ function mergeAccounts(newCredential) { repo.delete(prevUser); // Sign in user with the account you want to link to - signInWithCredential(auth, newCredential).then((result) => { + try { + const result = await signInWithCredential(auth, newCredential); console.log("Sign In Success", result); const currentUser = result.user; const currentUserData = repo.get(currentUser); @@ -149,11 +155,11 @@ function mergeAccounts(newCredential) { // Save the merged data to the new user repo.set(signInResult.user, mergedData); }); - }).catch((error) => { + } catch (error) { // If there are errors we want to undo the data merge/deletion console.log("Sign In Error", error); repo.set(prevUser, prevUserData); - }); + } // [END auth_merge_accounts] } @@ -168,75 +174,74 @@ function makeEmailCredential() { // [END auth_make_email_credential] } -function unlink(providerId) { +async function unlink(providerId) { // [START auth_unlink_provider] const { getAuth, unlink } = require("firebase/auth"); const auth = getAuth(); - unlink(auth.currentUser, providerId).then(() => { + try { + await unlink(auth.currentUser, providerId); // Auth provider unlinked from account // ... - }).catch((error) => { + } catch (error) { // An error happened // ... - }); + } // [END auth_unlink_provider] } -function accountExistsPopup(auth, facebookProvider, goToApp, promptUserForPassword, promptUserForSignInMethod, getProviderForProviderId) { +async function accountExistsPopup(auth, facebookProvider, goToApp, promptUserForPassword, promptUserForSignInMethod, getProviderForProviderId) { // [START account_exists_popup] const { signInWithPopup, signInWithEmailAndPassword, linkWithCredential } = require("firebase/auth"); - // User tries to sign in with Facebook. - signInWithPopup(auth, facebookProvider).catch((error) => { - // User's email already exists. - if (error.code === 'auth/account-exists-with-different-credential') { - // The pending Facebook credential. - const pendingCred = error.credential; - // The provider account's email address. - const email = error.customData.email; - - // Present the user with a list of providers they might have - // used to create the original account. - // Then, ask the user to sign in with the existing provider. - const method = promptUserForSignInMethod(); - - if (method === 'password') { - // TODO: Ask the user for their password. - // In real scenario, you should handle this asynchronously. - const password = promptUserForPassword(); - signInWithEmailAndPassword(auth, email, password).then((result) => { - return linkWithCredential(result.user, pendingCred); - }).then(() => { + try { + // User tries to sign in with Facebook. + await signInWithPopup(auth, facebookProvider); + } catch (error) { + // User's email already exists. + if (error.code === 'auth/account-exists-with-different-credential') { + // The pending Facebook credential. + const pendingCred = error.credential; + // The provider account's email address. + const email = error.customData.email; + + // Present the user with a list of providers they might have + // used to create the original account. + // Then, ask the user to sign in with the existing provider. + const method = promptUserForSignInMethod(); + + if (method === 'password') { + // TODO: Ask the user for their password. + // In real scenario, you should handle this asynchronously. + const password = promptUserForPassword(); + const result = signInWithEmailAndPassword(auth, email, password); + await linkWithCredential(result.user, pendingCred); // Facebook account successfully linked to the existing user. goToApp(); - }); - return; - } - - // All other cases are external providers. - // Construct provider object for that provider. - // TODO: Implement getProviderForProviderId. - const provider = getProviderForProviderId(method); - // At this point, you should let the user know that they already have an - // account with a different provider, and validate they want to sign in - // with the new provider. - // Note: Browsers usually block popups triggered asynchronously, so in - // real app, you should ask the user to click on a "Continue" button - // that will trigger signInWithPopup(). - signInWithPopup(auth, provider).then((result) => { + return; + } + + // All other cases are external providers. + // Construct provider object for that provider. + // TODO: Implement getProviderForProviderId. + const provider = getProviderForProviderId(method); + // At this point, you should let the user know that they already have an + // account with a different provider, and validate they want to sign in + // with the new provider. + // Note: Browsers usually block popups triggered asynchronously, so in + // real app, you should ask the user to click on a "Continue" button + // that will trigger signInWithPopup(). + const result = await signInWithPopup(auth, provider); // Note: Identity Platform doesn't control the provider's sign-in // flow, so it's possible for the user to sign in with an account // with a different email from the first one. // Link the Facebook credential. We have access to the pending // credential, so we can directly call the link method. - linkWithCredential(result.user, pendingCred).then((userCred) => { - // Success. - goToApp(); - }); - }); + const userCred = await linkWithCredential(result.user, pendingCred); + // Success. + goToApp(); + } } -}); -// [END account_exists_popup] + // [END account_exists_popup] } diff --git a/snippets/auth-next/link-multiple-accounts/account_exists_popup.js b/snippets/auth-next/link-multiple-accounts/account_exists_popup.js index 2c667882..4e03b824 100644 --- a/snippets/auth-next/link-multiple-accounts/account_exists_popup.js +++ b/snippets/auth-next/link-multiple-accounts/account_exists_popup.js @@ -4,11 +4,13 @@ // To update the snippets in this file, edit the source and then run // 'npm run snippets'. - // [START account_exists_popup_modular] - import { signInWithPopup, signInWithEmailAndPassword, linkWithCredential } from "firebase/auth"; +// [START account_exists_popup_modular] +import { signInWithPopup, signInWithEmailAndPassword, linkWithCredential } from "firebase/auth"; +try { // User tries to sign in with Facebook. - signInWithPopup(auth, facebookProvider).catch((error) => { + await signInWithPopup(auth, facebookProvider); +} catch (error) { // User's email already exists. if (error.code === 'auth/account-exists-with-different-credential') { // The pending Facebook credential. @@ -25,12 +27,10 @@ // TODO: Ask the user for their password. // In real scenario, you should handle this asynchronously. const password = promptUserForPassword(); - signInWithEmailAndPassword(auth, email, password).then((result) => { - return linkWithCredential(result.user, pendingCred); - }).then(() => { - // Facebook account successfully linked to the existing user. - goToApp(); - }); + const result = signInWithEmailAndPassword(auth, email, password); + await linkWithCredential(result.user, pendingCred); + // Facebook account successfully linked to the existing user. + goToApp(); return; } @@ -44,18 +44,16 @@ // Note: Browsers usually block popups triggered asynchronously, so in // real app, you should ask the user to click on a "Continue" button // that will trigger signInWithPopup(). - signInWithPopup(auth, provider).then((result) => { - // Note: Identity Platform doesn't control the provider's sign-in - // flow, so it's possible for the user to sign in with an account - // with a different email from the first one. + const result = await signInWithPopup(auth, provider); + // Note: Identity Platform doesn't control the provider's sign-in + // flow, so it's possible for the user to sign in with an account + // with a different email from the first one. - // Link the Facebook credential. We have access to the pending - // credential, so we can directly call the link method. - linkWithCredential(result.user, pendingCred).then((userCred) => { - // Success. - goToApp(); - }); - }); + // Link the Facebook credential. We have access to the pending + // credential, so we can directly call the link method. + const userCred = await linkWithCredential(result.user, pendingCred); + // Success. + goToApp(); } -}); +} // [END account_exists_popup_modular] \ No newline at end of file diff --git a/snippets/auth-next/link-multiple-accounts/auth_anonymous_link.js b/snippets/auth-next/link-multiple-accounts/auth_anonymous_link.js index 3bf9ab56..d8bac539 100644 --- a/snippets/auth-next/link-multiple-accounts/auth_anonymous_link.js +++ b/snippets/auth-next/link-multiple-accounts/auth_anonymous_link.js @@ -8,11 +8,11 @@ import { getAuth, linkWithCredential } from "firebase/auth"; const auth = getAuth(); -linkWithCredential(auth.currentUser, credential) - .then((usercred) => { - const user = usercred.user; - console.log("Anonymous account successfully upgraded", user); - }).catch((error) => { - console.log("Error upgrading anonymous account", error); - }); +try { + const usercred = await linkWithCredential(auth.currentUser, credential); + const user = usercred.user; + console.log("Anonymous account successfully upgraded", user); +} catch (error) { + console.log("Error upgrading anonymous account", error); +} // [END auth_anonymous_link_modular] \ No newline at end of file diff --git a/snippets/auth-next/link-multiple-accounts/auth_get_redirect_result.js b/snippets/auth-next/link-multiple-accounts/auth_get_redirect_result.js index 1608a933..82ba9e2c 100644 --- a/snippets/auth-next/link-multiple-accounts/auth_get_redirect_result.js +++ b/snippets/auth-next/link-multiple-accounts/auth_get_redirect_result.js @@ -6,15 +6,16 @@ // [START auth_get_redirect_result_modular] import { getRedirectResult } from "firebase/auth"; -getRedirectResult(auth).then((result) => { +try { + const result = await getRedirectResult(auth); const credential = GoogleAuthProvider.credentialFromResult(result); if (credential) { // Accounts successfully linked. const user = result.user; // ... } -}).catch((error) => { +} catch (error) { // Handle Errors here. // ... -}); +} // [END auth_get_redirect_result_modular] \ No newline at end of file diff --git a/snippets/auth-next/link-multiple-accounts/auth_link_with_popup.js b/snippets/auth-next/link-multiple-accounts/auth_link_with_popup.js index b6619cad..5414614e 100644 --- a/snippets/auth-next/link-multiple-accounts/auth_link_with_popup.js +++ b/snippets/auth-next/link-multiple-accounts/auth_link_with_popup.js @@ -9,13 +9,14 @@ import { getAuth, linkWithPopup, GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider(); const auth = getAuth(); -linkWithPopup(auth.currentUser, provider).then((result) => { +try { + const result = await linkWithPopup(auth.currentUser, provider); // Accounts successfully linked. const credential = GoogleAuthProvider.credentialFromResult(result); const user = result.user; // ... -}).catch((error) => { +} catch (error) { // Handle Errors here. // ... -}); +} // [END auth_link_with_popup_modular] \ No newline at end of file diff --git a/snippets/auth-next/link-multiple-accounts/auth_link_with_redirect.js b/snippets/auth-next/link-multiple-accounts/auth_link_with_redirect.js index 1e496f42..6a583807 100644 --- a/snippets/auth-next/link-multiple-accounts/auth_link_with_redirect.js +++ b/snippets/auth-next/link-multiple-accounts/auth_link_with_redirect.js @@ -9,7 +9,10 @@ import { getAuth, linkWithRedirect, GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider(); const auth = getAuth(); -linkWithRedirect(auth.currentUser, provider) - .then(/* ... */) - .catch(/* ... */); +try { + await linkWithRedirect(auth.currentUser, provider); + /* ... */ +} catch (error) { + /* ... */ +} // [END auth_link_with_redirect_modular] \ No newline at end of file diff --git a/snippets/auth-next/link-multiple-accounts/auth_merge_accounts.js b/snippets/auth-next/link-multiple-accounts/auth_merge_accounts.js index f7cc113c..2fbb8f18 100644 --- a/snippets/auth-next/link-multiple-accounts/auth_merge_accounts.js +++ b/snippets/auth-next/link-multiple-accounts/auth_merge_accounts.js @@ -22,7 +22,8 @@ const prevUserData = repo.get(prevUser); repo.delete(prevUser); // Sign in user with the account you want to link to -signInWithCredential(auth, newCredential).then((result) => { +try { + const result = await signInWithCredential(auth, newCredential); console.log("Sign In Success", result); const currentUser = result.user; const currentUserData = repo.get(currentUser); @@ -42,9 +43,9 @@ signInWithCredential(auth, newCredential).then((result) => { // Save the merged data to the new user repo.set(signInResult.user, mergedData); }); -}).catch((error) => { +} catch (error) { // If there are errors we want to undo the data merge/deletion console.log("Sign In Error", error); repo.set(prevUser, prevUserData); -}); +} // [END auth_merge_accounts_modular] \ No newline at end of file diff --git a/snippets/auth-next/link-multiple-accounts/auth_simple_link.js b/snippets/auth-next/link-multiple-accounts/auth_simple_link.js index 15c434a2..75c02009 100644 --- a/snippets/auth-next/link-multiple-accounts/auth_simple_link.js +++ b/snippets/auth-next/link-multiple-accounts/auth_simple_link.js @@ -8,11 +8,11 @@ import { getAuth, linkWithCredential } from "firebase/auth"; const auth = getAuth(); -linkWithCredential(auth.currentUser, credential) - .then((usercred) => { - const user = usercred.user; - console.log("Account linking success", user); - }).catch((error) => { - console.log("Account linking error", error); - }); +try { + const usercred = await linkWithCredential(auth.currentUser, credential); + const user = usercred.user; + console.log("Account linking success", user); +} catch (error) { + console.log("Account linking error", error); +} // [END auth_simple_link_modular] \ No newline at end of file diff --git a/snippets/auth-next/link-multiple-accounts/auth_unlink_provider.js b/snippets/auth-next/link-multiple-accounts/auth_unlink_provider.js index 46617b26..7e881f28 100644 --- a/snippets/auth-next/link-multiple-accounts/auth_unlink_provider.js +++ b/snippets/auth-next/link-multiple-accounts/auth_unlink_provider.js @@ -8,11 +8,12 @@ import { getAuth, unlink } from "firebase/auth"; const auth = getAuth(); -unlink(auth.currentUser, providerId).then(() => { +try { + await unlink(auth.currentUser, providerId); // Auth provider unlinked from account // ... -}).catch((error) => { +} catch (error) { // An error happened // ... -}); +} // [END auth_unlink_provider_modular] \ No newline at end of file From 4c4ed91620d1ab85564b98c1a6ef9b853f413217 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:51:45 +0000 Subject: [PATCH 11/15] Update auth-next/phone-auth.js --- auth-next/phone-auth.js | 22 +++++++++---------- .../auth-next/phone-auth/auth_phone_signin.js | 20 ++++++++--------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/auth-next/phone-auth.js b/auth-next/phone-auth.js index 99492f99..5bba7e9a 100644 --- a/auth-next/phone-auth.js +++ b/auth-next/phone-auth.js @@ -66,7 +66,7 @@ function recaptchaRender() { // [END auth_phone_recaptcha_render] } -function phoneSignIn() { +async function phoneSignIn() { function getPhoneNumberFromUserInput() { return "+15558675309"; } @@ -78,16 +78,16 @@ function phoneSignIn() { const appVerifier = window.recaptchaVerifier; const auth = getAuth(); - signInWithPhoneNumber(auth, phoneNumber, appVerifier) - .then((confirmationResult) => { - // SMS sent. Prompt user to type the code from the message, then sign the - // user in with confirmationResult.confirm(code). - window.confirmationResult = confirmationResult; - // ... - }).catch((error) => { - // Error; SMS not sent - // ... - }); + try { + const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, appVerifier); + // SMS sent. Prompt user to type the code from the message, then sign the + // user in with confirmationResult.confirm(code). + window.confirmationResult = confirmationResult; + // ... + } catch (error) { + // Error; SMS not sent + // ... + } // [END auth_phone_signin] } diff --git a/snippets/auth-next/phone-auth/auth_phone_signin.js b/snippets/auth-next/phone-auth/auth_phone_signin.js index 31c3d248..9bb3a151 100644 --- a/snippets/auth-next/phone-auth/auth_phone_signin.js +++ b/snippets/auth-next/phone-auth/auth_phone_signin.js @@ -11,14 +11,14 @@ const phoneNumber = getPhoneNumberFromUserInput(); const appVerifier = window.recaptchaVerifier; const auth = getAuth(); -signInWithPhoneNumber(auth, phoneNumber, appVerifier) - .then((confirmationResult) => { - // SMS sent. Prompt user to type the code from the message, then sign the - // user in with confirmationResult.confirm(code). - window.confirmationResult = confirmationResult; - // ... - }).catch((error) => { - // Error; SMS not sent - // ... - }); +try { + const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, appVerifier); + // SMS sent. Prompt user to type the code from the message, then sign the + // user in with confirmationResult.confirm(code). + window.confirmationResult = confirmationResult; + // ... +} catch (error) { + // Error; SMS not sent + // ... +} // [END auth_phone_signin_modular] \ No newline at end of file From 429baff83c5e37b56f2797e88f49af2f873d12dc Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:54:47 +0000 Subject: [PATCH 12/15] Update auth-next/service-worker-sessions.js --- auth-next/service-worker-sessions.js | 46 +++++++++---------- .../auth_svc_get_idtoken.js | 13 +++--- .../auth_svc_intercept.js | 6 +-- .../auth_svc_register.js | 2 +- .../auth_svc_sign_in_email.js | 17 ++++--- 5 files changed, 40 insertions(+), 44 deletions(-) diff --git a/auth-next/service-worker-sessions.js b/auth-next/service-worker-sessions.js index abef386b..ee963d6d 100644 --- a/auth-next/service-worker-sessions.js +++ b/auth-next/service-worker-sessions.js @@ -3,18 +3,17 @@ // Docs: https://source.corp.google.com/piper///depot/google3/third_party/devsite/firebase/en/docs/auth/web/service-worker-sessions.md -function svcGetIdToken() { +async function svcGetIdToken() { // [START auth_svc_get_idtoken] const { getAuth, getIdToken } = require("firebase/auth"); const auth = getAuth(); - getIdToken(auth.currentUser) - .then((idToken) => { - // idToken can be passed back to server. - }) - .catch((error) => { - // Error occurred. - }); + try { + const idToken = await getIdToken(auth.currentUser); + // idToken can be passed back to server. + } catch (error) { + // Error occurred. + } // [END auth_svc_get_idtoken] } @@ -65,7 +64,7 @@ function svcIntercept() { const host = pathArray[2]; return protocol + '//' + host; }; - + // Get underlying body if available. Works for text and json bodies. const getBodyContent = (req) => { return Promise.resolve().then(() => { @@ -83,7 +82,7 @@ function svcIntercept() { // Ignore error. }); }; - + self.addEventListener('fetch', (event) => { /** @type {FetchEvent} */ const evt = event; @@ -93,9 +92,9 @@ function svcIntercept() { let processRequestPromise = Promise.resolve(); // For same origin https requests, append idToken to header. if (self.location.origin == getOriginFromUrl(evt.request.url) && - (self.location.protocol == 'https:' || - self.location.hostname == 'localhost') && - idToken) { + (self.location.protocol == 'https:' || + self.location.hostname == 'localhost') && + idToken) { // Clone headers as request headers are immutable. const headers = new Headers(); req.headers.forEach((val, key) => { @@ -147,25 +146,24 @@ function svcRegister() { // [START auth_svc_register] // Install servicerWorker if supported on sign-in/sign-up page. if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('/service-worker.js', {scope: '/'}); + navigator.serviceWorker.register('/service-worker.js', { scope: '/' }); } // [END auth_svc_register] } -function svcSignInEmail(email, password) { +async function svcSignInEmail(email, password) { // [START auth_svc_sign_in_email] const { getAuth, signInWithEmailAndPassword } = require("firebase/auth"); // Sign in screen. const auth = getAuth(); - signInWithEmailAndPassword(auth, email, password) - .then((result) => { - // Redirect to profile page after sign-in. The service worker will detect - // this and append the ID token to the header. - window.location.assign('/profile'); - }) - .catch((error) => { - // Error occurred. - }); + try { + const result = await signInWithEmailAndPassword(auth, email, password); + // Redirect to profile page after sign-in. The service worker will detect + // this and append the ID token to the header. + window.location.assign('/profile'); + } catch (error) { + // Error occurred. + } // [END auth_svc_sign_in_email] } diff --git a/snippets/auth-next/service-worker-sessions/auth_svc_get_idtoken.js b/snippets/auth-next/service-worker-sessions/auth_svc_get_idtoken.js index dd78ada8..2eb6a818 100644 --- a/snippets/auth-next/service-worker-sessions/auth_svc_get_idtoken.js +++ b/snippets/auth-next/service-worker-sessions/auth_svc_get_idtoken.js @@ -8,11 +8,10 @@ import { getAuth, getIdToken } from "firebase/auth"; const auth = getAuth(); -getIdToken(auth.currentUser) - .then((idToken) => { - // idToken can be passed back to server. - }) - .catch((error) => { - // Error occurred. - }); +try { + const idToken = await getIdToken(auth.currentUser); + // idToken can be passed back to server. +} catch (error) { + // Error occurred. +} // [END auth_svc_get_idtoken_modular] \ No newline at end of file diff --git a/snippets/auth-next/service-worker-sessions/auth_svc_intercept.js b/snippets/auth-next/service-worker-sessions/auth_svc_intercept.js index 419614ff..b201f5c3 100644 --- a/snippets/auth-next/service-worker-sessions/auth_svc_intercept.js +++ b/snippets/auth-next/service-worker-sessions/auth_svc_intercept.js @@ -40,9 +40,9 @@ self.addEventListener('fetch', (event) => { let processRequestPromise = Promise.resolve(); // For same origin https requests, append idToken to header. if (self.location.origin == getOriginFromUrl(evt.request.url) && - (self.location.protocol == 'https:' || - self.location.hostname == 'localhost') && - idToken) { + (self.location.protocol == 'https:' || + self.location.hostname == 'localhost') && + idToken) { // Clone headers as request headers are immutable. const headers = new Headers(); req.headers.forEach((val, key) => { diff --git a/snippets/auth-next/service-worker-sessions/auth_svc_register.js b/snippets/auth-next/service-worker-sessions/auth_svc_register.js index 0cb36be3..e260c864 100644 --- a/snippets/auth-next/service-worker-sessions/auth_svc_register.js +++ b/snippets/auth-next/service-worker-sessions/auth_svc_register.js @@ -7,6 +7,6 @@ // [START auth_svc_register_modular] // Install servicerWorker if supported on sign-in/sign-up page. if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('/service-worker.js', {scope: '/'}); + navigator.serviceWorker.register('/service-worker.js', { scope: '/' }); } // [END auth_svc_register_modular] \ No newline at end of file diff --git a/snippets/auth-next/service-worker-sessions/auth_svc_sign_in_email.js b/snippets/auth-next/service-worker-sessions/auth_svc_sign_in_email.js index 02e3a62a..cbaf045f 100644 --- a/snippets/auth-next/service-worker-sessions/auth_svc_sign_in_email.js +++ b/snippets/auth-next/service-worker-sessions/auth_svc_sign_in_email.js @@ -9,13 +9,12 @@ import { getAuth, signInWithEmailAndPassword } from "firebase/auth"; // Sign in screen. const auth = getAuth(); -signInWithEmailAndPassword(auth, email, password) - .then((result) => { - // Redirect to profile page after sign-in. The service worker will detect - // this and append the ID token to the header. - window.location.assign('/profile'); - }) - .catch((error) => { - // Error occurred. - }); +try { + const result = await signInWithEmailAndPassword(auth, email, password); + // Redirect to profile page after sign-in. The service worker will detect + // this and append the ID token to the header. + window.location.assign('/profile'); +} catch (error) { + // Error occurred. +} // [END auth_svc_sign_in_email_modular] \ No newline at end of file From 5dcd0b4d68737071a03737ac8a3b2aeea076e469 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 09:56:14 +0000 Subject: [PATCH 13/15] Update auth-next/saml.js --- auth-next/saml.js | 71 +++++++++---------- .../auth-next/saml/auth_saml_signin_popup.js | 32 ++++----- .../saml/auth_saml_signin_redirect_result.js | 33 +++++---- 3 files changed, 67 insertions(+), 69 deletions(-) diff --git a/auth-next/saml.js b/auth-next/saml.js index cdecce56..07dfd1c6 100644 --- a/auth-next/saml.js +++ b/auth-next/saml.js @@ -9,27 +9,27 @@ function samlProvider() { // [END auth_saml_provider_create] } -function samlSignInPopup(provider) { +async function samlSignInPopup(provider) { // [START auth_saml_signin_popup] const { getAuth, signInWithPopup, SAMLAuthProvider } = require("firebase/auth"); const auth = getAuth(); - signInWithPopup(auth, provider) - .then((result) => { - // User is signed in. - // Provider data available from the result.user.getIdToken() - // or from result.user.providerData - }).catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = SAMLAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); + try { + const result = await signInWithPopup(auth, provider); + // User is signed in. + // Provider data available from the result.user.getIdToken() + // or from result.user.providerData + } catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = SAMLAuthProvider.credentialFromError(error); + // Handle / display error. + // ... + } // [END auth_saml_signin_popup] } @@ -42,27 +42,26 @@ function samlSignInRedirect(provider) { // [END auth_saml_signin_redirect] } -function samlSignInRedirectResult(provider) { +async function samlSignInRedirectResult(provider) { // [START auth_saml_signin_redirect_result] const { getAuth, getRedirectResult, SAMLAuthProvider } = require("firebase/auth"); const auth = getAuth(); - getRedirectResult(auth) - .then((result) => { - // User is signed in. - // Provider data available from the result.user.getIdToken() - // or from result.user.providerData - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = SAMLAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); + try { + const result = await getRedirectResult(auth); + // User is signed in. + // Provider data available from the result.user.getIdToken() + // or from result.user.providerData + } catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = SAMLAuthProvider.credentialFromError(error); + // Handle / display error. + // ... + } // [END auth_saml_signin_redirect_result] -} \ No newline at end of file +} diff --git a/snippets/auth-next/saml/auth_saml_signin_popup.js b/snippets/auth-next/saml/auth_saml_signin_popup.js index 3a922a9a..b91e9e2d 100644 --- a/snippets/auth-next/saml/auth_saml_signin_popup.js +++ b/snippets/auth-next/saml/auth_saml_signin_popup.js @@ -8,20 +8,20 @@ import { getAuth, signInWithPopup, SAMLAuthProvider } from "firebase/auth"; const auth = getAuth(); -signInWithPopup(auth, provider) - .then((result) => { - // User is signed in. - // Provider data available from the result.user.getIdToken() - // or from result.user.providerData - }).catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = SAMLAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); +try { + const result = await signInWithPopup(auth, provider); + // User is signed in. + // Provider data available from the result.user.getIdToken() + // or from result.user.providerData +} catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = SAMLAuthProvider.credentialFromError(error); + // Handle / display error. + // ... +} // [END auth_saml_signin_popup_modular] \ No newline at end of file diff --git a/snippets/auth-next/saml/auth_saml_signin_redirect_result.js b/snippets/auth-next/saml/auth_saml_signin_redirect_result.js index e4bf73de..e7f030f2 100644 --- a/snippets/auth-next/saml/auth_saml_signin_redirect_result.js +++ b/snippets/auth-next/saml/auth_saml_signin_redirect_result.js @@ -8,21 +8,20 @@ import { getAuth, getRedirectResult, SAMLAuthProvider } from "firebase/auth"; const auth = getAuth(); -getRedirectResult(auth) - .then((result) => { - // User is signed in. - // Provider data available from the result.user.getIdToken() - // or from result.user.providerData - }) - .catch((error) => { - // Handle Errors here. - const errorCode = error.code; - const errorMessage = error.message; - // The email of the user's account used. - const email = error.customData.email; - // The AuthCredential type that was used. - const credential = SAMLAuthProvider.credentialFromError(error); - // Handle / display error. - // ... - }); +try { + const result = await getRedirectResult(auth); + // User is signed in. + // Provider data available from the result.user.getIdToken() + // or from result.user.providerData +} catch (error) { + // Handle Errors here. + const errorCode = error.code; + const errorMessage = error.message; + // The email of the user's account used. + const email = error.customData.email; + // The AuthCredential type that was used. + const credential = SAMLAuthProvider.credentialFromError(error); + // Handle / display error. + // ... +} // [END auth_saml_signin_redirect_result_modular] \ No newline at end of file From 44440f1f065f816d0c6fa73f788b05112b81568e Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 10:08:00 +0000 Subject: [PATCH 14/15] Update auth-next/multi-tenancy.js --- auth-next/multi-tenancy.js | 305 +++++++++--------- .../multitenant_account_exists_popup.js | 65 ++-- .../multitenant_account_exists_redirect.js | 27 +- .../multitenant_account_linking.js | 43 ++- .../multitenant_send_emaillink.js | 21 +- .../multitenant_signin_custom_token.js | 11 +- .../multitenant_signin_emaillink.js | 12 +- .../multitenant_signin_password.js | 16 +- .../multitenant_signin_password_demo.js | 18 +- .../multitenant_signin_saml_popup.js | 25 +- .../multitenant_signin_saml_redirect.js | 27 +- .../multitenant_signup_password.js | 16 +- 12 files changed, 286 insertions(+), 300 deletions(-) diff --git a/auth-next/multi-tenancy.js b/auth-next/multi-tenancy.js index d7577f34..abb50af4 100644 --- a/auth-next/multi-tenancy.js +++ b/auth-next/multi-tenancy.js @@ -38,23 +38,21 @@ function switchTenantMultiAuth(firebaseConfig1, firebaseConfig2) { // [END multitenant_switch_tenant_multiinstance] } -function passwordSignInWithTenantDemo(auth, email, password) { +async function passwordSignInWithTenantDemo(auth, email, password) { // [START multitenant_signin_password_demo] const { signInWithEmailAndPassword, onAuthStateChanged } = require("firebase/auth"); // Switch to TENANT_ID1 auth.tenantId = 'TENANT_ID1'; // Sign in with tenant - signInWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // User is signed in. - const user = userCredential.user; - // user.tenantId is set to 'TENANT_ID1'. - // Switch to 'TENANT_ID2'. - auth.tenantId = 'TENANT_ID2'; - // auth.currentUser still points to the user. - // auth.currentUser.tenantId is 'TENANT_ID1'. - }); + const userCredential = await signInWithEmailAndPassword(auth, email, password); + // User is signed in. + const user = userCredential.user; + // user.tenantId is set to 'TENANT_ID1'. + // Switch to 'TENANT_ID2'. + auth.tenantId = 'TENANT_ID2'; + // auth.currentUser still points to the user. + // auth.currentUser.tenantId is 'TENANT_ID1'. // You could also get the current user from Auth state observer. onAuthStateChanged(auth, (user) => { @@ -68,62 +66,61 @@ function passwordSignInWithTenantDemo(auth, email, password) { // [END multitenant_signin_password_demo] } -function signUpWithTenant(auth, email, password) { +async function signUpWithTenant(auth, email, password) { // [START multitenant_signup_password] const { createUserWithEmailAndPassword } = require("firebase/auth"); auth.tenantId = 'TENANT_ID'; - createUserWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // User is signed in. - // userCredential.user.tenantId is 'TENANT_ID'. - }).catch((error) => { - // Handle / display error. - // ... - }); + try { + const userCredential = await createUserWithEmailAndPassword(auth, email, password); + // User is signed in. + // userCredential.user.tenantId is 'TENANT_ID'. + } catch (error) { + // Handle / display error. + // ... + } // [END multitenant_signup_password] } -function passwordSignInWithTenant(auth, email, password) { +async function passwordSignInWithTenant(auth, email, password) { // [START multitenant_signin_password] const { signInWithEmailAndPassword } = require("firebase/auth"); auth.tenantId = 'TENANT_ID'; - signInWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // User is signed in. - // userCredential.user.tenantId is 'TENANT_ID'. - }).catch((error) => { - // Handle / display error. - // ... - }); + try { + const userCredential = await signInWithEmailAndPassword(auth, email, password); + // User is signed in. + // userCredential.user.tenantId is 'TENANT_ID'. + } catch (error) { + // Handle / display error. + // ... + } // [END multitenant_signin_password] } -function samlSignInPopupTenant(auth, provider) { +async function samlSignInPopupTenant(auth, provider) { // [START multitenant_signin_saml_popup] const { signInWithPopup } = require("firebase/auth"); // Switch to TENANT_ID1. auth.tenantId = 'TENANT_ID1'; - // Sign-in with popup. - signInWithPopup(auth, provider) - .then((userCredential) => { - // User is signed in. - const user = userCredential.user; - // user.tenantId is set to 'TENANT_ID1'. - // Provider data available from the result.user.getIdToken() - // or from result.user.providerData - }) - .catch((error) => { - // Handle / display error. - // ... - }); + try { + // Sign-in with popup. + const userCredential = await signInWithPopup(auth, provider); + // User is signed in. + const user = userCredential.user; + // user.tenantId is set to 'TENANT_ID1'. + // Provider data available from the result.user.getIdToken() + // or from result.user.providerData + } catch (error) { + // Handle / display error. + // ... + } // [END multitenant_signin_saml_popup] } -function samlSignInRedirectTenant(auth, provider) { +async function samlSignInRedirectTenant(auth, provider) { // [START multitenant_signin_saml_redirect] const { signInWithRedirect, getRedirectResult } = require("firebase/auth"); // Switch to TENANT_ID1. @@ -132,44 +129,42 @@ function samlSignInRedirectTenant(auth, provider) { // Sign-in with redirect. signInWithRedirect(auth, provider); - // After the user completes sign-in and returns to the app, you can get - // the sign-in result by calling getRedirectResult. However, if they sign out - // and sign in again with an IdP, no tenant is used. - getRedirectResult(auth) - .then((result) => { - // User is signed in. - // The tenant ID available in result.user.tenantId. - // Provider data available from the result.user.getIdToken() - // or from result.user.providerData - }) - .catch((error) => { - // Handle / display error. - // ... - }); + try { + // After the user completes sign-in and returns to the app, you can get + // the sign-in result by calling getRedirectResult. However, if they sign out + // and sign in again with an IdP, no tenant is used. + const result = await getRedirectResult(auth); + // User is signed in. + // The tenant ID available in result.user.tenantId. + // Provider data available from the result.user.getIdToken() + // or from result.user.providerData + } catch (error) { + // Handle / display error. + // ... + } // [END multitenant_signin_saml_redirect] } -function sendSignInLinkToEmailTenant(auth, email, actionCodeSettings) { +async function sendSignInLinkToEmailTenant(auth, email, actionCodeSettings) { // [START multitenant_send_emaillink] const { sendSignInLinkToEmail } = require("firebase/auth"); // Switch to TENANT_ID1 auth.tenantId = 'TENANT_ID1'; - sendSignInLinkToEmail(auth, email, actionCodeSettings) - .then(() => { - // The link was successfully sent. Inform the user. - // Save the email locally so you don't need to ask the user for it again - // if they open the link on the same device. - window.localStorage.setItem('emailForSignIn', email); - }) - .catch((error) => { - // Handle / display error. - // ... - }); + try { + await sendSignInLinkToEmail(auth, email, actionCodeSettings); + // The link was successfully sent. Inform the user. + // Save the email locally so you don't need to ask the user for it again + // if they open the link on the same device. + window.localStorage.setItem('emailForSignIn', email); + } catch (error) { + // Handle / display error. + // ... + } // [END multitenant_send_emaillink] } -function signInWithEmailLinkTenant(auth) { +async function signInWithEmailLinkTenant(auth) { // [START multitenant_signin_emaillink] const { isSignInWithEmailLink, parseActionCodeURL, signInWithEmailLink } = require("firebase/auth"); if (isSignInWithEmailLink(auth, window.location.href)) { @@ -184,13 +179,11 @@ function signInWithEmailLinkTenant(auth) { email = window.prompt('Please provide your email for confirmation'); } // The client SDK will parse the code from the link for you. - signInWithEmailLink(auth, email, window.location.href) - .then((result) => { - // User is signed in. - // tenant ID available in result.user.tenantId. - // Clear email from storage. - window.localStorage.removeItem('emailForSignIn'); - }); + const result = await signInWithEmailLink(auth, email, window.location.href); + // User is signed in. + // tenant ID available in result.user.tenantId. + // Clear email from storage. + window.localStorage.removeItem('emailForSignIn'); } // [END multitenant_signin_emaillink] } @@ -213,92 +206,93 @@ function createCustomTokenTenant(admin, uid) { // [END multitenant_create_custom_token] } -function signInWithCustomTokenTenant(auth, token) { +async function signInWithCustomTokenTenant(auth, token) { // [START multitenant_signin_custom_token] const { signInWithCustomToken } = require("firebase/auth"); auth.tenantId = 'TENANT_ID1'; - signInWithCustomToken(auth, token) - .catch((error) => { - // Handle / display error. - // ... - }); + try { + await signInWithCustomToken(auth, token); + } catch (error) { + // Handle / display error. + // ... + } // [END multitenant_signin_custom_token] } -function linkAccountTenant(auth, provider, email, password) { +async function linkAccountTenant(auth, provider, email, password) { // [START multitenant_account_linking] const { signInWithPopup, EmailAuthProvider, linkWithCredential, SAMLAuthProvider, signInWithCredential } = require("firebase/auth"); // Switch to TENANT_ID1 auth.tenantId = 'TENANT_ID1'; - // Sign-in with popup - signInWithPopup(auth, provider) - .then((userCredential) => { - // Existing user with e.g. SAML provider. - const prevUser = userCredential.user; - const emailCredential = - EmailAuthProvider.credential(email, password); - return linkWithCredential(prevUser, emailCredential) - .then((linkResult) => { - // Sign in with the newly linked credential - const linkCredential = SAMLAuthProvider.credentialFromResult(linkResult); - return signInWithCredential(auth, linkCredential); - }) - .then((signInResult) => { - // Handle sign in of merged user - // ... - }); - }) - .catch((error) => { - // Handle / display error. - // ... - }); + try { + // Sign-in with popup + const userCredential = await signInWithPopup(auth, provider); + // Existing user with e.g. SAML provider. + const prevUser = userCredential.user; + const emailCredential = + EmailAuthProvider.credential(email, password); + return linkWithCredential(prevUser, emailCredential) + .then((linkResult) => { + // Sign in with the newly linked credential + const linkCredential = SAMLAuthProvider.credentialFromResult(linkResult); + return signInWithCredential(auth, linkCredential); + }) + .then((signInResult) => { + // Handle sign in of merged user + // ... + }); + } catch (error) { + // Handle / display error. + // ... + } // [END multitenant_account_linking] } -function accountExistsPopupTenant(auth, samlProvider, googleProvider, goToApp) { +async function accountExistsPopupTenant(auth, samlProvider, googleProvider, goToApp) { // [START multitenant_account_exists_popup] const { signInWithPopup, fetchSignInMethodsForEmail, linkWithCredential } = require("firebase/auth"); // Step 1. // User tries to sign in to the SAML provider in that tenant. auth.tenantId = 'TENANT_ID'; - signInWithPopup(auth, samlProvider) - .catch((error) => { - // An error happened. - if (error.code === 'auth/account-exists-with-different-credential') { - // Step 2. - // User's email already exists. - // The pending SAML credential. - const pendingCred = error.credential; - // The credential's tenantId if needed: error.tenantId - // The provider account's email address. - const email = error.customData.email; - // Get sign-in methods for this email. - fetchSignInMethodsForEmail(email, auth) - .then((methods) => { - // Step 3. - // Ask the user to sign in with existing Google account. - if (methods[0] == 'google.com') { - signInWithPopup(auth, googleProvider) - .then((result) => { - // Step 4 - // Link the SAML AuthCredential to the existing user. - linkWithCredential(result.user, pendingCred) - .then((linkResult) => { - // SAML account successfully linked to the existing - // user. - goToApp(); - }); - }); - } - }); - } - }); + try { + await signInWithPopup(auth, samlProvider); + } catch (error) { + // An error happened. + if (error.code === 'auth/account-exists-with-different-credential') { + // Step 2. + // User's email already exists. + // The pending SAML credential. + const pendingCred = error.credential; + // The credential's tenantId if needed: error.tenantId + // The provider account's email address. + const email = error.customData.email; + // Get sign-in methods for this email. + fetchSignInMethodsForEmail(email, auth) + .then((methods) => { + // Step 3. + // Ask the user to sign in with existing Google account. + if (methods[0] == 'google.com') { + signInWithPopup(auth, googleProvider) + .then((result) => { + // Step 4 + // Link the SAML AuthCredential to the existing user. + linkWithCredential(result.user, pendingCred) + .then((linkResult) => { + // SAML account successfully linked to the existing + // user. + goToApp(); + }); + }); + } + }); + } + } // [END multitenant_account_exists_popup] } -function accountExistsRedirectTenant(auth, samlProvider, googleProvider, goToApp) { +async function accountExistsRedirectTenant(auth, samlProvider, googleProvider, goToApp) { // [START multitenant_account_exists_redirect] const { signInWithRedirect, getRedirectResult, fetchSignInMethodsForEmail, linkWithCredential } = require("firebase/auth"); // Step 1. @@ -306,8 +300,10 @@ function accountExistsRedirectTenant(auth, samlProvider, googleProvider, goToApp auth.tenantId = 'TENANT_ID'; signInWithRedirect(auth, samlProvider); var pendingCred; - // Redirect back from SAML IDP. auth.tenantId is null after redirecting. - getRedirectResult(auth).catch((error) => { + try { + // Redirect back from SAML IDP. auth.tenantId is null after redirecting. + await getRedirectResult(auth); + } catch (error) { if (error.code === 'auth/account-exists-with-different-credential') { // Step 2. // User's email already exists. @@ -329,19 +325,16 @@ function accountExistsRedirectTenant(auth, samlProvider, googleProvider, goToApp } }); } - }); + } // Redirect back from Google. auth.tenantId is null after redirecting. - getRedirectResult(auth).then((result) => { - // Step 4 - // Link the SAML AuthCredential to the existing user. - // result.user.tenantId is 'TENANT_ID'. - linkWithCredential(result.user, pendingCred) - .then((linkResult) => { - // SAML account successfully linked to the existing - // user. - goToApp(); - }); - }); + const result = await getRedirectResult(auth); + // Step 4 + // Link the SAML AuthCredential to the existing user. + // result.user.tenantId is 'TENANT_ID'. + const linkResult = await linkWithCredential(result.user, pendingCred); + // SAML account successfully linked to the existing + // user. + goToApp(); // [END multitenant_account_exists_redirect] -} \ No newline at end of file +} diff --git a/snippets/auth-next/multi-tenancy/multitenant_account_exists_popup.js b/snippets/auth-next/multi-tenancy/multitenant_account_exists_popup.js index 7bf33262..c3311e0f 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_account_exists_popup.js +++ b/snippets/auth-next/multi-tenancy/multitenant_account_exists_popup.js @@ -9,36 +9,37 @@ import { signInWithPopup, fetchSignInMethodsForEmail, linkWithCredential } from // Step 1. // User tries to sign in to the SAML provider in that tenant. auth.tenantId = 'TENANT_ID'; -signInWithPopup(auth, samlProvider) - .catch((error) => { - // An error happened. - if (error.code === 'auth/account-exists-with-different-credential') { - // Step 2. - // User's email already exists. - // The pending SAML credential. - const pendingCred = error.credential; - // The credential's tenantId if needed: error.tenantId - // The provider account's email address. - const email = error.customData.email; - // Get sign-in methods for this email. - fetchSignInMethodsForEmail(email, auth) - .then((methods) => { - // Step 3. - // Ask the user to sign in with existing Google account. - if (methods[0] == 'google.com') { - signInWithPopup(auth, googleProvider) - .then((result) => { - // Step 4 - // Link the SAML AuthCredential to the existing user. - linkWithCredential(result.user, pendingCred) - .then((linkResult) => { - // SAML account successfully linked to the existing - // user. - goToApp(); - }); - }); - } - }); - } - }); +try { + await signInWithPopup(auth, samlProvider); +} catch (error) { + // An error happened. + if (error.code === 'auth/account-exists-with-different-credential') { + // Step 2. + // User's email already exists. + // The pending SAML credential. + const pendingCred = error.credential; + // The credential's tenantId if needed: error.tenantId + // The provider account's email address. + const email = error.customData.email; + // Get sign-in methods for this email. + fetchSignInMethodsForEmail(email, auth) + .then((methods) => { + // Step 3. + // Ask the user to sign in with existing Google account. + if (methods[0] == 'google.com') { + signInWithPopup(auth, googleProvider) + .then((result) => { + // Step 4 + // Link the SAML AuthCredential to the existing user. + linkWithCredential(result.user, pendingCred) + .then((linkResult) => { + // SAML account successfully linked to the existing + // user. + goToApp(); + }); + }); + } + }); + } +} // [END multitenant_account_exists_popup_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_account_exists_redirect.js b/snippets/auth-next/multi-tenancy/multitenant_account_exists_redirect.js index a81617dd..13a94d69 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_account_exists_redirect.js +++ b/snippets/auth-next/multi-tenancy/multitenant_account_exists_redirect.js @@ -11,8 +11,10 @@ import { signInWithRedirect, getRedirectResult, fetchSignInMethodsForEmail, link auth.tenantId = 'TENANT_ID'; signInWithRedirect(auth, samlProvider); var pendingCred; -// Redirect back from SAML IDP. auth.tenantId is null after redirecting. -getRedirectResult(auth).catch((error) => { +try { + // Redirect back from SAML IDP. auth.tenantId is null after redirecting. + await getRedirectResult(auth); +} catch (error) { if (error.code === 'auth/account-exists-with-different-credential') { // Step 2. // User's email already exists. @@ -34,18 +36,15 @@ getRedirectResult(auth).catch((error) => { } }); } -}); +} // Redirect back from Google. auth.tenantId is null after redirecting. -getRedirectResult(auth).then((result) => { - // Step 4 - // Link the SAML AuthCredential to the existing user. - // result.user.tenantId is 'TENANT_ID'. - linkWithCredential(result.user, pendingCred) - .then((linkResult) => { - // SAML account successfully linked to the existing - // user. - goToApp(); - }); -}); +const result = await getRedirectResult(auth); +// Step 4 +// Link the SAML AuthCredential to the existing user. +// result.user.tenantId is 'TENANT_ID'. +const linkResult = await linkWithCredential(result.user, pendingCred); +// SAML account successfully linked to the existing +// user. +goToApp(); // [END multitenant_account_exists_redirect_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_account_linking.js b/snippets/auth-next/multi-tenancy/multitenant_account_linking.js index c43ff90d..362c2f53 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_account_linking.js +++ b/snippets/auth-next/multi-tenancy/multitenant_account_linking.js @@ -9,26 +9,25 @@ import { signInWithPopup, EmailAuthProvider, linkWithCredential, SAMLAuthProvide // Switch to TENANT_ID1 auth.tenantId = 'TENANT_ID1'; -// Sign-in with popup -signInWithPopup(auth, provider) - .then((userCredential) => { - // Existing user with e.g. SAML provider. - const prevUser = userCredential.user; - const emailCredential = - EmailAuthProvider.credential(email, password); - return linkWithCredential(prevUser, emailCredential) - .then((linkResult) => { - // Sign in with the newly linked credential - const linkCredential = SAMLAuthProvider.credentialFromResult(linkResult); - return signInWithCredential(auth, linkCredential); - }) - .then((signInResult) => { - // Handle sign in of merged user - // ... - }); - }) - .catch((error) => { - // Handle / display error. - // ... - }); +try { + // Sign-in with popup + const userCredential = await signInWithPopup(auth, provider); + // Existing user with e.g. SAML provider. + const prevUser = userCredential.user; + const emailCredential = + EmailAuthProvider.credential(email, password); + return linkWithCredential(prevUser, emailCredential) + .then((linkResult) => { + // Sign in with the newly linked credential + const linkCredential = SAMLAuthProvider.credentialFromResult(linkResult); + return signInWithCredential(auth, linkCredential); + }) + .then((signInResult) => { + // Handle sign in of merged user + // ... + }); +} catch (error) { + // Handle / display error. + // ... +} // [END multitenant_account_linking_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_send_emaillink.js b/snippets/auth-next/multi-tenancy/multitenant_send_emaillink.js index 4c4d95c5..696975eb 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_send_emaillink.js +++ b/snippets/auth-next/multi-tenancy/multitenant_send_emaillink.js @@ -9,15 +9,14 @@ import { sendSignInLinkToEmail } from "firebase/auth"; // Switch to TENANT_ID1 auth.tenantId = 'TENANT_ID1'; -sendSignInLinkToEmail(auth, email, actionCodeSettings) - .then(() => { - // The link was successfully sent. Inform the user. - // Save the email locally so you don't need to ask the user for it again - // if they open the link on the same device. - window.localStorage.setItem('emailForSignIn', email); - }) - .catch((error) => { - // Handle / display error. - // ... - }); +try { + await sendSignInLinkToEmail(auth, email, actionCodeSettings); + // The link was successfully sent. Inform the user. + // Save the email locally so you don't need to ask the user for it again + // if they open the link on the same device. + window.localStorage.setItem('emailForSignIn', email); +} catch (error) { + // Handle / display error. + // ... +} // [END multitenant_send_emaillink_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_signin_custom_token.js b/snippets/auth-next/multi-tenancy/multitenant_signin_custom_token.js index b9fa9c58..cca5764e 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_signin_custom_token.js +++ b/snippets/auth-next/multi-tenancy/multitenant_signin_custom_token.js @@ -8,9 +8,10 @@ import { signInWithCustomToken } from "firebase/auth"; auth.tenantId = 'TENANT_ID1'; -signInWithCustomToken(auth, token) - .catch((error) => { - // Handle / display error. - // ... - }); +try { + await signInWithCustomToken(auth, token); +} catch (error) { + // Handle / display error. + // ... +} // [END multitenant_signin_custom_token_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_signin_emaillink.js b/snippets/auth-next/multi-tenancy/multitenant_signin_emaillink.js index 0032af1c..409f40ab 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_signin_emaillink.js +++ b/snippets/auth-next/multi-tenancy/multitenant_signin_emaillink.js @@ -18,12 +18,10 @@ if (isSignInWithEmailLink(auth, window.location.href)) { email = window.prompt('Please provide your email for confirmation'); } // The client SDK will parse the code from the link for you. - signInWithEmailLink(auth, email, window.location.href) - .then((result) => { - // User is signed in. - // tenant ID available in result.user.tenantId. - // Clear email from storage. - window.localStorage.removeItem('emailForSignIn'); - }); + const result = await signInWithEmailLink(auth, email, window.location.href); + // User is signed in. + // tenant ID available in result.user.tenantId. + // Clear email from storage. + window.localStorage.removeItem('emailForSignIn'); } // [END multitenant_signin_emaillink_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_signin_password.js b/snippets/auth-next/multi-tenancy/multitenant_signin_password.js index 73642a8d..43b9df75 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_signin_password.js +++ b/snippets/auth-next/multi-tenancy/multitenant_signin_password.js @@ -8,12 +8,12 @@ import { signInWithEmailAndPassword } from "firebase/auth"; auth.tenantId = 'TENANT_ID'; -signInWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // User is signed in. - // userCredential.user.tenantId is 'TENANT_ID'. - }).catch((error) => { - // Handle / display error. - // ... - }); +try { + const userCredential = await signInWithEmailAndPassword(auth, email, password); + // User is signed in. + // userCredential.user.tenantId is 'TENANT_ID'. +} catch (error) { + // Handle / display error. + // ... +} // [END multitenant_signin_password_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_signin_password_demo.js b/snippets/auth-next/multi-tenancy/multitenant_signin_password_demo.js index 87882773..aa1fcb8f 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_signin_password_demo.js +++ b/snippets/auth-next/multi-tenancy/multitenant_signin_password_demo.js @@ -10,16 +10,14 @@ import { signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth"; auth.tenantId = 'TENANT_ID1'; // Sign in with tenant -signInWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // User is signed in. - const user = userCredential.user; - // user.tenantId is set to 'TENANT_ID1'. - // Switch to 'TENANT_ID2'. - auth.tenantId = 'TENANT_ID2'; - // auth.currentUser still points to the user. - // auth.currentUser.tenantId is 'TENANT_ID1'. - }); +const userCredential = await signInWithEmailAndPassword(auth, email, password); +// User is signed in. +const user = userCredential.user; +// user.tenantId is set to 'TENANT_ID1'. +// Switch to 'TENANT_ID2'. +auth.tenantId = 'TENANT_ID2'; +// auth.currentUser still points to the user. +// auth.currentUser.tenantId is 'TENANT_ID1'. // You could also get the current user from Auth state observer. onAuthStateChanged(auth, (user) => { diff --git a/snippets/auth-next/multi-tenancy/multitenant_signin_saml_popup.js b/snippets/auth-next/multi-tenancy/multitenant_signin_saml_popup.js index 6aa90550..4f450c6f 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_signin_saml_popup.js +++ b/snippets/auth-next/multi-tenancy/multitenant_signin_saml_popup.js @@ -9,17 +9,16 @@ import { signInWithPopup } from "firebase/auth"; // Switch to TENANT_ID1. auth.tenantId = 'TENANT_ID1'; -// Sign-in with popup. -signInWithPopup(auth, provider) - .then((userCredential) => { - // User is signed in. - const user = userCredential.user; - // user.tenantId is set to 'TENANT_ID1'. - // Provider data available from the result.user.getIdToken() - // or from result.user.providerData - }) - .catch((error) => { - // Handle / display error. - // ... - }); +try { + // Sign-in with popup. + const userCredential = await signInWithPopup(auth, provider); + // User is signed in. + const user = userCredential.user; + // user.tenantId is set to 'TENANT_ID1'. + // Provider data available from the result.user.getIdToken() + // or from result.user.providerData +} catch (error) { + // Handle / display error. + // ... +} // [END multitenant_signin_saml_popup_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_signin_saml_redirect.js b/snippets/auth-next/multi-tenancy/multitenant_signin_saml_redirect.js index d3552a56..aeb1c5a1 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_signin_saml_redirect.js +++ b/snippets/auth-next/multi-tenancy/multitenant_signin_saml_redirect.js @@ -12,18 +12,17 @@ auth.tenantId = 'TENANT_ID1'; // Sign-in with redirect. signInWithRedirect(auth, provider); -// After the user completes sign-in and returns to the app, you can get -// the sign-in result by calling getRedirectResult. However, if they sign out -// and sign in again with an IdP, no tenant is used. -getRedirectResult(auth) - .then((result) => { - // User is signed in. - // The tenant ID available in result.user.tenantId. - // Provider data available from the result.user.getIdToken() - // or from result.user.providerData - }) - .catch((error) => { - // Handle / display error. - // ... - }); +try { + // After the user completes sign-in and returns to the app, you can get + // the sign-in result by calling getRedirectResult. However, if they sign out + // and sign in again with an IdP, no tenant is used. + const result = await getRedirectResult(auth); + // User is signed in. + // The tenant ID available in result.user.tenantId. + // Provider data available from the result.user.getIdToken() + // or from result.user.providerData +} catch (error) { + // Handle / display error. + // ... +} // [END multitenant_signin_saml_redirect_modular] \ No newline at end of file diff --git a/snippets/auth-next/multi-tenancy/multitenant_signup_password.js b/snippets/auth-next/multi-tenancy/multitenant_signup_password.js index d89d5edf..13c0a24a 100644 --- a/snippets/auth-next/multi-tenancy/multitenant_signup_password.js +++ b/snippets/auth-next/multi-tenancy/multitenant_signup_password.js @@ -8,12 +8,12 @@ import { createUserWithEmailAndPassword } from "firebase/auth"; auth.tenantId = 'TENANT_ID'; -createUserWithEmailAndPassword(auth, email, password) - .then((userCredential) => { - // User is signed in. - // userCredential.user.tenantId is 'TENANT_ID'. - }).catch((error) => { - // Handle / display error. - // ... - }); +try { + const userCredential = await createUserWithEmailAndPassword(auth, email, password); + // User is signed in. + // userCredential.user.tenantId is 'TENANT_ID'. +} catch (error) { + // Handle / display error. + // ... +} // [END multitenant_signup_password_modular] \ No newline at end of file From 0025fed9da9fe8107c313bf504ee0e70c275b606 Mon Sep 17 00:00:00 2001 From: rinarakaki Date: Sun, 20 Oct 2024 10:15:02 +0000 Subject: [PATCH 15/15] Update auth-next/custom-email-handler.js --- auth-next/custom-email-handler.js | 64 ++++++++++--------- .../auth_handle_mgmt_query_params.js | 4 +- .../auth_handle_recover_email.js | 25 ++++---- .../auth_handle_reset_password.js | 20 +++--- .../auth_handle_verify_email.js | 15 +++-- 5 files changed, 68 insertions(+), 60 deletions(-) diff --git a/auth-next/custom-email-handler.js b/auth-next/custom-email-handler.js index 5fcc1f71..0b7e5472 100644 --- a/auth-next/custom-email-handler.js +++ b/auth-next/custom-email-handler.js @@ -29,7 +29,7 @@ function handleUserManagementQueryParams() { // This is the minimum configuration required for the API to be used. const config = { 'apiKey': "YOUR_API_KEY" // Copy this key from the web initialization - // snippet found in the Firebase console. + // snippet found in the Firebase console. }; const app = initializeApp(config); const auth = getAuth(app); @@ -49,7 +49,7 @@ function handleUserManagementQueryParams() { handleVerifyEmail(auth, actionCode, continueUrl, lang); break; default: - // Error: invalid mode. + // Error: invalid mode. } }, false); // [END auth_handle_mgmt_query_params] @@ -58,20 +58,22 @@ function handleUserManagementQueryParams() { // [START auth_handle_reset_password] const { verifyPasswordResetCode, confirmPasswordReset } = require("firebase/auth"); -function handleResetPassword(auth, actionCode, continueUrl, lang) { +async function handleResetPassword(auth, actionCode, continueUrl, lang) { // Localize the UI to the selected language as determined by the lang // parameter. - // Verify the password reset code is valid. - verifyPasswordResetCode(auth, actionCode).then((email) => { + try { + // Verify the password reset code is valid. + const email = await verifyPasswordResetCode(auth, actionCode); const accountEmail = email; // TODO: Show the reset screen with the user's email and ask the user for // the new password. const newPassword = "..."; - // Save the new password. - confirmPasswordReset(auth, actionCode, newPassword).then((resp) => { + try { + // Save the new password. + const resp = await confirmPasswordReset(auth, actionCode, newPassword); // Password reset has been confirmed and new password updated. // TODO: Display a link back to the app, or sign-in the user directly @@ -81,55 +83,57 @@ function handleResetPassword(auth, actionCode, continueUrl, lang) { // TODO: If a continue URL is available, display a button which on // click redirects the user back to the app via continueUrl with // additional state determined from that URL's parameters. - }).catch((error) => { + } catch (error) { // Error occurred during confirmation. The code might have expired or the // password is too weak. - }); - }).catch((error) => { + } + } catch (error) { // Invalid or expired action code. Ask user to try to reset the password // again. - }); + } } // [END auth_handle_reset_password] // [START auth_handle_recover_email] const { checkActionCode, applyActionCode, sendPasswordResetEmail } = require("firebase/auth"); -function handleRecoverEmail(auth, actionCode, lang) { +async function handleRecoverEmail(auth, actionCode, lang) { // Localize the UI to the selected language as determined by the lang // parameter. let restoredEmail = null; - // Confirm the action code is valid. - checkActionCode(auth, actionCode).then((info) => { + try { + // Confirm the action code is valid. + const info = await checkActionCode(auth, actionCode); // Get the restored email address. restoredEmail = info['data']['email']; // Revert to the old email. - return applyActionCode(auth, actionCode); - }).then(() => { + await applyActionCode(auth, actionCode); // Account email reverted to restoredEmail // TODO: Display a confirmation message to the user. - // You might also want to give the user the option to reset their password - // in case the account was compromised: - sendPasswordResetEmail(auth, restoredEmail).then(() => { + try { + // You might also want to give the user the option to reset their password + // in case the account was compromised: + await sendPasswordResetEmail(auth, restoredEmail); // Password reset confirmation sent. Ask user to check their email. - }).catch((error) => { + } catch (error) { // Error encountered while sending password reset code. - }); - }).catch((error) => { + } + } catch (error) { // Invalid code. - }); + } } // [END auth_handle_recover_email] // [START auth_handle_verify_email] -function handleVerifyEmail(auth, actionCode, continueUrl, lang) { - // Localize the UI to the selected language as determined by the lang - // parameter. - // Try to apply the email verification code. - applyActionCode(auth, actionCode).then((resp) => { +async function handleVerifyEmail(auth, actionCode, continueUrl, lang) { + try { + // Localize the UI to the selected language as determined by the lang + // parameter. + // Try to apply the email verification code. + const resp = await applyActionCode(auth, actionCode); // Email address has been verified. // TODO: Display a confirmation message to the user. @@ -138,10 +142,10 @@ function handleVerifyEmail(auth, actionCode, continueUrl, lang) { // TODO: If a continue URL is available, display a button which on // click redirects the user back to the app via continueUrl with // additional state determined from that URL's parameters. - }).catch((error) => { + } catch (error) { // Code is invalid or expired. Ask the user to verify their email address // again. - }); + } } // [END auth_handle_verify_email] diff --git a/snippets/auth-next/custom-email-handler/auth_handle_mgmt_query_params.js b/snippets/auth-next/custom-email-handler/auth_handle_mgmt_query_params.js index d0a22696..32bf34f6 100644 --- a/snippets/auth-next/custom-email-handler/auth_handle_mgmt_query_params.js +++ b/snippets/auth-next/custom-email-handler/auth_handle_mgmt_query_params.js @@ -24,7 +24,7 @@ document.addEventListener('DOMContentLoaded', () => { // This is the minimum configuration required for the API to be used. const config = { 'apiKey': "YOUR_API_KEY" // Copy this key from the web initialization - // snippet found in the Firebase console. + // snippet found in the Firebase console. }; const app = initializeApp(config); const auth = getAuth(app); @@ -44,7 +44,7 @@ document.addEventListener('DOMContentLoaded', () => { handleVerifyEmail(auth, actionCode, continueUrl, lang); break; default: - // Error: invalid mode. + // Error: invalid mode. } }, false); // [END auth_handle_mgmt_query_params_modular] \ No newline at end of file diff --git a/snippets/auth-next/custom-email-handler/auth_handle_recover_email.js b/snippets/auth-next/custom-email-handler/auth_handle_recover_email.js index a4351a50..6a119527 100644 --- a/snippets/auth-next/custom-email-handler/auth_handle_recover_email.js +++ b/snippets/auth-next/custom-email-handler/auth_handle_recover_email.js @@ -7,31 +7,32 @@ // [START auth_handle_recover_email_modular] import { checkActionCode, applyActionCode, sendPasswordResetEmail } from "firebase/auth"; -function handleRecoverEmail(auth, actionCode, lang) { +async function handleRecoverEmail(auth, actionCode, lang) { // Localize the UI to the selected language as determined by the lang // parameter. let restoredEmail = null; - // Confirm the action code is valid. - checkActionCode(auth, actionCode).then((info) => { + try { + // Confirm the action code is valid. + const info = await checkActionCode(auth, actionCode); // Get the restored email address. restoredEmail = info['data']['email']; // Revert to the old email. - return applyActionCode(auth, actionCode); - }).then(() => { + await applyActionCode(auth, actionCode); // Account email reverted to restoredEmail // TODO: Display a confirmation message to the user. - // You might also want to give the user the option to reset their password - // in case the account was compromised: - sendPasswordResetEmail(auth, restoredEmail).then(() => { + try { + // You might also want to give the user the option to reset their password + // in case the account was compromised: + await sendPasswordResetEmail(auth, restoredEmail); // Password reset confirmation sent. Ask user to check their email. - }).catch((error) => { + } catch (error) { // Error encountered while sending password reset code. - }); - }).catch((error) => { + } + } catch (error) { // Invalid code. - }); + } } // [END auth_handle_recover_email_modular] \ No newline at end of file diff --git a/snippets/auth-next/custom-email-handler/auth_handle_reset_password.js b/snippets/auth-next/custom-email-handler/auth_handle_reset_password.js index 95a3faea..dfce1f1a 100644 --- a/snippets/auth-next/custom-email-handler/auth_handle_reset_password.js +++ b/snippets/auth-next/custom-email-handler/auth_handle_reset_password.js @@ -7,20 +7,22 @@ // [START auth_handle_reset_password_modular] import { verifyPasswordResetCode, confirmPasswordReset } from "firebase/auth"; -function handleResetPassword(auth, actionCode, continueUrl, lang) { +async function handleResetPassword(auth, actionCode, continueUrl, lang) { // Localize the UI to the selected language as determined by the lang // parameter. - // Verify the password reset code is valid. - verifyPasswordResetCode(auth, actionCode).then((email) => { + try { + // Verify the password reset code is valid. + const email = await verifyPasswordResetCode(auth, actionCode); const accountEmail = email; // TODO: Show the reset screen with the user's email and ask the user for // the new password. const newPassword = "..."; - // Save the new password. - confirmPasswordReset(auth, actionCode, newPassword).then((resp) => { + try { + // Save the new password. + const resp = await confirmPasswordReset(auth, actionCode, newPassword); // Password reset has been confirmed and new password updated. // TODO: Display a link back to the app, or sign-in the user directly @@ -30,13 +32,13 @@ function handleResetPassword(auth, actionCode, continueUrl, lang) { // TODO: If a continue URL is available, display a button which on // click redirects the user back to the app via continueUrl with // additional state determined from that URL's parameters. - }).catch((error) => { + } catch (error) { // Error occurred during confirmation. The code might have expired or the // password is too weak. - }); - }).catch((error) => { + } + } catch (error) { // Invalid or expired action code. Ask user to try to reset the password // again. - }); + } } // [END auth_handle_reset_password_modular] \ No newline at end of file diff --git a/snippets/auth-next/custom-email-handler/auth_handle_verify_email.js b/snippets/auth-next/custom-email-handler/auth_handle_verify_email.js index 730d4601..63cb40d7 100644 --- a/snippets/auth-next/custom-email-handler/auth_handle_verify_email.js +++ b/snippets/auth-next/custom-email-handler/auth_handle_verify_email.js @@ -5,11 +5,12 @@ // 'npm run snippets'. // [START auth_handle_verify_email_modular] -function handleVerifyEmail(auth, actionCode, continueUrl, lang) { - // Localize the UI to the selected language as determined by the lang - // parameter. - // Try to apply the email verification code. - applyActionCode(auth, actionCode).then((resp) => { +async function handleVerifyEmail(auth, actionCode, continueUrl, lang) { + try { + // Localize the UI to the selected language as determined by the lang + // parameter. + // Try to apply the email verification code. + const resp = await applyActionCode(auth, actionCode); // Email address has been verified. // TODO: Display a confirmation message to the user. @@ -18,9 +19,9 @@ function handleVerifyEmail(auth, actionCode, continueUrl, lang) { // TODO: If a continue URL is available, display a button which on // click redirects the user back to the app via continueUrl with // additional state determined from that URL's parameters. - }).catch((error) => { + } catch (error) { // Code is invalid or expired. Ask the user to verify their email address // again. - }); + } } // [END auth_handle_verify_email_modular] \ No newline at end of file