Zarządzaj użytkownikami w Firebase

Tworzenie konta użytkownika

Nowego użytkownika możesz utworzyć na kilka sposobów:

  • W aplikacji: utwórz nowego użytkownika w projekcie Firebase, wywołując metodę createUser lub logując użytkownika po raz pierwszy za pomocą federacyjnego dostawcy tożsamości, np. Logowania przez Google lub Logowania przez Facebooka.

  • W konsoli Firebase: utwórz nowego użytkownika uwierzytelnianego hasłem na karcie Bezpieczeństwo > Uwierzytelnianie > Użytkownicy.

Pobieranie obecnie zalogowanego użytkownika

Zalecany sposób pobierania bieżącego użytkownika polega na ustawieniu odbiornika w obiekcie Auth:

Swift

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

Objective-C

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

Użycie odbiornika gwarantuje, że podczas pobierania bieżącego użytkownika obiekt Auth nie będzie w stanie pośrednim, np. w trakcie inicjowania.

Możesz też pobrać obecnie zalogowanego użytkownika za pomocą właściwości currentUser. Jeśli użytkownik nie jest zalogowany, currentUser ma wartość nil:

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

Pobieranie profilu użytkownika

Aby pobrać informacje o profilu użytkownika, użyj właściwości instancji FIRUser. Przykład:

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

Pobieranie informacji o profilu użytkownika specyficznych dla dostawcy

Aby pobrać informacje o profilu pobrane od dostawców logowania połączonych z użytkownikiem, użyj właściwości providerData. Przykład:

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

Aktualizowanie profilu użytkownika

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

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) {
  // ...
}];

Ustawianie adresu e-mail użytkownika

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

Swift

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

Objective-C

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

Wysyłanie użytkownikowi e-maila weryfikacyjnego

E-maila weryfikacyjnego możesz wysłać do użytkownika za pomocą metody sendEmailVerificationWithCompletion:. Przykład:

Swift

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

Objective-C

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

Możesz dostosować szablon e-maila używany na karcie Bezpieczeństwo > Uwierzytelnianie > Szablony w konsoli Firebase. Zobacz Szablony e-maili w Centrum pomocy Firebase.

Podczas wysyłania e-maila weryfikacyjnego możesz też przekazać stan za pomocą adresu URL kontynuacji, aby przekierować użytkownika z powrotem do aplikacji.

Dodatkowo możesz zlokalizować e-maila weryfikacyjnego, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Przykład:

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

Ustawianie hasła użytkownika

Hasło użytkownika możesz ustawić za pomocą metody updatePassword. Przykład:

Swift

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

Objective-C

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

Wysyłanie e-maila do zresetowania hasła

E-maila do zresetowania hasła możesz wysłać do użytkownika za pomocą metody sendPasswordReset. Przykład:

Swift

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

Objective-C

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

Szablon e-maila, który jest używany, możesz dostosować w sekcji Uwierzytelnianie w Firebase konsoli na stronie Szablony e-maili. Zobacz Szablony e-maili w Centrum pomocy Firebase.

Podczas wysyłania e-maila do zresetowania hasła możesz też przekazać stan za pomocą adresu URL kontynuacji, aby przekierować użytkownika z powrotem do aplikacji.

Dodatkowo możesz zlokalizować e-maila do zresetowania hasła, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Przykład:

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

E-maile do zresetowania 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:

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

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 zmienianie 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 nie powiedzie się i pojawi się błąd FIRAuthErrorCodeCredentialTooOld. W takim przypadku ponownie uwierzytelnij użytkownika, pobierając od niego nowe dane logowania i przekazując je do reauthenticate. Przykład:

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

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