קשר מספר ספקי אימות לחשבון באמצעות JavaScript

אתה יכול לאפשר למשתמשים להיכנס לאפליקציה שלך באמצעות מספר ספקי אימות על ידי קישור אישורי ספק אימות לחשבון משתמש קיים. ניתן לזהות משתמשים באמצעות אותו מזהה משתמש של Firebase ללא קשר לספק האימות שבו השתמשו כדי להיכנס. לדוגמה, משתמש שנכנס עם סיסמה יכול לקשר חשבון Google ולהיכנס עם כל אחת מהשיטות בעתיד. לחלופין, משתמש אנונימי יכול לקשר חשבון פייסבוק ולאחר מכן, מאוחר יותר, להיכנס לפייסבוק כדי להמשיך להשתמש באפליקציה שלך.

לפני שאתה מתחיל

הוסף תמיכה עבור שני ספקי אימות או יותר (אולי כולל אימות אנונימי) לאפליקציה שלך.

כדי לקשר אישורים מספק אישור כגון Google או Facebook לחשבון משתמש קיים:

  1. היכנס למשתמש באמצעות כל ספק או שיטה של ​​אימות.
  2. קבל את האובייקט AuthProvider המתאים לספק שברצונך לקשר לחשבון המשתמש. דוגמאות:

    Web modular API

    import { GoogleAuthProvider, FacebookAuthProvider, TwitterAuthProvider, GithubAuthProvider } from "firebase/auth";
    
    const googleProvider = new GoogleAuthProvider();
    const facebookProvider = new FacebookAuthProvider();
    const twitterProvider = new TwitterAuthProvider();
    const githubProvider = new GithubAuthProvider();

    Web namespaced API

    var googleProvider = new firebase.auth.GoogleAuthProvider();
    var facebookProvider = new firebase.auth.FacebookAuthProvider();
    var twitterProvider = new firebase.auth.TwitterAuthProvider();
    var githubProvider = new firebase.auth.GithubAuthProvider();
  3. בקש מהמשתמש להיכנס עם הספק שברצונך לקשר. אתה יכול לבקש מהמשתמשים שלך להיכנס על ידי פתיחת חלון מוקפץ או על ידי הפנייה מחדש לדף הכניסה של הספק. שיטת ההפניה מועדפת במכשירים ניידים.
    • כדי להיכנס באמצעות חלון קופץ, התקשר ל- linkWithPopup :

      Web modular API

      import { getAuth, linkWithPopup, GoogleAuthProvider } from "firebase/auth";
      const provider = new GoogleAuthProvider();
      
      const auth = getAuth();
      linkWithPopup(auth.currentUser, provider).then((result) => {
        // Accounts successfully linked.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const user = result.user;
        // ...
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });

      Web namespaced API

      auth.currentUser.linkWithPopup(provider).then((result) => {
        // Accounts successfully linked.
        var credential = result.credential;
        var user = result.user;
        // ...
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });
    • כדי להיכנס על ידי הפנייה מחדש לדף הכניסה של הספק, התקשר ל- linkWithRedirect : פעל לפי השיטות המומלצות בעת השימוש ב-'linkWithRedirect'.

      Web modular API

      import { getAuth, linkWithRedirect, GoogleAuthProvider } from "firebase/auth";
      const provider = new GoogleAuthProvider();
      
      const auth = getAuth();
      linkWithRedirect(auth.currentUser, provider)
        .then(/* ... */)
        .catch(/* ... */);

      Web namespaced API

      auth.currentUser.linkWithRedirect(provider)
        .then(/* ... */)
        .catch(/* ... */);
      לאחר שהמשתמש נכנס, הוא מנותב בחזרה לדף שלך. לאחר מכן, תוכל לאחזר את תוצאת הכניסה על ידי קריאה getRedirectResult כאשר הדף שלך נטען:

      Web modular API

      import { getRedirectResult } from "firebase/auth";
      getRedirectResult(auth).then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        if (credential) {
          // Accounts successfully linked.
          const user = result.user;
          // ...
        }
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });

      Web namespaced API

      auth.getRedirectResult().then((result) => {
        if (result.credential) {
          // Accounts successfully linked.
          var credential = result.credential;
          var user = result.user;
          // ...
        }
      }).catch((error) => {
        // Handle Errors here.
        // ...
      });
    אם המשתמש נכנס בהצלחה, החשבון של המשתמש אצל הספק מקושר לחשבון המשתמש בפרויקט Firebase שלך.

    קישור החשבון ייכשל אם האישורים כבר מקושרים לחשבון משתמש אחר. במצב זה, עליך לטפל במיזוג החשבונות והנתונים המשויכים בהתאם לאפליקציה שלך:

    Web modular API

    import { getAuth, signInWithCredential, linkWithCredential, OAuthProvider } from "firebase/auth";
    
    // The implementation of how you store your user data depends on your application
    const repo = new MyUserDataRepo();
    
    // Get reference to the currently signed-in user
    const auth = getAuth();
    const prevUser = auth.currentUser;
    
    // Get the data which you will want to merge. This should be done now
    // while the app is still signed in as this user.
    const prevUserData = repo.get(prevUser);
    
    // Delete the user's data now, we will restore it if the merge fails
    repo.delete(prevUser);
    
    // Sign in user with the account you want to link to
    signInWithCredential(auth, newCredential).then((result) => {
      console.log("Sign In Success", result);
      const currentUser = result.user;
      const currentUserData = repo.get(currentUser);
    
      // Merge prevUser and currentUser data stored in Firebase.
      // Note: How you handle this is specific to your application
      const mergedData = repo.merge(prevUserData, currentUserData);
    
      const credential = OAuthProvider.credentialFromResult(result);
      return linkWithCredential(prevUser, credential)
        .then((linkResult) => {
          // Sign in with the newly linked credential
          const linkCredential = OAuthProvider.credentialFromResult(linkResult);
          return signInWithCredential(auth, linkCredential);
        })
        .then((signInResult) => {
          // Save the merged data to the new user
          repo.set(signInResult.user, mergedData);
        });
    }).catch((error) => {
      // If there are errors we want to undo the data merge/deletion
      console.log("Sign In Error", error);
      repo.set(prevUser, prevUserData);
    });

    Web namespaced API

    // The implementation of how you store your user data depends on your application
    var repo = new MyUserDataRepo();
    
    // Get reference to the currently signed-in user
    var prevUser = auth.currentUser;
    
    // Get the data which you will want to merge. This should be done now
    // while the app is still signed in as this user.
    var prevUserData = repo.get(prevUser);
    
    // Delete the user's data now, we will restore it if the merge fails
    repo.delete(prevUser);
    
    // Sign in user with the account you want to link to
    auth.signInWithCredential(newCredential).then((result) => {
      console.log("Sign In Success", result);
      var currentUser = result.user;
      var currentUserData = repo.get(currentUser);
    
      // Merge prevUser and currentUser data stored in Firebase.
      // Note: How you handle this is specific to your application
      var mergedData = repo.merge(prevUserData, currentUserData);
    
      return prevUser.linkWithCredential(result.credential)
        .then((linkResult) => {
          // Sign in with the newly linked credential
          return auth.signInWithCredential(linkResult.credential);
        })
        .then((signInResult) => {
          // Save the merged data to the new user
          repo.set(signInResult.user, mergedData);
        });
    }).catch((error) => {
      // If there are errors we want to undo the data merge/deletion
      console.log("Sign In Error", error);
      repo.set(prevUser, prevUserData);
    });

