ربط عدة مقدّمي خدمات مصادقة بحساب باستخدام JavaScript

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

قبل البدء

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

لربط بيانات الاعتماد من مقدّم خدمة مصادقة، مثل 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, 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

    // 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

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

    Web

    var credential = firebase.auth.EmailAuthProvider.credential(email, password);
  4. نقْل عنصر AuthCredential إلى linkWithCredential method للمستخدم الذي سجّل الدخول:

    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 إذا كانت بيانات الاعتماد مرتبطة بحساب مستخدم آخر. في هذه الحالة، عليك التعامل مع دمج الحسابات والبيانات المرتبطة بها بما يناسب تطبيقك (راجِع المثال أعلاه).

يمكنك إلغاء ربط مقدّم خدمة مصادقة بحساب، لكي لا يتمكّن المستخدم من تسجيل الدخول باستخدام مقدّم الخدمة هذا.

لإلغاء ربط مقدّم خدمة مصادقة بحساب مستخدم، عليك تمرير معرّف مقدّم الخدمة إلى الأسلوب 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
  // ...
});