管理 Firebase 中的用戶

創建用戶

您可以透過呼叫createUserWithEmailAndPassword方法或使用聯合身分識別提供者(例如Google Sign-InFacebook Login )首次登入使用者來在 Firebase 專案中建立新使用者。

您也可以從Firebase 控制台的「驗證」部分、「使用者」頁面或使用Admin SDK建立新的經過密碼驗證的使用者。

取得目前登入的用戶

取得目前使用者的建議方法是在 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
    // ...
  }
});

透過使用觀察者,您可以確保在獲取當前使用者時 Auth 物件不處於中間狀態(例如初始化)。當您使用signInWithRedirect時, onAuthStateChanged觀察者會等待getRedirectResult解析後再觸發。

您也可以使用currentUser屬性來取得目前登入的使用者。如果使用者未登錄,則currentUser為 null:

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

取得用戶的個人資料

若要取得使用者的個人資料訊息,請使用User實例的屬性。例如:

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

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

若要取得從連結到使用者的登入提供者檢索的設定檔信息,請使用providerData屬性。例如:

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

更新用戶的個人資料

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

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

設定使用者的電子郵件地址

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

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

向使用者發送驗證電子郵件

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

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

您可以在電子郵件範本頁面上自訂Firebase 控制台的驗證部分中使用的電子郵件範本。請參閱 Firebase 說明中心中的電子郵件範本

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

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

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

設定用戶密碼

您可以使用updatePassword方法設定使用者密碼。例如:

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

發送密碼重設電子郵件

您可以使用sendPasswordResetEmail方法向使用者傳送密碼重設電子郵件。例如:

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

您可以在電子郵件範本頁面上自訂Firebase 控制台的驗證部分中使用的電子郵件範本。請參閱 Firebase 說明中心中的電子郵件範本

發送密碼重設電子郵件時,也可以透過繼續 URL傳遞狀態以重新導向回應用程式。

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

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

您也可以從 Firebase 控制台傳送密碼重設電子郵件。

刪除用戶

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

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

您也可以從Firebase 控制台的「使用者」頁面上的「驗證」部分刪除使用者。

重新驗證使用者身份

某些安全敏感操作(例如刪除帳戶設定主電子郵件地址變更密碼)要求使用者最近登入。如果您執行其中一項操作,而使用者登入時間過長,操作因錯誤而失敗。發生這種情況時,請透過從使用者取得新的登入憑證並將憑證傳遞給reauthenticateWithCredential來重新驗證使用者身分。例如:

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

匯入使用者帳戶

您可以使用 Firebase CLI 的auth:import指令將使用者帳戶從檔案匯入到 Firebase 專案中。例如:

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