简体   繁体   English

Firebase-注册过程中的Auth问题

[英]Firebase - issue with Auth during registration

I am new to firebase and have managed to successfully setup an authentication with email/ password based off what I have managed to gather from the documentation/ examples online. 我是Firebase的新手,并且根据我从在线文档/示例中收集的信息成功地成功设置了电子邮件/密码身份验证。 I've encountered some strange behaviour on register though. 我在注册时遇到了一些奇怪的行为。 First of all here is my firebase auth code that sits in a React component function: 首先,这是我的Firebase身份验证代码,位于React组件函数中:

class SignupComponentInner extends Component { 
    toggleSignupLayoverAction(event){
        this.props.toggleSignupLayover("false")
    }
    signUp(e) {
        e.preventDefault();
        var firstName = $('.signup-first-name').val();
        var lastName = $('.signup-last-name').val();
        var userName = $('.signup-user-name').val();
        var password = $('.signup-user-password').val();
        var email = $('.signup-email').val();   

        var auth = firebase.auth();

        const promise = auth.createUserWithEmailAndPassword(email,password).then(function(user) {

        var user = firebase.auth().currentUser;
        user.updateProfile({
            displayName: userName,
        }).then(function() {
        // Update successful.

        // new db code here
        firebase.database().ref('users/' + user.uid).set({
            firstName: firstName,
            lastName: lastName,
            userName: userName
        })
        // end new db code here

    }, function(error) {
        // An error happened.
    });  

}, function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // [START_EXCLUDE]
    if (errorCode == 'auth/weak-password') {
        alert('The password is too weak.');
    } else {
        console.error(error);
    }
    // [END_EXCLUDE]
});

        promise.catch(e => console.log(e.message));   
        firebase.auth().onAuthStateChanged(firebaseUser => {
           if(firebaseUser) {
               console.log("logged in");
               var sendUserId = firebaseUser.uid;
               this.props.logUserIn(sendUserId)
           } else {
               console.log("not logged in")
           }
        });
    }
    render() {
       return (
           <div onClick={this.toggleSignupLayoverAction.bind(this)} className="signup-cont-par">
           <div className="signup-component-inner">
               <div className="signup-component-content" onClick={cancelBubble.bind(this)}>
               <h2>Sign up today!</h2>
               <form className="signup-form-elem">
                    <input placeholder="First Name" className="signup-first-name" type="text"></input>
                    <input placeholder="Last Name" className="signup-last-name" type="text"></input>
                    <input placeholder="Username" className="signup-user-name" type="text"></input>
                    <input placeholder="Password" className="signup-user-password" type="password"></input>
                    <input placeholder="Email Address" className="signup-email" type="text"></input>
                    <button onClick={this.signUp.bind(this)}>Sign Up</button>
               </form>
                   </div>
           </div>
           </div>
           )
    }
}

So the registration part works exactly as it should but its the login part here that is causing issues: 因此,注册部分完全可以正常工作,但是其登录部分却引起了问题:

        firebase.auth().onAuthStateChanged(firebaseUser => {
           if(firebaseUser) {
               console.log("logged in");
               var sendUserId = firebaseUser.uid;
               this.props.logUserIn(sendUserId)
           } else {
               console.log("not logged in")
           }
        });

It's basically executing twice as im getting console.log "logged in" twice on register. 它基本上是在两次使console.log在注册时“登录”时执行两次。 Not sure why that is? 不知道为什么会这样吗?

The other issue is the function that it is calling from the props this.props.logUserIn(sendUserId) This function basically hides a "create account" CTA and replaces it with a hello {{username}}. 另一个问题是它从道具this.props.logUserIn(sendUserId)调用的函数。该函数基本上隐藏了“创建帐户” CTA,并用“ {{username}}”代替。 The username updates on register but very strangely it will update to whatever username I registered on the previous register! 用户名会在注册时更新,但非常奇怪的是,它将更新为我在先前注册时注册的任何用户名! Here is the logUserIn function if it helps: 如果有帮助,这是logUserIn函数:

logUserIn(userId) {
    var db = firebase.database();
    var ref = db.ref('/users/' + userId);

    console.log(userId);

     ref.once('value').then((snapshot) => {
         var userObject = snapshot.val();
         var loggedUserName = userObject.userName;
        this.setState({
            LoggedInUsername:loggedUserName
        })
     });

    this.setState({
        loggedInState:true,
        LoggedInId:userId,
        signingUp:"inactive"
    })
},

Here loggedUserName is a state that is passed down to the main component to show the username that has just been registered (the one that is incorrectly showing the previous registered person when it should be showing the latest). 在这里, loggedUserName是一种状态,该状态会向下传递到主要组件以显示刚刚注册的用户名(在显示最近的注册人时,它会错误地显示先前的注册人)。 Not sure where I have gone wrong. 不知道我哪里出问题了。

Firebase maintains persistent connections with their servers so if you registered once, Firebase detects your browser and machine to be logged in for that newly created user. Firebase与服务器保持持久连接,因此,如果您注册一次,Firebase会为该新创建的用户检测到要登录的浏览器和计算机。 So, if you close the browser and then come back to your project on the SAME browser, Firebase still thinks you are logged in and hence, the onAuthStateChanged event handler is called. 因此,如果关闭浏览器,然后在SAME浏览器上返回项目,Firebase仍然认为您已登录,因此将onAuthStateChanged事件处理程序。

Try it out for yourself and see what happens when you open up 2 different browsers. 自己尝试一下,看看打开两种不同的浏览器时会发生什么。

To complete the whole authentication system, you need to have a logout function that will tell Firebase that this user has logged out ( https://firebase.google.com/docs/auth/web/password-auth#next_steps ) 要完成整个身份验证系统,您需要具有注销功能,该功能将告知Firebase该用户已注销( https://firebase.google.com/docs/auth/web/password-auth#next_steps

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM