จัดการผู้ใช้ใน Firebase

สร้างผู้ใช้

คุณสร้างผู้ใช้ใหม่ในโปรเจ็กต์ Firebase ได้โดยเรียกใช้เมธอด createUserWithEmailAndPassword หรือลงชื่อเข้าใช้ผู้ใช้เป็นครั้งแรกโดยใช้ผู้ให้บริการข้อมูลระบุตัวตนแบบรวมศูนย์ เช่น Google Sign-In หรือ Facebook Login

คุณยังสร้างผู้ใช้ใหม่ที่ตรวจสอบสิทธิ์ด้วยรหัสผ่านได้จากส่วนการตรวจสอบสิทธิ์ของคอนโซล Firebase ในหน้าผู้ใช้ หรือใช้ Admin SDK

รับผู้ใช้ที่ลงชื่อเข้าใช้อยู่ในปัจจุบัน

วิธีที่เราแนะนำในการรับผู้ใช้ปัจจุบันคือการตั้งค่าผู้สังเกตการณ์ในออบเจ็กต์ 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 จะว่างเปล่า

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

อัปเดตโปรไฟล์ของผู้ใช้

คุณสามารถอัปเดตข้อมูลโปรไฟล์พื้นฐานของผู้ใช้ ซึ่งได้แก่ ชื่อที่แสดงของผู้ใช้และ URL รูปโปรไฟล์ โดยใช้เมธอด updateProfile เช่น

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 ต่อเพื่อเปลี่ยนเส้นทางกลับไปยังแอปเมื่อส่งอีเมลยืนยันได้ด้วย

นอกจากนี้ คุณยังแปลอีเมลยืนยันเป็นภาษาท้องถิ่นได้โดยอัปเดตรหัสภาษาในอินสแตนซ์ Auth ก่อนส่งอีเมล เช่น

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

นอกจากนี้ คุณยังส่งสถานะผ่าน continue URL เพื่อเปลี่ยนเส้นทางกลับไปยังแอปเมื่อส่งอีเมลรีเซ็ตรหัสผ่านได้อีกด้วย

นอกจากนี้ คุณยังแปลอีเมลสำหรับรีเซ็ตรหัสผ่านเป็นภาษาท้องถิ่นได้โดยอัปเดตรหัสภาษาในอินสแตนซ์ Auth ก่อนส่งอีเมล เช่น

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