Как создать пользователя
Создать пользователя можно следующими способами:
Из приложения. Создайте нового пользователя в проекте Firebase, вызвав метод
createUserWithEmailAndPasswordили выполнив первый вход пользователя с помощью федеративного поставщика идентификационной информации, например Google или Facebook.В консоли Firebase создайте нового пользователя с аутентификацией по паролю на вкладке Безопасность > Аутентификация > Пользователи.
Как получить информацию о пользователе, выполнившем вход
Рекомендуемый способ получить текущего пользователя – задать наблюдателя для объекта 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 будет нулевым:
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; 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 // ... });
Как отправить письмо для сброса пароля
Вы можете отправить пользователю письмо с инструкциями по сбросу пароля с помощью метода 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 CLI. Пример:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14