Вход в Firebase через электронную почту завершается с ошибкой без сообщения об ошибке - PullRequest
0 голосов
/ 12 марта 2019

В моем приложении JavaScript Firebase я попытался настроить аутентификацию пользователя по электронной почте и одновременно синхронизировать данные пользователя с базой данных Firebase в реальном времени. Хотя наш вход в Google работал без проблем, функция, которая создает учетные записи, firebase.auth().createUserWithEmailAndPassword(email, password); не выполняется и (досадно) не выдает никаких сообщений об ошибках. Вот код: main.js: (проблемный раздел - submitAcc ())

var config = {
    apiKey: "censored",
    authDomain: "censored",
    databaseURL: "censored",
    projectId: "censored",
    storageBucket: "censored",
    messagingSenderId: "censored"
};
firebase.initializeApp(config);
var database = firebase.database();
function showAccCreate() { //Hides and shows account create button
    var x = document.getElementById("hiddenaccountcreation");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
function submitAcc() { //On submit button pressed
    alert("Signing in");
    var email = document.getElementById("emailinput").value;
    var password = document.getElementById("passinput").value;
    var username = document.getElementById("usernameinput").value;
    //console.log(email + password +username);
    var user;
    alert("recorded values");
    firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(email,password).then(function(result) {
        alert("Gets into .then");
        var user = firebase.auth().currentUser;
        var uidvalue = user.uid;
        console.log(uidvalue);
        console.log(uidvalue);
        alert("User value recorded");
        writeUserDataFromEmailSignin(email, username,uidvalue);
        alert(user.uid);
    }).catch(function(error) {
        alert(error.message);
        console.log(error.message);
        console.log(error.code);
    });
}


//Testing if auth state changes
firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
        alert("User is signed in.");
        document.getElementById("debugtest").innerHTML = "Signed in";
    }
});
function writeUserDataFromEmailSignin(email, name, uuid) { //Writes user data to database if user signs in
    alert("Entered function");
    database.ref('users/' + uuid).set({
        "name": name,
        "email": email,
        "uid": uuid,
    }).then(function() {
        alert("Completed");
    }).catch(function() {
        console.log(error.message);
        console.log(error.code);
    })
}
function showsignin() {
    var x = document.getElementById("hiddensignin");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
function googlesignin() { //Signs people into app via Google
    var provider = new firebase.auth.GoogleAuthProvider();
    provider.addScope("https://www.googleapis.com/auth/contacts.readonly");
    firebase.auth().languageCode = 'en';
    firebase.auth().signInWithPopup(provider).then(function(result) {
        var token = result.credential.accessToken; //Google Auth access token
        var user = result.user; //Contains all user info that Google provided us
        writeToDatabaseFromGoogle(user.email, user.displayName, user.uid, user.photoUrl);
    }).catch(function(error) {
        console.log(error.message);
        console.log(error.code);
    });


}
function writeToDatabaseFromGoogle(email, name, uuid, image_url) { //Writes user data to database from Google signin
    database.ref("users/" + uuid).set({
        "name": name,
        "email": email,
        //"imageUrl": image_url,
        "uid": uuid,
    }).catch(function(error) {
        console.log(error.message);
        console.log(error.code);
    });
}
function signInUser() { //Uses email sign-in so signin to existing account
    var email = document.getElementById("emailreauth");
    var pass = document.getElementById("passreauth");
    // noinspection JSUnresolvedFunction
    firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
        //Handle errors here
        let errorCode = error.code;
        let errorMessage = error.MESSAGE;
        console.log(errorCode);
        console.log(errorMessage);
    });
}

и файл index.html:

