使用自定义字段的 Firebase 身份验证

Firebase Authentication using custom fields

我一直在使用使用电子邮件和密码的 firebase 身份验证过程。这工作得很好。但我想在创建帐户时添加用户名。但是使用这个auth函数我只能发送两个参数,比如

const promise = auth.createUserWithEmailAndPassword(name.value, email.value, password.value);

向我建议的解决方法是在创建用户名后获取用户名。但我希望在创建帐户时将数据与电子邮件一起发送。有没有一种方法可以将用户名与此创建用户请求一起发送,这样我就可以在登录时获取用户名。提前致谢。

您只能将电子邮件和密码传递给createUserWithEmailAndPassword(),因此您无法使用此功能设置名称。

如果要为认证用户设置名称,需要在用户对象上使用updateProfile()方法,像这样:

user.updateProfile({
  displayName: "Jon Snow"
})

请注意 属性 称为 displayName,而不是 name

您可以在创建用户后立即设置名称。此示例使用 async/await:

const { user } = await auth.createUserWithEmailAndPassword(
  email,
  password
)

await user.updateProfile({ displayName: name });

或者,使用承诺:

auth.createUserWithEmailAndPassword(email, password)
  .then(({ user }) => user.updateProfile({ displayName: name }))
  .then(() => {
    console.log("User was updated!", auth.currentUser.displayName);
  });

如果您在代码的其他地方需要用户对象,您可以调用 firebase.auth().currentUserattach a listener to the authentication object.

您只能为 Firebase 用户设置有限数量的属性(例如 displayNameemailphotoURL)。附加(自定义)数据必须存储在其他地方,例如在 Firestore 中,连同用户的 uid。