Zarządzaj użytkownikami w Firebase

Tworzenie konta użytkownika

Nowego użytkownika możesz utworzyć na te sposoby:

Pobieranie obecnie zalogowanego użytkownika

Zalecanym sposobem uzyskania informacji o bieżącym użytkowniku 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życie detektora gwarantuje, że obiekt Auth nie będzie w stanie pośrednim, np. w trakcie inicjowania, gdy uzyskasz bieżącego użytkownika.

Możesz też uzyskać informacje o obecnie zalogowanym użytkowniku, wywołując funkcję CurrentUser. Jeśli użytkownik nie jest zalogowany, funkcja CurrentUser zwróci wartość null. Jeśli użytkownik jest wylogowany, wartość IsValid() będzie fałszywa.

Przechowywanie danych logowania użytkownika

Po zalogowaniu się użytkownika jego dane logowania są przechowywane w lokalnym magazynie kluczy. Lokalną pamięć podręczną danych logowania użytkownika można usunąć, wylogowując go. Magazyn kluczy jest specyficzny dla platformy:

Pobieranie profilu użytkownika

Aby uzyskać informacje o profilu użytkownika, użyj metod dostępu instancji klasy Firebase.Auth.FirebaseUser. 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;
}

Pobieranie informacji o profilu użytkownika specyficznych dla dostawcy

Aby uzyskać informacje profilowe pobrane od dostawców logowania połączonych z użytkownikiem, użyj metody ProviderData. 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;
  }
}

Aktualizowanie profilu użytkownika

Podstawowe informacje o profilu użytkownika, czyli jego nazwę wyświetlaną i adres URL zdjęcia profilowego, możesz zaktualizować za pomocą metody UpdateUserProfile. 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.");
  });
}

Ustawianie adresu e-mail użytkownika

Adres e-mail użytkownika możesz ustawić za pomocą metody UpdateEmail. 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.");
  });
}

Wysyłanie użytkownikowi e-maila weryfikacyjnego

Możesz wysłać e-maila weryfikacyjnego na adres użytkownika za pomocą metody SendEmailVerification. 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.");
  });
}

Na karcie Zabezpieczenia > Uwierzytelnianie > Szablony w konsoli Firebase możesz dostosować szablon e-maila, który będzie używany. Zobacz Szablony e-maili w Centrum pomocy Firebase.

Ustawianie hasła użytkownika

Hasło użytkownika możesz ustawić za pomocą metody UpdatePassword. 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.");
  });
}

Wysyłanie e-maila do resetowania hasła

Możesz wysłać e-maila z prośbą o zresetowanie hasła do użytkownika za pomocą metody SendPasswordResetEmail. 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.");
  });
}

Na karcie Zabezpieczenia > Uwierzytelnianie > Szablony w konsoli Firebase możesz dostosować szablon e-maila, który będzie używany. Zobacz Szablony e-maili w Centrum pomocy Firebase.

E-maile z prośbą o zresetowanie hasła możesz też wysyłać z konsoli Firebase.

Usuwanie użytkownika

Konto użytkownika możesz usunąć za pomocą metody Delete. 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.");
  });
}

Użytkowników możesz też usuwać w konsoli Firebase na karcie Zabezpieczenia > Uwierzytelnianie > Użytkownicy.

Ponowne uwierzytelnianie użytkownika

Niektóre działania związane z bezpieczeństwem, takie jak usuwanie konta, ustawianie podstawowego adresu e-mailzmiana hasła, wymagają, aby użytkownik niedawno się zalogował. Jeśli wykonasz jedną z tych czynności, a użytkownik zalogował się zbyt dawno, działanie zakończy się niepowodzeniem.

W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do Reauthenticate. 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.");
  });
}

Importowanie kont użytkowników

Możesz zaimportować konta użytkowników z pliku do projektu w Firebase za pomocą polecenia auth:import wiersza poleceń Firebase. Przykład:

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