ربط موفري المصادقة المتعددين بحساب باستخدام JavaScript

يمكنك السماح للمستخدمين بتسجيل الدخول إلى تطبيقك باستخدام موفري مصادقة متعددين عن طريق ربط بيانات اعتماد موفر المصادقة بحساب مستخدم موجود. يمكن التعرف على المستخدمين من خلال معرف مستخدم Firebase نفسه بغض النظر عن موفر المصادقة الذي استخدموه لتسجيل الدخول. على سبيل المثال، يمكن للمستخدم الذي سجل الدخول باستخدام كلمة مرور ربط حساب Google وتسجيل الدخول بأي من الطريقتين في المستقبل. أو يمكن لمستخدم مجهول ربط حساب Facebook ثم تسجيل الدخول لاحقًا باستخدام Facebook لمواصلة استخدام تطبيقك.

قبل ان تبدأ

أضف دعمًا لاثنين أو أكثر من موفري المصادقة (ربما بما في ذلك المصادقة المجهولة) إلى تطبيقك.

لربط بيانات الاعتماد من موفر مصادقة مثل 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
  // ...
});