Gestisci gli utenti in Firebase

Crea un utente

Crea un nuovo utente nel tuo progetto Firebase chiamando il metodo createUser o accedendo per la prima volta con un provider di identità federata, come Accedi con Google o Accesso con Facebook.

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

Recuperare l'utente che ha eseguito l'accesso

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

Swift

handle = Auth.auth().addStateDidChangeListener { auth, user in
  // ...
}

Objective-C

self.handle = [[FIRAuth auth]
    addAuthStateDidChangeListener:^(FIRAuth *_Nonnull auth, FIRUser *_Nullable user) {
      // ...
    }];

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 attualmente connesso utilizzando la proprietà currentUser. Se un utente non ha eseguito l'accesso, currentUser è nullo:

Swift

if Auth.auth().currentUser != nil {
  // User is signed in.
  // ...
} else {
  // No user is signed in.
  // ...
}

Objective-C

if ([FIRAuth auth].currentUser) {
  // User is signed in.
  // ...
} else {
  // No user is signed in.
  // ...
}

Ottenere il profilo di un utente

Per ottenere le informazioni del profilo di un utente, utilizza le proprietà di un'istanza di FIRUser. Ad esempio:

Swift

let user = Auth.auth().currentUser
if let user = user {
  // 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 getTokenWithCompletion:completion: instead.
  let uid = user.uid
  let email = user.email
  let photoURL = user.photoURL
  var multiFactorString = "MultiFactor: "
  for info in user.multiFactor.enrolledFactors {
    multiFactorString += info.displayName ?? "[DispayName]"
    multiFactorString += " "
  }
  // ...
}

Objective-C

FIRUser *user = [FIRAuth auth].currentUser;
if (user) {
  // 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 getTokenWithCompletion:completion: instead.
  NSString *email = user.email;
  NSString *uid = user.uid;
  NSMutableString *multiFactorString = [NSMutableString stringWithFormat:@"MultiFactor: "];
  for (FIRMultiFactorInfo *info in user.multiFactor.enrolledFactors) {
    [multiFactorString appendString:info.displayName];
    [multiFactorString appendString:@" "];
  }
  NSURL *photoURL = user.photoURL;
  // ...
}

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 la proprietà providerData. Ad esempio:

Swift

let userInfo = Auth.auth().currentUser?.providerData[indexPath.row]
cell?.textLabel?.text = userInfo?.providerID
// Provider-specific UID
cell?.detailTextLabel?.text = userInfo?.uid

Objective-C

id<FIRUserInfo> userInfo = [FIRAuth auth].currentUser.providerData[indexPath.row];
cell.textLabel.text = [userInfo providerID];
// Provider-specific UID
cell.detailTextLabel.text = [userInfo uid];

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 la classe UserProfileChangeRequest. Ad esempio:

Swift

let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = displayName
changeRequest?.commitChanges { error in
  // ...
}

Objective-C

FIRUserProfileChangeRequest *changeRequest = [[FIRAuth auth].currentUser profileChangeRequest];
changeRequest.displayName = userInput;
[changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
  // ...
}];

Impostare l'indirizzo email di un utente

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

Swift

Auth.auth().currentUser?.updateEmail(to: email) { error in
  // ...
}

Objective-C

[[FIRAuth auth].currentUser updateEmail:userInput completion:^(NSError *_Nullable error) {
  // ...
}];

Inviare un'email di verifica a un utente

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

Swift

Auth.auth().currentUser?.sendEmailVerification { error in
  // ...
}

Objective-C

[[FIRAuth auth].currentUser sendEmailVerificationWithCompletion:^(NSError *_Nullable error) {
  // ...
}];

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.

È anche possibile passare lo stato tramite un URL continuo per reindirizzare l'utente all'app quando invia un'email di verifica.

Inoltre, puoi localizzare l'email di verifica aggiornando il codice della lingua nell'istanza Auth prima di inviare l'email. Ad esempio:

Swift

Auth.auth().languageCode = "fr"
// To apply the default app language instead of explicitly setting it.
// Auth.auth().useAppLanguage()

Objective-C

[FIRAuth auth].languageCode = @"fr";
// To apply the default app language instead of explicitly setting it.
// [[FIRAuth auth] useAppLanguage];

Impostare la password di un utente

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

Swift

Auth.auth().currentUser?.updatePassword(to: password) { error in
  // ...
}

Objective-C

[[FIRAuth auth].currentUser updatePassword:userInput completion:^(NSError *_Nullable error) {
  // ...
}];

Inviare un'email di reimpostazione password

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

Swift

Auth.auth().sendPasswordReset(withEmail: email) { error in
  // ...
}

Objective-C

[[FIRAuth auth] sendPasswordResetWithEmail:userInput completion:^(NSError *_Nullable error) {
  // ...
}];

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.

È anche possibile passare lo stato tramite un URL continuo per reindirizzare l'utente all'app quando invia un'email di reimpostazione password.

Inoltre, puoi localizzare l'email di reimpostazione della password aggiornando il codice della lingua nell'istanza Auth prima di inviare l'email. Ad esempio:

Swift

Auth.auth().languageCode = "fr"
// To apply the default app language instead of explicitly setting it.
// Auth.auth().useAppLanguage()

Objective-C

[FIRAuth auth].languageCode = @"fr";
// To apply the default app language instead of explicitly setting it.
// [[FIRAuth auth] useAppLanguage];

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:

Swift

let user = Auth.auth().currentUser

user?.delete { error in
  if let error = error {
    // An error happened.
  } else {
    // Account deleted.
  }
}

Objective-C

FIRUser *user = [FIRAuth auth].currentUser;

[user deleteWithCompletion:^(NSError *_Nullable error) {
  if (error) {
    // An error happened.
  } else {
    // Account deleted.
  }
}];

Puoi anche eliminare gli utenti dalla sezione Autenticazione della Firebase console, nella pagina 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 e viene visualizzato l'errore FIRAuthErrorCodeCredentialTooOld. In questo caso, esegui nuovamente l'autenticazione dell'utente ottenendo nuove credenziali di accesso e trasmettendole a reauthenticate. Ad esempio:

Swift

let user = Auth.auth().currentUser
var credential: AuthCredential

// Prompt the user to re-provide their sign-in credentials

user?.reauthenticate(with: credential) { error in
  if let error = error {
    // An error happened.
  } else {
    // User re-authenticated.
  }
}

Objective-C

FIRUser *user = [FIRAuth auth].currentUser;
FIRAuthCredential *credential;

// Prompt the user to re-provide their sign-in credentials

[user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {
  if (error) {
    // An error happened.
  } else {
    // User re-authenticated.
  }
}];

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