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

إنشاء مستخدم

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

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

الطريقة المقترَحة للحصول على المستخدم الحالي هي ضبط أداة معالجة على كائن Auth:

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

باستخدام متتبِّع، يمكنك التأكّد من أنّ المصادقة ليست في حالة وسيطة، مثل الإعداد، عند الحصول على المستخدم الحالي.

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

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

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

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

للحصول على معلومات الملف الشخصي للمستخدم، استخدِم طرق الوصول إلى مثيل من 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