Zarządzaj użytkownikami w Firebase

Tworzenie konta użytkownika

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

Pobieranie aktualnie zalogowanego użytkownika

Zalecany sposób pobierania aktualnego użytkownika to ustawienie detektora w obiekcie Uwierzytelnianie:

class MyAuthStateListener : public firebase::auth::AuthStateListener {
 public:
  void OnAuthStateChanged(firebase::auth::Auth* auth) override {
    firebase::auth::User user = auth->current_user();
    if (user.is_valid()) {
      // User is signed in
      printf("OnAuthStateChanged: signed_in %s\n", user.uid().c_str());
    } else {
      // User is signed out
      printf("OnAuthStateChanged: signed_out\n");
    }
    // ...
  }
};
// ... initialization code
// Test notification on registration.
MyAuthStateListener state_change_listener;
auth->AddAuthStateListener(&state_change_listener);

Dzięki użyciu odbiornika masz pewność, że obiekt Auth nie jest w stanie pośrednim (np. inicjowania), gdy pobierasz aktualnego użytkownika.

Możesz też pobrać aktualnie zalogowanego użytkownika, wywołując current_user. Jeśli użytkownik nie jest zalogowany, metoda is_valid zwróci wartość false.

Utrwalanie danych logowania użytkownika

Po zalogowaniu się użytkownika jego dane logowania zostaną zapisane 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 pobrać informacje o profilu użytkownika, użyj metod dostępu instancji firebase::auth::User. Przykład:

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  std::string name = user.display_name();
  std::string email = user.email();
  std::string photo_url = user.photo_url();
  // 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 firebase::auth::User::Token() instead.
  std::string uid = user.uid();
}

Pobieranie informacji o profilu użytkownika specyficznych dla dostawcy

Aby pobrać informacje o profilu użytkownika uzyskane od dostawców logowania połączonych z użytkownikiem, użyj metody ProviderData. Przykład:

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  for (auto it = user.provider_data().begin();
       it != user.provider_data().end(); ++it) {
    firebase::auth::UserInfoInterface profile = *it;
    // Id of the provider (ex: google.com)
    std::string providerId = profile.provider_id();

    // UID specific to the provider
    std::string uid = profile.uid();

    // Name, email address, and profile photo Url
    std::string name = profile.display_name();
    std::string email = profile.email();
    std::string photoUrl = profile.photo_url();
  }
}

Aktualizowanie profilu użytkownika

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

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  firebase::auth::User::UserProfile profile;
  profile.display_name = "Jane Q. User";
  profile.photo_url = "https://example.com/jane-q-user/profile.jpg";
  user.UpdateUserProfile(profile).OnCompletion(
      [](const firebase::Future<void>& completed_future, void* user_data) {
        // We are probably in a different thread right now.
        if (completed_future.error() == 0) {
          printf("User profile updated.");
        }
      },
      nullptr);  // pass user_data here.
}

Ustawianie adresu e-mail użytkownika

Adres e-mail użytkownika możesz ustawić za pomocą metody UpdateEmail. Przykład:

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  user.UpdateEmail("user@example.com")
      .OnCompletion(
          [](const firebase::Future<void>& completed_future,
             void* user_data) {
            // We are probably in a different thread right now.
            if (completed_future.error() == 0) {
              printf("User email address updated.");
            }
          },
          nullptr);
}

Wysyłanie użytkownikowi e-maila weryfikacyjnego

Możesz wysłać użytkownikowi e-mail weryfikacyjny adresu za pomocą metody SendEmailVerification. Przykład:

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  user.SendEmailVerification().OnCompletion(
      [](const firebase::Future<void>& completed_future, void* user_data) {
        // We are probably in a different thread right now.
        if (completed_future.error() == 0) {
          printf("Email sent.");
        }
      },
      nullptr);
}

Szablon e-maila możesz dostosować w sekcji Uwierzytelnianie w Firebase konsoli na stronie Szablony e-maili. 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::User user = auth->current_user();
std::string newPassword = "SOME-SECURE-PASSWORD";

if (user.is_valid()) {
  user.UpdatePassword(newPassword.c_str())
      .OnCompletion(
          [](const firebase::Future<void>& completed_future,
             void* user_data) {
            // We are probably in a different thread right now.
            if (completed_future.error() == 0) {
              printf("password updated.");
            }
          },
          nullptr);
}

Wysyłanie e-maila z prośbą o zresetowanie hasła

Możesz wysłać użytkownikowi e-maila z prośbą o zresetowanie hasła za pomocą metody SendPasswordResetEmail. Przykład:

std::string emailAddress = "user@example.com";

auth->SendPasswordResetEmail(emailAddress.c_str())
    .OnCompletion(
        [](const firebase::Future<void>& completed_future,
           void* user_data) {
          // We are probably in a different thread right now.
          if (completed_future.error() == 0) {
            // Email sent.
          } else {
            // An error happened.
            printf("Error %d: %s", completed_future.error(),
                   completed_future.error_message());
          }
        },
        nullptr);

Możesz dostosować szablon e-maila, który ma być używany na karcie Bezpieczeństwo > Uwierzytelnianie > Szablony w konsoli Firebase. 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 konta użytkownika

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

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  user.Delete().OnCompletion(
      [](const firebase::Future<void>& completed_future, void* user_data) {
        if (completed_future.error() == 0) {
          // User deleted.
        } else {
          // An error happened.
          printf("Error %d: %s", completed_future.error(),
                 completed_future.error_message());
        }
      },
      nullptr);
}

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

Ponowne uwierzytelnianie użytkownika

Niektóre działania wymagające zachowania bezpieczeństwa, takie jak usuwanie konta, ustawianie podstawowego adresu e-mail i zmiana hasła, wymagają, aby użytkownik był niedawno zalogowany. Jeśli wykonasz jedno z tych działań, a użytkownik zalogował się zbyt dawno, działanie się nie powiedzie.

W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do Reauthenticate. Przykład:

firebase::auth::User user = auth->current_user();

// 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.is_valid()) {
  user.Reauthenticate(credential)
      .OnCompletion(
          [](const firebase::Future<void>& completed_future,
             void* user_data) {
            if (completed_future.error() == 0) {
              printf("User re-authenticated.");
            }
          },
          nullptr);
}

Importowanie kont użytkowników

Konta użytkowników możesz importować z pliku do projektu w Firebase za pomocą polecenia auth:import w wierszu poleceń Firebase. Przykład:

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