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

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

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

Вы также можете создавать новых пользователей, прошедших проверку пароля, в разделе «Аутентификация» консоли Firebase , на странице «Пользователи» или с помощью Admin SDK .

Получить текущего вошедшего в систему пользователя

Рекомендуемый способ получить текущего пользователя — установить наблюдателя на объекте Auth:

Web modular API

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 namespaced API

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 modular API

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 namespaced API

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 modular API

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 namespaced API

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 modular API

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 namespaced API

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 modular API

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 namespaced API

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 modular API

import { getAuth, updateEmail } from "firebase/auth";
const auth = getAuth();
updateEmail(auth.currentUser, "user@example.com").then(() => {
  // Email updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Web namespaced API

const user = firebase.auth().currentUser;

user.updateEmail("user@example.com").then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Отправить пользователю электронное письмо с подтверждением

Вы можете отправить электронное письмо с подтверждением адреса пользователю с помощью метода sendEmailVerification . Например:

Web modular API

import { getAuth, sendEmailVerification } from "firebase/auth";

const auth = getAuth();
sendEmailVerification(auth.currentUser)
  .then(() => {
    // Email verification sent!
    // ...
  });

Web namespaced API

firebase.auth().currentUser.sendEmailVerification()
  .then(() => {
    // Email verification sent!
    // ...
  });

Вы можете настроить шаблон электронной почты, который используется в разделе «Аутентификация» консоли Firebase на странице «Шаблоны электронной почты». См. Шаблоны электронной почты в Справочном центре Firebase.

Также можно передать состояние через URL-адрес продолжения для перенаправления обратно в приложение при отправке письма с подтверждением.

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

Web modular API

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 namespaced API

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

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

Вы можете установить пароль пользователя с помощью метода updatePassword . Например:

Web modular API

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 namespaced API

const user = firebase.auth().currentUser;
const newPassword = getASecureRandomPassword();

user.updatePassword(newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

Отправить электронное письмо для сброса пароля

Вы можете отправить электронное письмо для сброса пароля пользователю с помощью метода sendPasswordResetEmail . Например:

Web modular API

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 namespaced API

firebase.auth().sendPasswordResetEmail(email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ..
  });

Вы можете настроить шаблон электронной почты, который используется в разделе «Аутентификация» консоли Firebase на странице «Шаблоны электронной почты». См. Шаблоны электронной почты в Справочном центре Firebase.

Также можно передать состояние через URL-адрес продолжения для перенаправления обратно в приложение при отправке электронного письма для сброса пароля.

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

Web modular API

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 namespaced API

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

Вы также можете отправлять электронные письма для сброса пароля из консоли Firebase.

Удаление пользователя

Вы можете удалить учетную запись пользователя с помощью метода delete . Например:

Web modular API

import { getAuth, deleteUser } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

deleteUser(user).then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web namespaced API

const user = firebase.auth().currentUser;

user.delete().then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

Вы также можете удалить пользователей из раздела «Аутентификация» консоли Firebase на странице «Пользователи».

Повторная аутентификация пользователя

Некоторые действия, важные для безопасности, такие как удаление учетной записи , установка основного адреса электронной почты и изменение пароля , требуют, чтобы пользователь недавно вошел в систему. Если вы выполните одно из этих действий, а пользователь вошел в систему слишком давно, действие завершается с ошибкой. В этом случае выполните повторную аутентификацию пользователя, получив от пользователя новые учетные данные для входа и передав их в reauthenticateWithCredential . Например:

Web modular API

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 namespaced API

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