Firebase Auth登录未显示已登录的用户名

时间:2019-01-07 11:43:38

标签: javascript html

我正在使用Firebase Web身份验证将用户登录到我的网站,这非常正常-但我希望能够显示登录用户的名称。我该怎么做?

1 个答案:

答案 0 :(得分:0)

用户注册后,它将带有一些基本字段(电子邮件,uniqueID等)写入Firebase身份验证数据库(您可以访问,但不能完全控制它,因为它受以下人员控制) Firebase Auth系统)。

创建新用户后,您将获得一个UserCredential对象,其中包含用户的基本信息。使用uniqueID字段(UserCredential.user.uid)将您想要的用户详细信息以及任意多个字段(用户名,电子邮件,全名,地址,首选项等)写入Firebase数据库(实时数据库或Cloud Firestore)。我认为,最好将文件存储在Auth系统创建的具有唯一ID的文档下。

完成此操作后,以后用户登录,您将获得另一个userCredential对象,其中包含该用户的uniqueID。

您将使用该uniqueID来访问存储用户详细信息的数据库,您将能够检索所需的所有数据。

请参见下面的代码(我正在使用React):成功注册后,我们得到一个UserCredential对象,我们可以使用该对象读取刚刚创建的uniqueId uid,并使用该对象来创建我们数据库中具有相同ID的文档。我们可以根据需要添加任意多个字段。在这种情况下,我添加了用户名(我从注册表单获取)和电子邮件(我直接从UserCredential对象获取)。

UserCredential docs

Create User with Password and Email docs

handleSubmit(event){
    event.preventDefault();
    const { email, passwordOne} = this.state;

    // SIGN UP FUNCTION
    this.props.firebase.auth.createUserWithEmailAndPassword(email, passwordOne)

    // SAVING USER DETAILS TO MY DATABASE
    .then((UserCredential) => {
      const username = this.state.username;
      this.props.firebase.db.collection('users').doc(UserCredential.user.uid)
        .set({
          username: username,
          email: UserCredential.user.email
        })
        .then( () => {
          this.setState({ ...INITIAL_STATE });
          this.props.history.push('/');
          }
        )
        .catch(error => {
          this.setState({ error });
          }
        );
      }
    )
    .catch(error => {
      this.setState({ error });
      }
    );
  }