Gestisci gli utenti in Firebase

Crea un utente

Per creare un nuovo utente, hai a disposizione le seguenti opzioni:

Recuperare l'utente che ha eseguito l'accesso

Il modo consigliato per ottenere l'utente corrente è impostare un listener sull'oggetto Auth:

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

Utilizzando un listener, ti assicuri che l'oggetto Auth non si trovi in uno stato intermedio, ad esempio di inizializzazione, quando recuperi l'utente corrente.

Puoi anche ottenere l'utente che ha eseguito l'accesso chiamando current_user. Se un utente non ha eseguito l'accesso, il metodo is_valid dell'utente restituirà il valore false.

Persistere le credenziali di un utente

Le credenziali dell'utente vengono archiviate nel keystore locale dopo che l'utente ha eseguito l'accesso. La cache locale delle credenziali utente può essere eliminata disconnettendo l'utente. Il keystore è specifico della piattaforma:

Ottenere il profilo di un utente

Per ottenere le informazioni del profilo di un utente, utilizza i metodi di accesso di un'istanza di firebase::auth::User. Ad esempio:

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

Ottenere le informazioni del profilo specifiche del fornitore di un utente

Per ottenere le informazioni del profilo recuperate dai provider di accesso collegati a un utente, utilizza il metodo ProviderData. Ad esempio:

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

Aggiornare il profilo di un utente

Puoi aggiornare le informazioni di base del profilo di un utente, ovvero il nome visualizzato e l'URL della foto del profilo, con il metodo UpdateUserProfile. Ad esempio:

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

Impostare l'indirizzo email di un utente

Puoi impostare l'indirizzo email di un utente con il metodo UpdateEmail. Ad esempio:

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

Inviare un'email di verifica a un utente

Puoi inviare un'email di verifica dell'indirizzo a un utente con il metodo SendEmailVerification. Ad esempio:

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

Puoi personalizzare il modello di email utilizzato nella sezione Autenticazione della console Firebase nella pagina Modelli di email. Consulta Modelli email nel Centro assistenza Firebase.

Impostare la password di un utente

Puoi impostare la password di un utente con il metodo UpdatePassword. Ad esempio:

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

Inviare un'email di reimpostazione password

Puoi inviare un'email di reimpostazione della password a un utente con il metodo SendPasswordResetEmail. Ad esempio:

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

Puoi personalizzare il modello di email utilizzato nella scheda Sicurezza > Autenticazione > Modelli della console Firebase. Consulta Modelli email nel Centro assistenza Firebase.

Puoi anche inviare email di reimpostazione della password dalla console Firebase.

Eliminare un utente

Puoi eliminare un account utente con il metodo Delete. Ad esempio:

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

Puoi anche eliminare gli utenti nella console Firebase nella scheda Sicurezza > Autenticazione > Utenti.

Eseguire nuovamente l'autenticazione di un utente

Alcune azioni sensibili alla sicurezza, come l'eliminazione di un account, l'impostazione di un indirizzo email principale e la modifica di una password, richiedono che l'utente abbia eseguito l'accesso di recente. Se esegui una di queste azioni e l'utente ha eseguito l'accesso troppo tempo fa, l'azione non va a buon fine.

In questo caso, esegui nuovamente l'autenticazione dell'utente ottenendo nuove credenziali di accesso e trasmettendole a Reauthenticate. Ad esempio:

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

Importare gli account utente

Puoi importare gli account utente da un file nel tuo progetto Firebase utilizzando il comando auth:import dell'interfaccia a riga di comando di Firebase. Ad esempio:

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