Zarządzaj użytkownikami w Firebase

Utwórz użytkownika

Tworzysz nowego użytkownika w projekcie Firebase, wywołując metodę createUser lub logując użytkownika po raz pierwszy przy użyciu federacyjnego dostawcy tożsamości, takiego jak Google Sign-In lub Facebook Login .

Możesz także utworzyć nowych użytkowników uwierzytelnionych hasłem w sekcji Uwierzytelnianie konsoli Firebase na stronie Użytkownicy.

Pobierz aktualnie zalogowanego użytkownika

Zalecanym sposobem uzyskania bieżącego użytkownika jest ustawienie detektora w obiekcie Auth:

Szybki

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

Cel C

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

Używając odbiornika, możesz mieć pewność, że obiekt Auth nie będzie w stanie pośrednim — takim jak inicjalizacja — w momencie uzyskania bieżącego użytkownika.

Możesz także uzyskać aktualnie zalogowanego użytkownika, używając właściwości currentUser . Jeśli użytkownik nie jest zalogowany, currentUser wynosi zero:

Szybki

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

Cel C

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

Uzyskaj profil użytkownika

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

Szybki

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 += " "
  }
  // ...
}

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

Uzyskaj informacje o profilu dostawcy specyficzne dla użytkownika

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

Szybki

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

Cel C

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

Zaktualizuj profil użytkownika

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

Szybki

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

Cel C

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

Ustaw adres e-mail użytkownika

Adres e-mail użytkownika można ustawić za pomocą metody updateEmail . Na przykład:

Szybki

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

Cel C

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

Wyślij użytkownikowi e-mail weryfikacyjny

Możesz wysłać wiadomość e-mail weryfikującą adres do użytkownika za pomocą metody sendEmailVerificationWithCompletion: Na przykład:

Szybki

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

Cel C

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

Możesz dostosować szablon wiadomości e-mail używany w sekcji Uwierzytelnianie konsoli Firebase na stronie Szablony wiadomości e-mail. Zobacz Szablony e-maili w Centrum pomocy Firebase.

Możliwe jest również przekazanie stanu poprzez adres URL kontynuacji , aby przekierować z powrotem do aplikacji podczas wysyłania wiadomości e-mail weryfikacyjnej.

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

Szybki

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

Cel C

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

Ustaw hasło użytkownika

Hasło użytkownika można ustawić za pomocą metody updatePassword . Na przykład:

Szybki

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

Cel C

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

Wyślij wiadomość e-mail dotyczącą resetowania hasła

Możesz wysłać wiadomość e-mail dotyczącą resetowania hasła do użytkownika za pomocą metody sendPasswordReset . Na przykład:

Szybki

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

Cel C

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

Możesz dostosować szablon wiadomości e-mail używany w sekcji Uwierzytelnianie konsoli Firebase na stronie Szablony wiadomości e-mail. Zobacz Szablony e-maili w Centrum pomocy Firebase.

Możliwe jest również przekazanie stanu poprzez adres URL kontynuacji , aby przekierować z powrotem do aplikacji podczas wysyłania wiadomości e-mail dotyczącej resetowania hasła.

Dodatkowo możesz zlokalizować wiadomość e-mail dotyczącą resetowania hasła, aktualizując kod języka w instancji Auth przed wysłaniem wiadomości e-mail. Na przykład:

Szybki

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

Cel C

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

Możesz także wysyłać wiadomości e-mail dotyczące resetowania hasła z konsoli Firebase.

Usuń użytkownika

Konto użytkownika możesz usunąć metodą delete . Na przykład:

Szybki

let user = Auth.auth().currentUser

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

Cel C

FIRUser *user = [FIRAuth auth].currentUser;

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

Możesz także usunąć użytkowników z sekcji Uwierzytelnianie konsoli Firebase na stronie Użytkownicy.

Ponownie uwierzytelnij użytkownika

Niektóre działania związane z bezpieczeństwem — takie jak usunięcie konta , ustawienie podstawowego adresu e-mail i zmiana hasła — wymagają, aby użytkownik zalogował się niedawno. Jeśli wykonasz jedną z tych czynności, a użytkownik zalogował się zbyt dawno temu, akcja kończy się niepowodzeniem z powodu błędu FIRAuthErrorCodeCredentialTooOld . Gdy tak się stanie, ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je w celu reauthenticate . Na przykład:

Szybki

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

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

Importuj konta użytkowników

Możesz zaimportować konta użytkowników z pliku do projektu Firebase, używając polecenia auth:import interfejsu Firebase CLI. Na przykład:

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