Управление пользователями в Firebase

Создать пользователя

Для создания нового пользователя у вас есть следующие варианты:

  • В вашем приложении : создайте нового пользователя в вашем проекте Firebase, вызвав метод createUserWithEmailAndPassword или впервые войдя в систему с помощью федеративного поставщика идентификации, такого как Google Sign-In или Facebook Login .

  • В консоли 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 будет равен 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);
  });
}

Обновить профиль пользователя

С помощью метода updateProfile можно обновить основную информацию профиля пользователя — отображаемое имя и URL-адрес фотографии профиля. Например:

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-адрес продолжения , чтобы перенаправить пользователя обратно в приложение при отправке письма с подтверждением.

Кроме того, вы можете локализовать письмо с подтверждением, обновив код языка в экземпляре аутентификации перед отправкой письма. Например:

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-адрес продолжения , чтобы перенаправить пользователя обратно в приложение при отправке электронного письма для сброса пароля.

Кроме того, вы можете локализовать электронное письмо для сброса пароля, обновив код языка в экземпляре аутентификации перед отправкой письма. Например:

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