在 Firebase 中管理使用者

新增使用者

您可以呼叫 createUserWithEmailAndPassword 方法,或使用聯合身分識別資訊提供者 (例如 Google 登入Facebook 登入) 首次登入使用者,在 Firebase 專案中建立新使用者。

您也可以在「使用者」頁面中,透過 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);
  });
}

更新使用者個人資料

您可以使用 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, "[email protected]").then(() => {
  // Email updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.updateEmail("[email protected]").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 說明中心的「電子郵件範本」一文。

您也可以透過繼續網址傳遞狀態,在傳送驗證電子郵件時將使用者重新導向至應用程式。

此外,您也可以在傳送電子郵件前更新 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 說明中心的「電子郵件範本」一文。

您也可以透過繼續網址傳遞狀態,在傳送密碼重設電子郵件時將使用者重新導向至應用程式。

此外,您也可以在傳送電子郵件前更新 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 CLI 的 auth:import 指令,將使用者帳戶從檔案匯入 Firebase 專案。例如:

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