Tworzenie konta użytkownika
Nowego użytkownika możesz utworzyć na te sposoby:
Z aplikacji: utwórz nowego użytkownika w projekcie w Firebase, wywołując metodę
createUserWithEmailAndPasswordlub logując użytkownika po raz pierwszy za pomocą dostawcy tożsamości sfederowanej, takiego jak Logowanie przez Google lub Zaloguj się przez Facebooka.W konsoli Firebase: utwórz nowego użytkownika uwierzytelnianego hasłem na karcie Zabezpieczenia > Uwierzytelnianie > Użytkownicy.
Pobieranie informacji o obecnie zalogowanym użytkowniku
Zalecanym sposobem uzyskania bieżącego użytkownika jest ustawienie obserwatora w 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 // ... } });
Dzięki użyciu obserwatora masz pewność, że obiekt Auth nie jest w stanie pośrednim (np. inicjalizacji), gdy pobierasz bieżącego użytkownika. Gdy używasz signInWithRedirect, obserwator onAuthStateChanged czeka, aż getRedirectResult zostanie rozwiązany, zanim zostanie aktywowany.
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ść 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. Na 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 u konkretnego dostawcy
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:
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, takie jak wyświetlana nazwa i adres URL zdjęcia profilowego, możesz zaktualizować za pomocą metody updateProfile. Na 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. Na 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 e-maila weryfikacyjnego do użytkownika
Możesz wysłać e-maila weryfikacyjnego do użytkownika za pomocą metody sendEmailVerification. Na 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 na karcie Bezpieczeństwo > Uwierzytelnianie > Szablony w konsoli Firebase. Więcej informacji znajdziesz w artykule Szablony e-maili w Centrum pomocy Firebase.
Można też przekazać stan za pomocą URL-a dalszego działania, aby przekierować użytkownika z powrotem do aplikacji podczas wysyłania e-maila weryfikacyjnego.
Dodatkowo możesz zlokalizować e-maila weryfikacyjnego, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Na 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. Na przykład:
Web
import { getAuth, updatePassword } from "firebase/auth"; const auth = getAuth(); const user = auth.currentUser; // Add your own function here to read the user's entered password, or generate a new one const newPassword = getASecureRandomPassword(); updatePassword(user, newPassword).then(() => { // Update successful. }).catch((error) => { // An error ocurred // ... });
Web
const user = firebase.auth().currentUser; // Add your own function here to read the user's entered password, or generate a new one const newPassword = getASecureRandomPassword(); user.updatePassword(newPassword).then(() => { // Update successful. }).catch((error) => { // An error ocurred // ... });
Wysyłanie e-maila z prośbą o zresetowanie hasła
Możesz wysłać użytkownikowi e-maila z prośbą o zresetowanie hasła, korzystając z metody sendPasswordResetEmail. Na 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 na karcie Bezpieczeństwo > Uwierzytelnianie > Szablony w konsoli Firebase. Więcej informacji znajdziesz w artykule Szablony e-maili w Centrum pomocy Firebase.
Można też przekazać stan za pomocą URL-a dalszego działania, aby przekierować użytkownika z powrotem do aplikacji podczas wysyłania e-maila z linkiem do resetowania hasła.
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. Na 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 linkiem do resetowania hasła możesz też wysyłać z konsoli Firebase.
Usuwanie użytkownika
Konto użytkownika możesz usunąć za pomocą metody delete. Na 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 Bezpieczeństwo > Uwierzytelnianie > Użytkownicy.
Ponowne uwierzytelnianie 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 niedawno się zalogował. Jeśli wykonasz jedną z tych czynności, a użytkownik zalogował się zbyt dawno temu, działanie zakończy się błędem.
W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do reauthenticateWithCredential.
Na 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
Konta użytkowników możesz importować z pliku do projektu Firebase za pomocą polecenia auth:import wiersza poleceń Firebase. Na przykład:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14