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 nhà cung cấp danh tính được 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 mới được xác thực bằng mật khẩu 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 dành cho quản trị viên.
Nhận người dùng hiện đã đăng nhập
Cách được đề xuất để có được người dùng hiện tại là đặt một người quan sát trên đối tượng Auth:
Web version 9
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 version 8
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ể có được người dùng hiện đã đă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
là null:
Web version 9
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 version 8
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. }
Nhận 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 version 9
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 version 8
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ơ nhà cung cấp cụ thể của người dùng
Để nhận thông tin hồ sơ được truy xuất từ các nhà cung cấp đă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 version 9
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 version 8
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 version 9
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 version 8
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 version 9
import { getAuth, updateEmail } from "firebase/auth"; const auth = getAuth(); updateEmail(auth.currentUser, "user@example.com").then(() => { // Email updated! // ... }).catch((error) => { // An error occurred // ... });
Web version 8
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 version 9
import { getAuth, sendEmailVerification } from "firebase/auth"; const auth = getAuth(); sendEmailVerification(auth.currentUser) .then(() => { // Email verification sent! // ... });
Web version 8
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 trở 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 version 9
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
Web version 8
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 version 9
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 version 8
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 version 9
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 version 8
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 version 9
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
Web version 8
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 version 9
import { getAuth, deleteUser } from "firebase/auth"; const auth = getAuth(); const user = auth.currentUser; deleteUser(user).then(() => { // User deleted. }).catch((error) => { // An error ocurred // ... });
Web version 8
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ới bảo mật — chẳng hạn như xóa tài khoản , đặt địa chỉ email chính và thay đổi mật khẩu — yêu cầu người dùng đã đă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 quá lâu, hành động không thành công 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 để reauthenticateWithCredential
thực lại. Ví dụ:
Web version 9
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 version 8
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