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 bằng cách gọi phương thức createUserWithEmailAndPassword hoặc đăng nhập người dùng lần đầu bằ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 bằng Facebook.

Bạn cũng có thể tạo người dùng mới được xác thực bằng mật khẩu trong 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 dành cho quản trị viên.

Lấy người dùng hiện đã đăng nhập

Bạn nên lấy người dùng hiện tại bằng cách đặt trình quan sát trên đối tượng 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
    // ...
  }
});

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 chạy) khi bạn nhận đượ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 phân giải trước khi kích hoạt.

Bạn cũng có thể lấy 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ẽ có giá trị rỗng:

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

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 thực thể User. Ví dụ:

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

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

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

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

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

Bạn có thể cập nhật thông tin cơ bản trong hồ sơ 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

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

Đặ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

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

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

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

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

Bạn có thể tuỳ chỉnh mẫu email được 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 phần Mẫu email trong Trung tâm trợ giúp của Firebase.

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

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

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

Đặt mật khẩu cho 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

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

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

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

Bạn có thể tuỳ chỉnh mẫu email được 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 phần Mẫu email trong Trung tâm trợ giúp của Firebase.

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

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

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

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ể xoá tài khoản người dùng bằng phương thức delete. Ví dụ:

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

Bạn cũng có thể xoá 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ư xoá 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 thao tác này và người dùng đã đăng nhập quá lâu, thì thao tác đó sẽ không thành công và báo 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 lấy thông tin đăng nhập mới từ người dùng và chuyển thông tin đăng nhập đó đến reauthenticateWithCredential. Ví dụ:

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

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 bằng cách sử dụng lệnh auth:import của CLI Firebase. Ví dụ:

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