إدارة المستخدمين في Firebase

إنشاء مستخدم

تتوفّر لك الخيارات التالية لإنشاء مستخدم جديد:

الحصول على المستخدم الذي سجّل الدخول حاليًا

The recommended way to get the current user is by setting a listener on the Auth object:

Firebase.Auth.FirebaseAuth auth;
Firebase.Auth.FirebaseUser user;

// Handle initialization of the necessary firebase modules:
void InitializeFirebase() {
  Debug.Log("Setting up Firebase Auth");
  auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
  auth.StateChanged += AuthStateChanged;
  AuthStateChanged(this, null);
}

// Track state changes of the auth object.
void AuthStateChanged(object sender, System.EventArgs eventArgs) {
  if (auth.CurrentUser != user) {
    bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
    if (!signedIn && user != null) {
      Debug.Log("Signed out " + user.UserId);
    }
    user = auth.CurrentUser;
    if (signedIn) {
      Debug.Log("Signed in " + user.UserId);
    }
  }
}

// Handle removing subscription and reference to the Auth instance.
// Automatically called by a Monobehaviour after Destroy is called on it.
void OnDestroy() {
  auth.StateChanged -= AuthStateChanged;
  auth = null;
}

By using a listener, you ensure that the Auth object isn't in an intermediate state—such as initialization—when you get the current user.

يمكنك أيضًا الحصول على المستخدم الذي سجّل الدخول حاليًا من خلال طلب CurrentUser. إذا لم يسجّل المستخدم الدخول، ستعرض السمة CurrentUser قيمة فارغة. إذا سجّل المستخدم الخروج، ستعرض السمة IsValid() للمستخدم القيمة "خطأ".

الاحتفاظ ببيانات اعتماد المستخدم

سيتم تخزين بيانات اعتماد المستخدم في ملف تخزين المفاتيح على الجهاز بعد تسجيل دخول المستخدم. يمكن حذف ذاكرة التخزين المؤقت المحلية لبيانات اعتماد المستخدم من خلال تسجيل خروج المستخدم. يختلف ملف تخزين المفاتيح حسب النظام الأساسي:

الحصول على ملف مستخدم شخصي

للحصول على معلومات الملف الشخصي لمستخدم، استخدِم طرق استرجاع البيانات لنسخة من Firebase.Auth.FirebaseUser. على سبيل المثال:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  string name = user.DisplayName;
  string email = user.Email;
  System.Uri photo_url = user.PhotoUrl;
  // The user's Id, unique to the Firebase project.
  // Do NOT use this value to authenticate with your backend server, if you
  // have one; use User.TokenAsync() instead.
  string uid = user.UserId;
}

الحصول على معلومات الملف الشخصي الخاصة بمقدّم الخدمة لمستخدم معيّن

للحصول على معلومات الملف الشخصي التي تم استردادها من موفّري خدمات تسجيل الدخول المرتبطين بمستخدم معيّن، استخدِم طريقة ProviderData. على سبيل المثال:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  foreach (var profile in user.ProviderData) {
    // Id of the provider (ex: google.com)
    string providerId = profile.ProviderId;

    // UID specific to the provider
    string uid = profile.UserId;

    // Name, email address, and profile photo Url
    string name = profile.DisplayName;
    string email = profile.Email;
    System.Uri photoUrl = profile.PhotoUrl;
  }
}

تعديل الملف الشخصي لمستخدم

يمكنك تعديل معلومات الملف الشخصي الأساسية للمستخدم، أي الاسم المعروض للمستخدم وعنوان URL لصورة الملف الشخصي، باستخدام طريقة UpdateUserProfile. على سبيل المثال:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  Firebase.Auth.UserProfile profile = new Firebase.Auth.UserProfile {
    DisplayName = "Jane Q. User",
    PhotoUrl = new System.Uri("https://example.com/jane-q-user/profile.jpg"),
  };
  user.UpdateUserProfileAsync(profile).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdateUserProfileAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdateUserProfileAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User profile updated successfully.");
  });
}

