ניהול משתמשים ב-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 תחזיר ערך null. אם המשתמש לא מחובר לחשבון, הפונקציה 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.");
  });
}

אפשר להתאים אישית את תבנית האימייל שבה משתמשים בכרטיסייה Security ‏> Authentication ‏> Templates במסוף 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.");
  });
}

אפשר להתאים אישית את תבנית האימייל שבה משתמשים בכרטיסייה Security ‏> Authentication ‏> Templates במסוף 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