Tworzenie konta użytkownika
Nowego użytkownika w projekcie Firebase możesz utworzyć, wywołując metodę createUserWithEmailAndPassword
lub logując użytkownika po raz pierwszy za pomocą dostawcy tożsamości federacyjnej, takiego jak logowanie w Google czy logowanie w Facebooku.
Nowe konta użytkowników uwierzytelniane hasłem możesz też tworzyć w sekcji uwierzytelniania w konsoli Firebase na stronie Użytkownicy lub za pomocą pakietu Admin SDK.
Pobieranie informacji o obecnie zalogowanym użytkowniku
Zalecaną metodą 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 możesz mieć pewność, że obiekt Auth nie jest w pośrednim stanie (np. inicjalizacji) podczas pobierania bieżącego użytkownika. Gdy używasz signInWithRedirect
, obserwator onAuthStateChanged
czeka, aż getRedirectResult
zostanie rozwiązany, a potem uruchamia się.
Użytkownika, który jest obecnie zalogowany, 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; }
Pobieranie informacji o profilu użytkownika w usłudze danego dostawcy
Aby uzyskać informacje profilowe pobrane od dostawców usług logowania powiązanych 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 zaktualizować podstawowe informacje w profilu użytkownika, czyli jego nazwę wyświetlaną i 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 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ć e-maila z weryfikacją adresu do użytkownika 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! // ... });
Szablon e-maila używany w sekcji uwierzytelniania w konsoli Firebase możesz dostosować na stronie Szablony e-maila. Więcej informacji znajdziesz w sekcji Szablony e-maili w Centrum pomocy Firebase.
Stan można też przekazać za pomocą adresu URL kontynuacji, 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. 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ć użytkownikowi e-maila z możliwością zresetowania hasła, korzystając z 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; // .. });
Szablon e-maila używany w sekcji uwierzytelniania w konsoli Firebase możesz dostosować na stronie Szablony e-maili. Więcej informacji znajdziesz w sekcji Szablony e-maili w Centrum pomocy Firebase.
Stan można też przekazać za pomocą adresu URL do kontynuowania, aby przekierować użytkownika z powrotem do aplikacji podczas wysyłania e-maila do resetowania hasła.
Dodatkowo możesz 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();
Możesz też wysyłać e-maile do zresetowania hasła z konsoli Firebase.
Usuwanie użytkownika
Możesz usunąć konto użytkownika, korzystając z 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ż usunąć w sekcji uwierzytelniania w konsoli Firebase na stronie Użytkownicy.
Ponowne uwierzytelnianie użytkownika
Niektóre działania związane z bezpieczeństwem, takie jak usuwanie konta, ustawienie podstawowego adresu e-mail i zmiana hasła, wymagają, aby użytkownik zalogował się niedawno. Jeśli wykonasz jedno z tych działań, a użytkownik zalogował się zbyt dawno, działanie zakończy się niepowodzeniem.
W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do 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
Konta użytkowników możesz importować z pliku do projektu Firebase, używając polecenia auth:import
w wierszu poleceń Firebase. Przykład:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14