Как создать пользователя
Вы можете создать нового пользователя одним из следующих способов:
Из приложения. Создайте нового пользователя в проекте Firebase, вызвав метод
createUserWithEmailAndPasswordили выполнив первый вход пользователя с помощью федеративного поставщика идентификационной информации, например входа с аккаунтом Google или Facebook Login.В консоли Firebase создайте нового пользователя с аутентификацией по паролю на вкладке Security (Безопасность) > Authentication (Аутентификация) > Users (Пользователи).
Получение данных о пользователе, выполнившем вход
Рекомендуемый способ получить текущего пользователя – установить наблюдателя для объекта 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 // ... } });
Используя наблюдатель, вы гарантируете, что объект Auth не находится в промежуточном состоянии, например инициализации, когда вы получаете текущего пользователя. При использовании signInWithRedirect наблюдатель onAuthStateChanged ждет, пока getRedirectResult не разрешится, прежде чем сработать.
Вы также можете получить информацию о пользователе, который вошел в аккаунт, с помощью свойства currentUser. Если пользователь не вошел в аккаунт, currentUser имеет значение 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. }
Как получить профиль пользователя
Чтобы получить информацию профиля пользователя, используйте свойства экземпляра User. Пример:
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; }
Как получить информацию профиля пользователя, относящуюся к поставщику
Чтобы получить информацию профиля, извлеченную из поставщиков входа, связанных с пользователем, используйте свойство providerData. Пример:
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); }); }
Как изменить профиль пользователя
Вы можете обновить основные сведения профиля пользователя, такие как отображаемое название и URL фото профиля, с помощью метода updateProfile. Пример:
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 // ... });
Как задать адрес электронной почты пользователя
Адрес электронной почты пользователя можно задать с помощью метода updateEmail. Пример:
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 // ... });
Как отправить пользователю письмо с подтверждением
Вы можете отправить пользователю письмо с подтверждением адреса с помощью метода sendEmailVerification. Пример:
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! // ... });
Вы можете выбрать шаблон электронного письма на вкладке Безопасность > Аутентификация > Шаблоны в консоли Firebase. Подробнее о шаблонах электронных писем в Справочном центре Firebase.
Также можно передавать состояние через URL продолжения, чтобы перенаправлять пользователя обратно в приложение при отправке письма с подтверждением.
Кроме того, вы можете локализовать письмо с подтверждением, обновив код языка в экземпляре Auth перед отправкой письма. Пример:
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();
Как задать пароль пользователя
Вы можете задать пароль пользователя с помощью метода updatePassword. Пример:
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 // ... });
Отправка письма для сброса пароля
Вы можете отправить пользователю электронное письмо для сброса пароля с помощью метода sendPasswordResetEmail. Пример:
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; // .. });
Вы можете выбрать шаблон электронного письма на вкладке Безопасность > Аутентификация > Шаблоны в консоли Firebase. Подробнее о шаблонах электронных писем в Справочном центре Firebase.
Также можно передавать состояние через URL продолжения, чтобы перенаправлять пользователя обратно в приложение при отправке письма для сброса пароля.
Кроме того, вы можете локализовать письмо для сброса пароля, обновив код языка в экземпляре Auth перед отправкой письма. Пример:
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();
Вы также можете отправлять письма для сброса пароля из консоли Firebase.
Удаление пользователя
Удалить аккаунт пользователя можно с помощью метода delete. Пример:
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 // ... });
Вы также можете удалить пользователей в консоли Firebase на вкладке Безопасность > Аутентификация > Пользователи.
Как повторно аутентифицировать пользователя
Для выполнения некоторых действий, связанных с безопасностью, например удаления аккаунта, установки основного адреса электронной почты и изменения пароля, требуется, чтобы пользователь недавно входил в аккаунт. Если вы выполните одно из этих действий, а пользователь вошел в систему слишком давно, действие завершится ошибкой.
В этом случае повторно аутентифицируйте пользователя, получив новые учетные данные и передав их в reauthenticateWithCredential.
Пример:
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 // ... });
Импорт аккаунтов пользователей
Вы можете импортировать аккаунты пользователей из файла в проект Firebase с помощью команды auth:import интерфейса командной строки Firebase. Пример:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14