Gestisci gli utenti in Firebase

Crea un utente

Puoi creare un nuovo utente nel tuo progetto Firebase chiamando il metodo CreateUserWithEmailAndPassword o accedendo a un utente per la prima volta utilizzando un provider di identità federato, come Google Sign-In o Facebook Login .

Puoi anche creare nuovi utenti autenticati tramite password dalla sezione Autenticazione della console Firebase , nella pagina Utenti.

Ottieni l'utente attualmente connesso

Il modo consigliato per ottenere l'utente corrente è impostare un ascoltatore sull'oggetto 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;
}

Utilizzando un ascoltatore, ti assicuri che l'oggetto Auth non sia in uno stato intermedio, come l'inizializzazione, quando ottieni l'utente corrente.

Puoi anche ottenere l'utente attualmente connesso chiamando CurrentUser . Se un utente non ha effettuato l'accesso, CurrentUser restituirà null. Se un utente è disconnesso, IsValid() dell'utente restituirà false.

Mantenere le credenziali di un utente

Le credenziali dell'utente verranno archiviate nell'archivio chiavi locale dopo che l'utente ha effettuato l'accesso. La cache locale delle credenziali dell'utente può essere eliminata disconnettendosi dall'utente. Il keystore è specifico della piattaforma:

Ottieni il profilo di un utente

Per ottenere informazioni sul profilo di un utente, utilizza i metodi di accesso di un'istanza di Firebase.Auth.FirebaseUser . Per esempio:

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

Ottieni informazioni sul profilo specifico del provider di un utente

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

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

Aggiorna 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 . Per esempio:

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

Imposta l'indirizzo email di un utente

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

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

Invia a un utente un'e-mail di verifica

È possibile inviare un'e-mail di verifica dell'indirizzo a un utente con il metodo SendEmailVerification . Per esempio:

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

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

Imposta la password di un utente

È possibile impostare la password di un utente con il metodo UpdatePassword . Per esempio:

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

Invia un'e-mail di reimpostazione della password

È possibile inviare un'e-mail di reimpostazione della password a un utente con il metodo SendPasswordResetEmail . Per esempio:

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

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

Puoi anche inviare e-mail di reimpostazione della password dalla console Firebase.

Elimina un utente

È possibile eliminare un account utente con il metodo Delete . Per esempio:

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

Puoi anche eliminare gli utenti dalla sezione Autenticazione della console Firebase , nella pagina Utenti.

Riautenticare 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 effettuato l'accesso di recente. Se esegui una di queste azioni e l'utente ha effettuato l'accesso troppo tempo fa, il l'azione fallisce.

In questo caso, autenticare nuovamente l'utente ottenendo nuove credenziali di accesso dall'utente e passando le credenziali a Reauthenticate . Per esempio:

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

Importa account utente

Puoi importare account utente da un file nel tuo progetto Firebase utilizzando il comando auth:import della CLI Firebase. Per esempio:

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