Zarządzaj użytkownikami w Firebase

Utwórz użytkownika

Tworzysz nowego użytkownika w projekcie Firebase, wywołując metodę CreateUserWithEmailAndPassword lub logując się użytkownika po raz pierwszy przy użyciu federacyjnego dostawcy tożsamości, takiego jak Google Sign-In lub Facebook Login .

Możesz także utworzyć nowych użytkowników uwierzytelnionych hasłem w sekcji Uwierzytelnianie konsoli Firebase na stronie Użytkownicy.

Pobierz aktualnie zalogowanego użytkownika

Zalecanym sposobem uzyskania bieżącego użytkownika jest ustawienie detektora w obiekcie 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;
}

Używając odbiornika, możesz mieć pewność, że obiekt Auth nie będzie w stanie pośrednim — takim jak inicjalizacja — w momencie uzyskania bieżącego użytkownika.

Możesz także uzyskać aktualnie zalogowanego użytkownika, wywołując CurrentUser . Jeśli użytkownik nie jest zalogowany, CurrentUser zwróci wartość null. Jeśli użytkownik jest wylogowany, IsValid() użytkownika zwróci wartość false.

Utrwalaj poświadczenia użytkownika

Poświadczenia użytkownika będą przechowywane w lokalnym magazynie kluczy po zalogowaniu się użytkownika. Lokalną pamięć podręczną poświadczeń użytkownika można usunąć, wylogowując się użytkownika. Magazyn kluczy jest specyficzny dla platformy:

Uzyskaj profil użytkownika

Aby uzyskać informacje o profilu użytkownika, użyj metod dostępu instancji Firebase.Auth.FirebaseUser . Na przykład:

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

Uzyskaj informacje o profilu dostawcy specyficzne dla użytkownika

Aby uzyskać informacje o profilu pobrane od dostawców logowania połączonych z użytkownikiem, użyj metody ProviderData . Na przykład:

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

Zaktualizuj profil użytkownika

Podstawowe informacje o profilu użytkownika — nazwę wyświetlaną użytkownika i adres URL zdjęcia profilowego — można zaktualizować za pomocą metody UpdateUserProfile . Na przykład:

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.");
  });
}

Ustaw adres e-mail użytkownika

Adres e-mail użytkownika można ustawić za pomocą metody UpdateEmail . Na przykład:

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.");
  });
}

Wyślij użytkownikowi e-mail weryfikacyjny

Możesz wysłać wiadomość e-mail weryfikującą adres do użytkownika za pomocą metody SendEmailVerification . Na przykład:

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.");
  });
}

Możesz dostosować szablon wiadomości e-mail używany w sekcji Uwierzytelnianie konsoli Firebase na stronie Szablony wiadomości e-mail. Zobacz Szablony e-maili w Centrum pomocy Firebase.

Ustaw hasło użytkownika

Hasło użytkownika można ustawić za pomocą metody UpdatePassword . Na przykład:

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.");
  });
}

Wyślij wiadomość e-mail dotyczącą resetowania hasła

Możesz wysłać wiadomość e-mail dotyczącą resetowania hasła do użytkownika za pomocą metody SendPasswordResetEmail . Na przykład:

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.");
  });
}

Możesz dostosować szablon wiadomości e-mail używany w sekcji Uwierzytelnianie konsoli Firebase na stronie Szablony wiadomości e-mail. Zobacz Szablony e-maili w Centrum pomocy Firebase.

Możesz także wysyłać wiadomości e-mail dotyczące resetowania hasła z konsoli Firebase.

Usuń użytkownika

Konto użytkownika możesz usunąć za pomocą metody Delete . Na przykład:

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.");
  });
}

Możesz także usunąć użytkowników z sekcji Uwierzytelnianie konsoli Firebase na stronie Użytkownicy.

Ponownie uwierzytelnij użytkownika

Niektóre działania związane z bezpieczeństwem — takie jak usunięcie konta , ustawienie podstawowego adresu e-mail i zmiana hasła — wymagają, aby użytkownik zalogował się niedawno. Jeśli wykonasz jedną z tych czynności, a użytkownik zalogował się zbyt dawno temu, akcja kończy się niepowodzeniem.

Gdy tak się stanie, ponownie uwierzytelnij użytkownika, uzyskując od niego nowe poświadczenia logowania i przekazując je do Reauthenticate . Na przykład:

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.");
  });
}

Importuj konta użytkowników

Możesz zaimportować konta użytkowników z pliku do projektu Firebase, używając polecenia auth:import interfejsu Firebase CLI. Na przykład:

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