Quản lý người dùng trong Firebase

Tạo người dùng

Bạn tạo người dùng mới trong dự án Firebase của mình bằng cách gọi phương thức createUserWithEmailAndPassword hoặc bằng cách đăng nhập người dùng lần đầu tiên bằng cách sử dụng nhà cung cấp danh tính liên kết, chẳng hạn như Đăng nhập bằng Google hoặc Đăng nhập Facebook .

Bạn cũng có thể tạo người dùng được xác thực bằng mật khẩu mới từ phần Xác thực của bảng điều khiển Firebase , trên trang Người dùng hoặc bằng cách sử dụng SDK quản trị viên .

Nhận người dùng hiện đang đăng nhập

Cách được đề xuất để có được người dùng hiện tại là đặt người quan sát trên đối tượng 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
    // ...
  }
});

Bằng cách sử dụng trình quan sát, bạn đảm bảo rằng đối tượng Auth không ở trạng thái trung gian—chẳng hạn như khởi tạo—khi bạn có được người dùng hiện tại. Khi bạn sử dụng signInWithRedirect , trình quan sát onAuthStateChanged sẽ đợi cho đến khi getRedirectResult giải quyết trước khi kích hoạt.

Bạn cũng có thể biết người dùng hiện đang đăng nhập bằng cách sử dụng thuộc tính currentUser . Nếu người dùng chưa đăng nhập, currentUser sẽ rỗng:

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.
}

Lấy hồ sơ của người dùng

Để lấy thông tin hồ sơ của người dùng, hãy sử dụng các thuộc tính của một phiên bản User . Ví dụ:

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;
}

Nhận thông tin hồ sơ cụ thể của nhà cung cấp của người dùng

Để lấy thông tin hồ sơ được truy xuất từ ​​nhà cung cấp dịch vụ đăng nhập được liên kết với người dùng, hãy sử dụng thuộc tính providerData . Ví dụ:

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);
  });
}

Cập nhật hồ sơ của người dùng

Bạn có thể cập nhật thông tin hồ sơ cơ bản của người dùng—tên hiển thị và URL ảnh hồ sơ của người dùng—bằng phương thức updateProfile . Ví dụ:

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
  // ...
});  

Đặt địa chỉ email của người dùng

Bạn có thể đặt địa chỉ email của người dùng bằng phương thức updateEmail . Ví dụ:

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
  // ...
});

Gửi cho người dùng một email xác minh

Bạn có thể gửi email xác minh địa chỉ cho người dùng bằng phương thức sendEmailVerification . Ví dụ:

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!
    // ...
  });

Bạn có thể tùy chỉnh mẫu email được sử dụng trong phần Xác thực của bảng điều khiển Firebase , trên trang Mẫu email. Xem Mẫu email trong Trung tâm trợ giúp Firebase.

Cũng có thể chuyển trạng thái qua URL tiếp tục để chuyển hướng quay lại ứng dụng khi gửi email xác minh.

Ngoài ra, bạn có thể bản địa hóa email xác minh bằng cách cập nhật mã ngôn ngữ trên phiên bản Auth trước khi gửi email. Ví dụ:

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();

Đặt mật khẩu của người dùng

Bạn có thể đặt mật khẩu của người dùng bằng phương thức updatePassword . Ví dụ:

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
  // ...
});

Gửi email đặt lại mật khẩu

Bạn có thể gửi email đặt lại mật khẩu cho người dùng bằng phương thức sendPasswordResetEmail . Ví dụ:

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;
    // ..
  });

Bạn có thể tùy chỉnh mẫu email được sử dụng trong phần Xác thực của bảng điều khiển Firebase , trên trang Mẫu email. Xem Mẫu email trong Trung tâm trợ giúp Firebase.

Cũng có thể chuyển trạng thái qua URL tiếp tục để chuyển hướng trở lại ứng dụng khi gửi email đặt lại mật khẩu.

Ngoài ra, bạn có thể bản địa hóa email đặt lại mật khẩu bằng cách cập nhật mã ngôn ngữ trên phiên bản Auth trước khi gửi email. Ví dụ:

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();

Bạn cũng có thể gửi email đặt lại mật khẩu từ bảng điều khiển Firebase.

Xóa người dùng

Bạn có thể xóa tài khoản người dùng bằng phương pháp delete . Ví dụ:

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
  // ...
});

Bạn cũng có thể xóa người dùng khỏi phần Xác thực của bảng điều khiển Firebase , trên trang Người dùng.

Xác thực lại người dùng

Một số hành động nhạy cảm về bảo mật—chẳng hạn như xóa tài khoản , đặt địa chỉ email chínhthay đổi mật khẩu —yêu cầu người dùng phải đăng nhập gần đây. Nếu bạn thực hiện một trong những hành động này và người dùng đã đăng nhập cách đây quá lâu, hành động thất bại với một lỗi. Khi điều này xảy ra, hãy xác thực lại người dùng bằng cách nhận thông tin đăng nhập mới từ người dùng và chuyển thông tin xác thực đó đến reauthenticateWithCredential . Ví dụ:

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
  // ...
});

Nhập tài khoản người dùng

Bạn có thể nhập tài khoản người dùng từ một tệp vào dự án Firebase của mình bằng cách sử dụng lệnh auth:import của Firebase CLI. Ví dụ:

firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14