ضبط عنوان البريد الإلكتروني لمستخدم

يمكنك ضبط عنوان البريد الإلكتروني للمستخدم باستخدام طريقة UpdateEmail. على سبيل المثال:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.UpdateEmailAsync("user@example.com").ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdateEmailAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdateEmailAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User email updated successfully.");
  });
}

إرسال رسالة تأكيد إلى مستخدم

يمكنك إرسال رسالة تأكيد العنوان إلى مستخدم باستخدام الطريقة SendEmailVerification. على سبيل المثال:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.SendEmailVerificationAsync().ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("SendEmailVerificationAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("SendEmailVerificationAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Email sent successfully.");
  });
}

يمكنك تخصيص نموذج الرسالة الإلكترونية المستخدَم في علامة التبويب الأمان > المصادقة > النماذج في وحدة تحكّم "Firebase". يُرجى الاطّلاع على نماذج الرسائل الإلكترونية في مركز مساعدة Firebase.

ضبط كلمة مرور مستخدم

يمكنك ضبط كلمة مرور مستخدم باستخدام طريقة UpdatePassword. على سبيل المثال:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
string newPassword = "SOME-SECURE-PASSWORD";
if (user != null) {
  user.UpdatePasswordAsync(newPassword).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdatePasswordAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdatePasswordAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Password updated successfully.");
  });
}

إرسال رسالة إلكترونية لإعادة ضبط كلمة المرور

يمكنك إرسال رسالة إلكترونية لإعادة ضبط كلمة المرور إلى مستخدم باستخدام الطريقة SendPasswordResetEmail. على سبيل المثال:

string emailAddress = "user@example.com";
if (user != null) {
  auth.SendPasswordResetEmailAsync(emailAddress).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("SendPasswordResetEmailAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("SendPasswordResetEmailAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Password reset email sent successfully.");
  });
}

يمكنك تخصيص نموذج الرسالة الإلكترونية المستخدَم في علامة التبويب الأمان > المصادقة > النماذج في وحدة تحكّم "Firebase". يُرجى الاطّلاع على نماذج الرسائل الإلكترونية في مركز مساعدة Firebase.

يمكنك أيضًا إرسال رسائل إلكترونية لإعادة ضبط كلمة المرور من وحدة تحكّم Firebase.

حذف مستخدم

يمكنك حذف حساب مستخدم باستخدام طريقة Delete. على سبيل المثال:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.DeleteAsync().ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("DeleteAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("DeleteAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User deleted successfully.");
  });
}

يمكنك أيضًا حذف المستخدمين في وحدة تحكّم Firebase ضمن علامة التبويب الأمان > المصادقة > المستخدمون.

إعادة مصادقة مستخدم

تتطلب بعض الإجراءات الحساسة من الناحية الأمنية، مثل حذف حساب وضبط عنوان بريد إلكتروني رئيسي وتغيير كلمة مرور، أن يكون المستخدم قد سجّل الدخول مؤخرًا. إذا نفّذت أحد هذه الإجراءات، وكان المستخدم قد سجّل الدخول منذ فترة طويلة جدًا، سيتعذّر تنفيذ الإجراء.

وعند حدوث ذلك، يجب إعادة مصادقة المستخدم من خلال الحصول على بيانات اعتماد جديدة لتسجيل الدخول من المستخدم وتمرير بيانات الاعتماد إلى Reauthenticate. على سبيل المثال:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;

// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
Firebase.Auth.Credential credential =
    Firebase.Auth.EmailAuthProvider.GetCredential("user@example.com", "password1234");

if (user != null) {
  user.ReauthenticateAsync(credential).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("ReauthenticateAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("ReauthenticateAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User reauthenticated successfully.");
  });
}

استيراد حسابات المستخدمين

يمكنك استيراد حسابات المستخدمين من ملف إلى مشروع Firebase باستخدام الأمر auth:import في Firebase CLI. على سبيل المثال:

firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14