Check out what’s new from Firebase at Google I/O 2022. Learn more

在 Firebase 中管理用戶

創建用戶

您可以通過調用createUserWithEmailAndPassword方法或使用聯合身份提供商(例如Google Sign-InFacebook Login )首次登錄用戶來在 Firebase 項目中創建新用戶。

您還可以從Firebase 控制台的身份驗證部分、用戶頁面或使用Admin SDK創建新的密碼身份驗證用戶。

獲取當前登錄的用戶

獲取當前用戶的推薦方法是在 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/firebase.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/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

通過使用觀察者,您可以確保 Auth 對像在獲取當前用戶時不處於中間狀態(例如初始化)。當您使用signInWithRedirect時, onAuthStateChanged觀察者會等到getRedirectResult在觸發之前解決。

您還可以使用currentUser屬性獲取當前登錄的用戶。如果用戶未登錄,則currentUser為空:

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/firebase.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/firebase.User
  // ...
} else {
  // No user is signed in.
}

獲取用戶的個人資料

要獲取用戶的個人資料信息,請使用User實例的屬性。例如:

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

獲取用戶的提供商特定的個人資料信息

要獲取從鏈接到用戶的登錄提供程序檢索的配置文件信息,請使用providerData屬性。例如:

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

更新用戶的個人資料

您可以使用updateProfile方法更新用戶的基本個人資料信息(用戶的顯示名稱和個人資料照片 URL)。例如:

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

設置用戶的電子郵件地址

您可以使用updateEmail方法設置用戶的電子郵件地址。例如:

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

向用戶發送驗證電子郵件

您可以使用sendEmailVerification方法向用戶發送地址驗證電子郵件。例如:

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

您可以在電子郵件模板頁面上自定義Firebase 控制台的身份驗證部分中使用的電子郵件模板。請參閱 Firebase 幫助中心的電子郵件模板

發送驗證電子郵件時,也可以通過繼續 URL傳遞狀態以重定向回應用程序。

此外,您可以通過在發送電子郵件之前更新 Auth 實例上的語言代碼來本地化驗證電子郵件。例如:

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

設置用戶密碼

您可以使用updatePassword方法設置用戶的密碼。例如:

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

發送密碼重置電子郵件

您可以使用sendPasswordResetEmail方法向用戶發送密碼重置電子郵件。例如:

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

您可以在電子郵件模板頁面上自定義Firebase 控制台的身份驗證部分中使用的電子郵件模板。請參閱 Firebase 幫助中心的電子郵件模板

發送密碼重置電子郵件時,還可以通過繼續 URL傳遞狀態以重定向回應用程序。

此外,您可以通過在發送電子郵件之前更新 Auth 實例上的語言代碼來本地化密碼重置電子郵件。例如:

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

您還可以從 Firebase 控制台發送密碼重置電子郵件。

刪除用戶

您可以使用delete方法刪除用戶帳戶。例如:

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

您還可以在Firebase 控制台的“用戶”頁面上的“身份驗證”部分刪除用戶。

重新驗證用戶

某些安全敏感操作(例如刪除帳戶設置主電子郵件地址更改密碼)要求用戶最近登錄。如果您執行這些操作之一,而用戶登錄時間過長,則操作失敗並出現錯誤。發生這種情況時,通過從用戶那裡獲取新的登錄憑據並將憑據傳遞給reauthenticateWithCredential來重新驗證用戶。例如:

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

導入用戶帳戶

您可以使用 Firebase CLI 的auth:import命令將用戶帳戶從文件導入您的 Firebase 項目。例如:

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