Gestisci gli utenti in Firebase

Crea un utente

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

  • Dalla tua app: crea un nuovo utente nel tuo progetto Firebase chiamando il metodo CreateUserWithEmailAndPassword o eseguendo l'accesso di un utente per la prima volta utilizzando un provider di identità federate, come Accedi con Google o Accesso con Facebook.

  • Nella console Firebase: crea un nuovo utente autenticato con password nella scheda Sicurezza > Autenticazione > Utenti.

Recupera l'utente che ha eseguito l'accesso

Il modo consigliato per ottenere l'utente corrente è impostare un listener 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 listener, ti assicuri che l'oggetto Auth non si trovi in uno stato intermedio, ad esempio l'inizializzazione, quando recuperi l'utente corrente.

Puoi anche recuperare l'utente che ha eseguito l'accesso chiamando CurrentUser. Se un utente non ha eseguito l'accesso, CurrentUser restituirà null. Se un utente non ha eseguito l'accesso, il suo IsValid() restituirà false.

Rendi persistenti le credenziali di un utente

Le credenziali dell'utente verranno memorizzate nel keystore locale dopo l'accesso. La cache locale delle credenziali utente può essere eliminata disconnettendo l'utente. Il keystore è specifico della piattaforma:

Recupera il profilo di un utente

Per ottenere le informazioni del profilo di un utente, utilizza i metodi della funzione di accesso di un'istanza di Firebase.Auth.FirebaseUser. Ad 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;
}

Recupera le informazioni del profilo di un utente specifiche del provider

Per ottenere le informazioni del profilo recuperate dai provider di accesso collegati a un utente, utilizza il metodo ProviderData. Ad 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. Ad 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. Ad 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 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.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 scheda Sicurezza > Autenticazione > Modelli della console Firebase. Consulta Modelli di email nel Centro assistenza Firebase.

Imposta la password di un utente

Puoi impostare la password di un utente con il metodo UpdatePassword. Ad 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'email di reimpostazione password

Puoi inviare un'email di reimpostazione della password a un utente con il metodo SendPasswordResetEmail. Ad 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 scheda Sicurezza > Autenticazione > Modelli della console Firebase. Consulta Modelli di email nel Centro assistenza Firebase.

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

Elimina un utente

Puoi eliminare un account utente con il metodo Delete. Ad 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 nella console Firebase nella scheda Sicurezza > Autenticazione > Utenti.

Ripeti l'autenticazione di un utente

Alcune azioni sensibili dal punto di vista della 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, autentica nuovamente l'utente ottenendo nuove credenziali di accesso dall'utente e trasmettendole a Reauthenticate. Ad 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 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