<!DOCTYPE html>
<!--suppress HtmlRequiredLangAttribute -->
       <html>
    <head>
        <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase.js"></script>
        <script>
            // Initialize Firebase
            var config = {
                apiKey: "AIzaSyAhglAXFWaJhtvOrfeugAMgJHrBw5CUNEc",
                authDomain: "projectcrosscomm.firebaseapp.com",
                databaseURL: "https://projectcrosscomm.firebaseio.com",
                projectId: "projectcrosscomm",
                storageBucket: "projectcrosscomm.appspot.com",
                messagingSenderId: "412861101382"
            };
            firebase.initializeApp(config);
        </script>
        <!-- Firebase App is always required and must be first -->
        <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-app.js"></script>

        <!-- Add additional services that you want to use -->
        <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-auth.js"></script>
        <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-database.js"></script>


        <!-- Comment out (or don't include) services that you don't want to use -->
        <!-- <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-storage.js"></script> -->


        <script src="main.js" rel="script"></script>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Project Cross Comm!</title>
        <link rel="stylesheet" href="stylesheet.css">
    </head>
    <body>
    <button id="accountcreate" onclick="showAccCreate()">Create your account here!</button>
    <button id="showsignin" onclick="showsignin()">Already have an account?</button>
    <button2 id="googlesignin" onclick="googlesignin()">Sign in with Google</button2>

        <h1>Project Cross Comm!</h1>
        <h2 id="subtitle">
        Welcome to <strong>Project Cross Comm!</strong>
        </h2>
        <img height="200px" src="https://i.kym-cdn.com/entries/icons/mobile/000/013/564/doge.jpg" width="260px" alt="If you can't see this image you're a pleb">
        <h2></h2>
        <p id="desc"> Project Cross Comm is a free to use chatting program that runs in your browser. All the chats are encrypted, so no one can read your chats. Enjoy the program and chat away.</p>
        <div id="hiddenaccountcreation">
            <form>
                <fieldset>
                    <legend>Account Creation</legend> <!--Create account via email sign-in-->
                    <p>
                        <label for="usernameinput">Username</label>
                        <input type="text" id="usernameinput" name="createUsername" placeholder="Username">
                    <p>
                        <label for="emailinput">Email</label>
                        <input type="email" id="emailinput" value="" placeholder="example@example.com" name="createEmail">
                    </p>
                    <p>
                        <label for="passinput">Password</label>
                        <input type="password" id="passinput" value="" placeholder="password" name="createPass">
                    </p>
                    <button id="submit" onclick="submitAcc()">SUBMIT</button>
                </fieldset>
            </form>
        </div>
        <div id="hiddensignin">
            <form>
                <fieldset>
                    <legend>Sign In</legend>
                    <p>
                        <label for="usernamereauth">Username</label>
                        <input type="text" id="usernamereauth" value="">
                    <p>
                        <label for="emailreauth">Email</label>
                        <input type="email" id="emailreauth" value="">
                    </p>
                    <p>
                        <label for="passreauth">Password</label>
                        <input type="password" id="passreauth" value="">
                    </p>
                    <button id="signin" onclick="signInUser()">SUBMIT</button>
                </fieldset>
            </form>
        </div>
        <div id="getthisblockoutofmygoddamnedway"> <!--Problematic code block that another member of my team put there -->
            <a style = "color: white; "id="link" href="InfoPage.html">Click here for more information.</a>
            <h6></h6>
            <a style = "color: white; "id="link2" href="ChatLayout.html">Click Here To Chat</a>
            <h6></h6>
            <a style = "color: white; "id="link3" href="https://app.termly.io/document/privacy-policy/0ae020d8-ee05-4202-a0c7-d4ff19e8f661">Privacy Policy </a>

        </div>
    </body>
    <footer>
        <p id="debugtest" class="debug">Haven't Been Signed In Yet</p>
        <noscript>Man, sucks for you! We only support modern, functioning browsers. Maybe you should get JavaScript </noscript>
    </footer>
</html>

Самое последнее предупреждение, которое получает моя программа, - alert("recorded values");, дальнейшие предупреждения не выполняются. Javascript не выдает никаких ошибок во время процесса; консоль пуста. Есть ли способ узнать, что не так, или даже заставить Javascript быть более многословным и регистрировать его память так часто?

Ответы [ 2 ]

1 голос
/ 13 марта 2019

Ваша текущая проблема в том, что вы не можете сохранить значения в БД с помощью метода submitAcc() .Этот method вызывается, когда пользователь создает учетную запись.Я исправил и внес некоторые изменения, пожалуйста, проверьте и дайте мне знать, если это работает для вас.

Я добавил две функции logout() и status(), чтобы понять, в чем проблема.Я бы посоветовал вам удалить их.

Я также наблюдал в методе signInUser().Вы пропустили значения .value до Email и Password и исправили их.

См. Изображение ниже, когда пользователь нажимает кнопку «Создать учетную запись». Я зарегистрировал его данные в консоли.

enter image description here

Сохранение базы данных Информация о пользователе:

enter image description here

Код

    
  
  var database = firebase.database();


  function showAccCreate() { //Hides and shows account create button
      var x = document.getElementById("hiddenaccountcreation");
      if (x.style.display === "none") {
          x.style.display = "block";
      } else {
          x.style.display = "none";
      }
  }
  function submitAcc() { //On submit button pressed
      alert("Signing in");
      var email = document.getElementById("emailinput").value;
      var password = document.getElementById("passinput").value;
      var username = document.getElementById("usernameinput").value;
      console.log(email + password +username);
      alert("recorded values");


      firebase.auth().createUserWithEmailAndPassword(email,password).then(function(result) {
          alert("Gets into .then");
          var user = firebase.auth().currentUser;
          var uidvalue = user.uid;
          console.log(uidvalue);
          console.log(uidvalue);
          alert("User value recorded");
          writeUserDataFromEmailSignin(email, username,uidvalue);
          alert(user.uid);
      }).catch(function(error) {
          alert(error.message);
          console.log(error.message);
          console.log(error.code);
      });
  }


  function writeUserDataFromEmailSignin(email, name, uuid) { //Writes user data to database if user signs in
    alert("Entered function");
    database.ref('users/' + uuid).set({
        "name": name,
        "email": email,
        "uid": uuid,
    }).then(function() {
        alert("Completed");
    }).catch(function() {
        console.log(error.message);
        console.log(error.code);
    })
}

  

  function logout()
  {
    firebase.auth().signOut().then(function() {
      // Sign-out successful.
    }).catch(function(error) {
      // An error happened.
    });
  }

  function status()
  {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        var emailv =user.email;
        console.log("User is signed in. em ankunav enti "+ emailv);
      } else {
        console.log("No user is signed in."); 
      }
    });
  }
  
  //Testing if auth state changes
  firebase.auth().onAuthStateChanged(function (user) {
      if (user) {
          alert("User is signed in.");
          document.getElementById("debugtest").innerHTML = "Signed in";
      }
      else
      {
        document.getElementById("debugtest").innerHTML = "NOT LOGGED IN ";
      }
  });


  
  function showsignin() {
      var x = document.getElementById("hiddensignin");
      if (x.style.display === "none") {
          x.style.display = "block";
      } else {
          x.style.display = "none";
      }
  }
  
  
  function signInUser() { //Uses email sign-in so signin to existing account
      var email = document.getElementById("emailreauth").value;
      var pass = document.getElementById("passreauth").value;
      // noinspection JSUnresolvedFunction
      firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
          //Handle errors here
          let errorCode = error.code;
          let errorMessage = error.MESSAGE;
          console.log(errorCode);
          console.log(errorMessage);
      });
  }

  
