Tworzenie konta użytkownika
Nowego użytkownika możesz utworzyć w projekcie Firebase, wywołując metodę createUserWithEmailAndPassword
lub logując użytkownika po raz pierwszy przy użyciu dostawcy tożsamości sfederowanego, takiego jak Logowanie przez Google lub Logowanie przez Facebooka.
Nowych użytkowników z uwierzytelnianiem za pomocą hasła możesz też utworzyć w sekcji Uwierzytelnianie w konsoli Firebase, na stronie Użytkownicy lub za pomocą pakietu Admin SDK.
Pobierz informacje o zalogowanym użytkowniku
Aby uzyskać bieżącego użytkownika, najlepiej ustawić 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 obserwatorowi masz pewność, że po otrzymaniu bieżącego użytkownika obiekt Auth nie znajduje się w stanie pośrednim, np. jako inicjalizacja. Gdy używasz metody signInWithRedirect
, przed aktywacją obserwator onAuthStateChanged
czeka, aż getRedirectResult
zakończy działanie.
Informacje o aktualnie zalogowanym użytkowniku możesz też poznać, korzystając z 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
. 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; }
Uzyskiwanie informacji o profilu użytkownika specyficznych dla dostawcy
Aby pobrać informacje profilowe 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
Za pomocą metody updateProfile
możesz aktualizować podstawowe informacje profilowe użytkownika – wyświetlaną nazwę i adres URL zdjęcia profilowego. 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 skonfigurować 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 e-maila weryfikacyjnego do użytkownika
Aby wysłać do użytkownika e-maila na potrzeby weryfikacji adresu, użyj 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! // ... });
Na stronie Szablony e-maili możesz dostosować szablon e-maila w sekcji Uwierzytelnianie w konsoli Firebase. Przeczytaj artykuł Szablony e-maili w Centrum pomocy Firebase.
Można też przekazać stan za pomocą adresu URL kontynuacji, aby przekierowywać użytkowników z powrotem do aplikacji podczas wysyłania e-maila weryfikacyjnego.
Możesz też zlokalizować e-maila weryfikacyjnego, aktualizując kod języka w instancji Auth przed wysłaniem wiadomości. 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 // ... });
Wyślij e-maila do resetowania hasła
Za pomocą metody sendPasswordResetEmail
możesz wysłać do użytkownika e-maila z prośbą o zresetowanie hasła. 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; // .. });
Na stronie Szablony e-maili możesz dostosować szablon e-maila w sekcji Uwierzytelnianie w konsoli Firebase. Przeczytaj artykuł Szablony e-maili w Centrum pomocy Firebase.
Możesz też przekazywać stan za pomocą adresu URL kontynuacji, aby przekierowywać użytkowników z powrotem do aplikacji podczas wysyłania e-maila do resetowania hasła.
Możesz też zlokalizować e-maila do resetowania hasła, aktualizując kod języka w instancji Auth przed wysłaniem wiadomości. 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();
Możesz też wysyłać e-maile dotyczące resetowania hasła z konsoli Firebase.
Usuwanie konta 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 sekcji Uwierzytelnianie w konsoli Firebase na stronie 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 lub zmiana hasła) wymagają ostatniego zalogowania się. Jeśli wykonasz jedną z tych czynności, a użytkownik zaloguje się zbyt dawno temu, nie powiedzie się 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 usługi 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
Aby zaimportować konta użytkowników z pliku do projektu Firebase, użyj polecenia auth:import
interfejsu wiersza poleceń Firebase. Przykład:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14