נהל משתמשים ב-Firebase

צור משתמש

אתה יוצר משתמש חדש בפרויקט Firebase שלך ​​על ידי קריאה לשיטת CreateUserWithEmailAndPassword או על ידי כניסה למשתמש בפעם הראשונה באמצעות ספק זהות מאוחד, כגון Google Sign-In או Facebook Login .

אתה יכול גם ליצור משתמשים חדשים מאומתים באמצעות סיסמה מקטע האימות של מסוף 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;
}

על ידי שימוש במאזין, אתה מבטיח שאובייקט Auth אינו במצב ביניים - כגון אתחול - כאשר אתה מקבל את המשתמש הנוכחי.

אתה יכול גם לקבל את המשתמש המחובר כעת על ידי התקשרות 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.");
  });
}

אתה יכול להתאים אישית את תבנית הדוא"ל המשמשת בקטע אימות של מסוף 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