<!DOCTYPE html>
<!--suppress HtmlRequiredLangAttribute -->
       <html>
    <head>
        
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "hmcalreac",
    authDomain: "kbckyc",
    databaseURL: "https://abc.dmc",
    projectId: "test12d",
    storageBucket: "t11",
    messagingSenderId: "11"
  };
  firebase.initializeApp(config);
</script>


        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Project Cross Comm!</title>
        
    </head>
    <body>
    <button id="accountcreate" onclick="showAccCreate()">Create your account here!</button>
    <button id="showsignin" onclick="showsignin()">Already have an account?</button>
    <button2 id="googlesignin" onclick="googlesignin()">Sign in with Google</button2>

        <h1>Project Cross Comm!</h1>
        <h2 id="subtitle">
        Welcome to <strong>Project Cross Comm!</strong>
        </h2>
        <img height="200px" src="https://i.kym-cdn.com/entries/icons/mobile/000/013/564/doge.jpg" width="260px" alt="If you can't see this image you're a pleb">
        <h2></h2>
        <p id="desc"> Project Cross Comm is a free to use chatting program that runs in your browser. All the chats are encrypted, so no one can read your chats. Enjoy the program and chat away.</p>
        <div id="hiddenaccountcreation">
            
                <fieldset>
                    <legend>Account Creation</legend> <!--Create account via email sign-in-->
                    <p>
                        <label for="usernameinput">Username</label>
                        <input type="text" id="usernameinput" name="createUsername" placeholder="Username">
                    <p>
                        <label for="emailinput">Email</label>
                        <input type="email" id="emailinput" value="" placeholder="example@example.com" name="createEmail">
                    </p>
                    <p>
                        <label for="passinput">Password</label>
                        <input type="password" id="passinput" value="" placeholder="password" name="createPass">
                    </p>
                    <button id="submit" onclick="submitAcc()">SUBMIT TO CREATE ACCOUNT </button>
                </fieldset>
            
        </div>
        <div id="hiddensignin">
            
                <fieldset>
                    <legend>Sign In</legend>
                    <p>
                        <label for="usernamereauth">Username</label>
                        <input type="text" id="usernamereauth" value="">
                    <p>
                        <label for="emailreauth">Email</label>
                        <input type="email" id="emailreauth" value="">
                    </p>
                    <p>
                        <label for="passreauth">Password</label>
                        <input type="password" id="passreauth" value="">
                    </p>
                    <button id="signin" onclick="signInUser()">SUBMIT To Signin to console</button>
                </fieldset>
            
        </div>

        <button id=mystat onclick="status()">CLICK me to GET Status</button>

        <button id=mystat onclick="logout()">CLICK me to logout </button>
       
        
        <div id="getthisblockoutofmygoddamnedway"> <!--Problematic code block that another member of my team put there -->
            <a style = "color: white; "id="link" href="InfoPage.html">Click here for more information.</a>
            <h6></h6>
            <a style = "color: white; "id="link2" href="ChatLayout.html">Click Here To Chat</a>
            <h6></h6>
            <a style = "color: white; "id="link3" href="https://app.termly.io/document/privacy-policy/0ae020d8-ee05-4202-a0c7-d4ff19e8f661">Privacy Policy </a>

        </div>
        <script src="ne2.js" rel="script"></script>
    </body>


    <footer>
        <p id="debugtest" class="debug">Haven't Been Signed In Yet</p>
        <noscript>Man, sucks for you! We only support modern, functioning browsers. Maybe you should get JavaScript </noscript>
    </footer>
</html>
1 голос
/ 13 марта 2019

Можете ли вы попробовать это?Это работает в моем случае.

    firebase.auth().signInWithEmailAndPassword(email, password)
        .then(response => {
            const uid = response.user.uid;   // you have uid
            response.user.getIdToken()
                .then(token => {
                    // do anything with token
                })
                .catch(error => {
                    // any error handling
                })
        })
        .catch(error => {
           // any error handling
        })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...