管理 Firebase 中的用户

创建用户

如需在 Firebase 项目中创建新用户,您可以调用 createUserWithEmailAndPassword 方法,或让用户通过 Google 登录服务或 Facebook 登录服务等联合身份提供方服务完成首次登录。

您还可以前往 Firebase 控制台的“Authentication”部分,在“用户”页面中创建以密码验证身份的新用户,或者使用 Admin SDK 创建此类新用户。

获取当前登录的用户

如需获取当前用户,建议在 Auth 对象上设置一个观测器 (observer):

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 为 null:

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, "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 控制台的“Authentication”部分的“电子邮件模板”页面中自定义使用的电子邮件模板。请参阅 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 控制台的“Authentication”部分的“电子邮件模板”页面中自定义使用的电子邮件模板。请参阅 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 控制台的“Authentication”部分,在“用户”页面中删除用户。

重新对用户进行身份验证

某些涉及安全的敏感操作(例如删除账号设置主电子邮件地址更改密码)只能针对最近登录过的用户执行。如果对长时间没有登录的用户执行这类操作,操作将失败并显示错误。发生这种情况时,请向用户索取新的登录凭据并将这些凭据传递给 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