Zarządzaj użytkownikami w Firebase

Tworzenie konta użytkownika

Nowego użytkownika możesz utworzyć na 3 sposoby:

Pobieranie obecnie zalogowanego użytkownika

Zalecanym sposobem uzyskania informacji o bieżącym użytkowniku jest ustawienie obserwatora na obiekcie Auth:

Web

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/auth.user
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Web

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/v8/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Używając obserwatora, masz pewność, że obiekt Auth nie znajduje się w stanie pośrednim, np. w trakcie inicjowania, gdy uzyskujesz bieżącego użytkownika. Gdy używasz signInWithRedirect, obserwator onAuthStateChanged czeka na rozwiązanie getRedirectResult przed wywołaniem.

Obecnie zalogowanego użytkownika możesz też uzyskać za pomocą właściwości currentUser. Jeśli użytkownik nie jest zalogowany, wartość currentUser to null:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/auth.user
  // ...
} else {
  // No user is signed in.
}

Web

const user = firebase.auth().currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/v8/firebase.User
  // ...
} else {
  // No user is signed in.
}

Pobieranie profilu użytkownika

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

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // 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.getToken() instead.
  const uid = user.uid;
}

Web

const user = firebase.auth().currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // 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.getIdToken() instead.
  const uid = user.uid;
}

Pobieranie informacji o profilu użytkownika specyficznych dla dostawcy

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

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

if (user !== null) {
  user.providerData.forEach((profile) => {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  Provider-specific UID: " + profile.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
    console.log("  Photo URL: " + profile.photoURL);
  });
}

Web

const user = firebase.auth().currentUser;

if (user !== null) {
  user.providerData.forEach((profile) => {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  Provider-specific UID: " + profile.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
    console.log("  Photo URL: " + profile.photoURL);
  });
}

Aktualizowanie profilu użytkownika

Podstawowe informacje o profilu użytkownika, czyli jego nazwę wyświetlaną i adres URL zdjęcia profilowego, możesz zaktualizować za pomocą metody updateProfile. Przykład:

Web

import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
  displayName: "Jane Q. User", photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
  // Profile updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});  

Ustawianie adresu e-mail użytkownika

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

Web

import { getAuth, updateEmail } from "firebase/auth";
const auth = getAuth();
updateEmail(auth.currentUser, "user@example.com").then(() => {
  // Email updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.updateEmail("user@example.com").then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Wysyłanie użytkownikowi e-maila weryfikacyjnego

Możesz wysłać do użytkownika e-maila weryfikacyjnego adresu za pomocą metody sendEmailVerification. Przykład:

Web

import { getAuth, sendEmailVerification } from "firebase/auth";

const auth = getAuth();
sendEmailVerification(auth.currentUser)
  .then(() => {
    // Email verification sent!
    // ...
  });

Web

firebase.auth().currentUser.sendEmailVerification()
  .then(() => {
    // Email verification sent!
    // ...
  });

Możesz dostosować szablon e-maila używany na karcie Zabezpieczenia > Uwierzytelnianie > Szablony w konsoli Firebase. Więcej informacji znajdziesz w artykule Szablony e-maili w Centrum pomocy Firebase.

Możesz też przekazać stan za pomocą URL-a dalszego działania, aby po wysłaniu e-maila weryfikacyjnego przekierować użytkownika z powrotem do aplikacji.

Możesz też dostosować język e-maila weryfikacyjnego, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Przykład:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
auth.languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// auth.useDeviceLanguage();

Web

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

Ustawianie hasła użytkownika

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

Web

import { getAuth, updatePassword } from "firebase/auth";

const auth = getAuth();

const user = auth.currentUser;
const newPassword = getASecureRandomPassword();

updatePassword(user, newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;
const newPassword = getASecureRandomPassword();

user.updatePassword(newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

Wysyłanie e-maila do resetowania hasła

Możesz wysłać e-maila z prośbą o zresetowanie hasła do użytkownika za pomocą metody sendPasswordResetEmail. Przykład:

Web

import { getAuth, sendPasswordResetEmail } from "firebase/auth";

const auth = getAuth();
sendPasswordResetEmail(auth, email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ..
  });

Web

firebase.auth().sendPasswordResetEmail(email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ..
  });

Możesz dostosować szablon e-maila używany na karcie Zabezpieczenia > Uwierzytelnianie > Szablony w konsoli Firebase. Więcej informacji znajdziesz w artykule Szablony e-maili w Centrum pomocy Firebase.

Możesz też przekazać stan za pomocą URL-a dalszego działania, aby po wysłaniu e-maila do zresetowania hasła przekierować użytkownika z powrotem do aplikacji.

Możesz też zlokalizować e-maila z prośbą o zresetowanie hasła, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Przykład:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
auth.languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// auth.useDeviceLanguage();

Web

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

E-maile z prośbą o zresetowanie hasła możesz też wysyłać z konsoli Firebase.

Usuwanie użytkownika

Konto użytkownika możesz usunąć za pomocą metody delete. Przykład:

Web

import { getAuth, deleteUser } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

deleteUser(user).then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.delete().then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

Użytkowników możesz też usuwać w konsoli Firebase na karcie Zabezpieczenia > Uwierzytelnianie > Użytkownicy.

Ponowne uwierzytelnianie użytkownika

Niektóre działania związane z bezpieczeństwem, takie jak usuwanie konta, ustawianie podstawowego adresu e-mailzmiana hasła, wymagają, aby użytkownik niedawno się zalogował. Jeśli wykonasz jedną z tych czynności, a użytkownik zalogował się zbyt dawno, działanie zakończy się niepowodzeniem i wyświetli się błąd. W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do funkcji reauthenticateWithCredential. Przykład:

Web

import { getAuth, reauthenticateWithCredential } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

reauthenticateWithCredential(user, credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

user.reauthenticateWithCredential(credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error occurred
  // ...
});

Importowanie kont użytkowników

Możesz zaimportować konta użytkowników z pliku do projektu w Firebase za pomocą polecenia auth:import wiersza poleceń Firebase. Przykład:

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