在身份验证系统中创建用户之后,在数据库中创建用户?

时间:2019-05-27 07:48:01

标签: javascript firebase

我在JavaScript应用程序中使用了Firebase。但是,当我创建用户(电子邮件和密码)时,它将在身份验证中创建,但不在数据库中创建。您能告诉我如何在Javascript中建立两者之间的联系吗?

谢谢!

这里有我的代码,包括login.html,login.js,main.js,main.html和firebase.js。

Login.js :

(function(){

// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());

    var uiConfig = {
        callbacks: {
          signInSuccessWithAuthResult: function(authResult, redirectUrl) {
            // User successfully signed in.
            // Return type determines whether we continue the redirect automatically
            // or whether we leave that to developer to handle.
            return true;
          },
          uiShown: function() {
            // The widget is rendered.
            // Hide the loader.
            document.getElementById('loader').style.display = 'none';
          }
        },
        // Will use popup for IDP Providers sign-in flow instead of the default, redirect.
        signInFlow: 'popup',
        signInSuccessUrl: 'main.html',
        signInOptions: [
          // Leave the lines as is for the providers you want to offer your users.
          //firebase.auth.GoogleAuthProvider.PROVIDER_ID,
          //firebase.auth.FacebookAuthProvider.PROVIDER_ID,
          //firebase.auth.TwitterAuthProvider.PROVIDER_ID,
          //firebase.auth.GithubAuthProvider.PROVIDER_ID,
          firebase.auth.EmailAuthProvider.PROVIDER_ID,
          //firebase.auth.PhoneAuthProvider.PROVIDER_ID
        ],
        // Terms of service url.
        tosUrl: 'main.html',
        // Privacy policy url.
        privacyPolicyUrl: 'main.html'
      };

      // The start method will wait until the DOM is loaded.
    ui.start('#firebaseui-auth-container', uiConfig);


})()


Main.js : 

    var mainApp = {};

(function() {

    var firebase = app_fireBase;

    firebase.auth().onAuthStateChanged(function(user) {
         if (user) {
              // User is signed in. 

              uid = user.uid;

              //writeUserData(uid);

            }else{

                uid = null;
                window.location.replace("login.html");
            }
        });


        function logOut(){

            firebase.auth().signOut();
        }

        //function writeUserData(uid) {
        //    firebase.database().ref('users/' + uid).set({
        //        uid : uid
        //    });
        //  }

        mainApp.logOut = logOut;

})()


firebase.js : 

var app_fireBase = {};

(function (){


    const firebaseConfig = {
        apiKey: "AIzaSyBC-tE5w3BYAV4eVtiT2Dy3EUsl5ymameE",
        authDomain: "durian-7ea02.firebaseapp.com",
        databaseURL: "https://durian-7ea02.firebaseio.com",
        projectId: "durian-7ea02",
        storageBucket: "durian-7ea02.appspot.com",
        messagingSenderId: "1066960181281",
        appId: "1:1066960181281:web:a5aa7781ba17b8fc"
      };

      firebase.initializeApp(firebaseConfig);


      app_fireBase = firebaseConfig;

})()


main.html : 

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Main page</title> <script src="gstatic.com/firebasejs/6.0.4/firebase.js"></script> </head> <body> <h1>Welcome to main page</h1> <button onclick="mainApp.logOut()">Log out</button> <script> </script> <script type="text/javascript" src="fireBase.js"></script> <script type="text/javascript" src="main.js"></script> </body> </html> 

login.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login page</title>

    <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase.js"></script>
    <script src="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js"></script>
    <link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.css" />

</head>
<body>

<!-- The surrounding HTML is left untouched by FirebaseUI.
     Your app may use that space for branding, controls and other customizations.-->
     <h1>Welcome</h1>
     <div id="firebaseui-auth-container"></div>
     <div id="loader">Loading...</div>




    <script type="text/javascript" src="fireBase.js"></script>
    <script type="text/javascript" src="login.js"></script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

这是预期的行为。 Firebase身份验证独立于Firestore。但是您可以创建一个Firestore集合,并将uid用作文档密钥。这样,您可以存储特定于每个用户的数据。另外,请不要忘记调整您的安全规则,以使某个用户无法更改其他用户的数据。您应该能够在Firebase文档中找到所有内容来完成此任务:

Firebase Authentication

Cloud Firestore

答案 1 :(得分:0)

FirebaseUI JavaScript library文档中所述,“ signInSuccessWithAuthResult回调在用户成功登录后被调用”和“如果该回调返回false 或不返回,则页面不会自动重定向。”

因为,传递给回调的authResult是一个firebaseui.auth.AuthResult对象(包括当前登录的用户),您可以按以下方式使用它,使用{ {3}}方法。成功异步写入数据库后,可以在then()方法中相应地重定向页面。

var uiConfig = {
    callbacks: {
      signInSuccessWithAuthResult: function(authResult, redirectUrl) {
        // User successfully signed in.
        // Return type determines whether we continue the redirect automatically
        // or whether we leave that to developer to handle.

        // HERE we take the option of handling the redirect ourself

        console.log(authResult.user);
        var userObject = {
            displayName: authResult.user.displayName,
            email: authResult.user.email
            //HERE add any extra info you want
        };
        firebase.database().ref("users/" + authResult.user.uid).set(userObject).
        then(function() {
            console.log('user info saved to realtime database');
            window.location.replace("main.html");
            //If you want to see the output of the console.logs just comment out the above line
        })

      },
    //.....