כדי להוסיף כתובת דואר אלקטרוני ואישורי סיסמה לחשבון משתמש קיים:

  1. היכנס למשתמש באמצעות כל ספק או שיטה של ​​אימות.
  2. בקש מהמשתמש כתובת דואר אלקטרוני וסיסמה חדשה.
  3. צור אובייקט AuthCredential עם כתובת הדוא"ל והסיסמה:

    Web modular API

    import { EmailAuthProvider } from "firebase/auth";
    
    const credential = EmailAuthProvider.credential(email, password);

    Web namespaced API

    var credential = firebase.auth.EmailAuthProvider.credential(email, password);
  4. העבר את האובייקט AuthCredential לשיטת linkWithCredential של המשתמש המחובר:

    Web modular API

    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);
      });

    Web namespaced API

    auth.currentUser.linkWithCredential(credential)
      .then((usercred) => {
        var user = usercred.user;
        console.log("Account linking success", user);
      }).catch((error) => {
        console.log("Account linking error", error);
      });

    הקריאה ל- linkWithCredential תיכשל אם האישורים כבר מקושרים לחשבון משתמש אחר. במצב זה, עליך לטפל במיזוג החשבונות והנתונים המשויכים בהתאם לאפליקציה שלך (ראה דוגמה למעלה).

אתה יכול לבטל קישור של ספק אישור מחשבון, כך שהמשתמש לא יוכל יותר להיכנס עם אותו ספק.

כדי לבטל קישור של ספק אישור מחשבון משתמש, העבר את מזהה הספק לשיטת unlink . אתה יכול לקבל את מזהי הספקים של ספקי ההסמכה המקושרים למשתמש מהמאפיין providerData .

Web modular API

import { getAuth, unlink } from "firebase/auth";

const auth = getAuth();
unlink(auth.currentUser, providerId).then(() => {
  // Auth provider unlinked from account
  // ...
}).catch((error) => {
  // An error happened
  // ...
});

Web namespaced API

user.unlink(providerId).then(() => {
  // Auth provider unlinked from account
  // ...
}).catch((error) => {
  // An error happened
  // ...
});