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

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

לפני שמתחילים

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

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

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

    Web

    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

    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

      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

      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

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

      Web

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

      Web

      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

      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

    import { getAuth, signInWithCredential, deleteUser } 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);
    
    try {
      // Sign in user with the account you want to link to
      const result = await signInWithCredential(auth, newCredential);
      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);
    
      // Save the merged data to the new user
      repo.set(currentUser, mergedData);
    
      // Delete the previous user's Firebase Auth account first
      await deleteUser(prevUser);
      repo.delete(prevUser);
    } catch (error) {
      console.log("Sign In Error", error);
    }

    Web

    // 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);
    
    // 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);
    
      // Save the merged data to the new user
      repo.set(currentUser, mergedData);
    
      // Delete the previous user's Firebase Auth account first
      return prevUser.delete().then(() => {
        repo.delete(prevUser);
      });
    }).catch((error) => {
      console.log("Sign In Error", error);
    });

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

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

    Web

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

    Web

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

    Web

    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

    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 תיכשל אם פרטי הכניסה כבר מקושרים לחשבון משתמש אחר. במצב כזה, אתם צריכים למזג את החשבונות והנתונים המשויכים אליהם בהתאם לאפליקציה שלכם (ראו דוגמה למעלה).

לחשבון משתמש אחד ב-Firebase יכולים להיות כמה ספקי אימות מקושרים (לדוגמה, אימייל/סיסמה, Google, פייסבוק), מה שמאפשר למשתמש להיכנס לאותו חשבון Firebase בשיטות שונות.

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

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

Web

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

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

פתרון בעיות

אם נתקלתם בשגיאות כשניסיתם לקשר כמה חשבונות, עיינו במסמכי התיעוד בנושא כתובות אימייל מאומתות.