Firebase 身份验证 - Firebase 注册并重定向后用户未登录

2024-07-03

我正在使用 firebase 为用户创建一个帐户。创建帐户后,我重定向到主页,该页面检查我是否已登录。奇怪的是,我没有登录。

在创建帐户页面上:

createAccount() {
  firebaseAuth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((user) => {
    // write some data to database
    firebase.database().ref().child('users').child(user.uid).child('someKey').set(this.state.email).then(function() {
      // send email verification
      user.sendEmailVerification().then(function() {
        console.log("sent email verification");
        // Go to home page
        this.props.history.push('/home');
      }.bind(this)).catch(function(error) {
        console.log("Error: account created but no verification email sent.");
      }.bind(this));
    }.bind(this)).catch((error) => {
      console.log('Error: while writing to database');
    });
  // catch any error while creating user
  }).catch((error) => {
    console.log('Error: while creating account');
  });
}

在主页上:

componentDidMount() {
  firebase.auth().onAuthStateChanged(function (user) {
    if (!user) {
      console.log("no user logged in");  
      this.props.history.replace('/login'); // ISSUE: Always redirected to login, even after signup and login
      return
    } else {
      console.log("Woo! User is logged in!");
    }
  }.bind(this))
}

替代尝试:

  • 我尝试在注册后显式登录用户,但出现相同的结果
  • 被取代this.createAccount with () => this.createAccount for onClick处理程序(相同的结果)
  • used firebase.auth()代替firebaseAuth()(相同的结果)

有谁明白为什么我没有登录吗?

** EDIT: **

以下是我初始化应用程序的方式:

<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "XXXXXXXXX",
    authDomain: "myproject.firebaseapp.com",
    databaseURL: "https://myproject.firebaseio.com",
    projectId: "XXXXXXXXX",
    storageBucket: "XXXXXXXXX.appspot.com",
    messagingSenderId: "XXXXXXXXX"
  };
  firebase.initializeApp(config);
</script>

可能值得注意的是:如果我使用一个不是刚刚创建的帐户登录(或者如果我等待一段时间然后登录到我创建的帐户),则在以下情况下保留授权似乎不存在问题重定向。似乎只有当我创建一个新用户然后重定向时它才会丢失登录用户。


我有相同的设置并且工作正常。

我的路由器顶部有我的身份验证状态更改侦听器......

state = { user: null };

componentDidMount() {
   firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ user });
      } else {
        this.props.history.push('/login');
      }
   });
 }

在 Login.js 中,我有一个表单连接到类似于您的登录功能......

login() {
    firebase
      .auth()
      .signInWithEmailAndPassword(this.state.email, this.state.password)
      .then(res => {
        this.props.history.push('/');
      })
      .catch(err => console.error(error));
  }

我唯一能想到的就是你有history.replace,尝试更改为history.push。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Firebase 身份验证 - Firebase 注册并重定向后用户未登录 的相关文章

随机推荐