Перенаправление в onAuthStateChanged аутентификации Firebase загружает страницу бесконечно - PullRequest
0 голосов
/ 29 января 2020

Я следовал инструкциям Переполнение стека - Как перенаправить после того, как пользователь вошел в систему с аутентификацией Firebase?

index. html:

<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My auth page</title>
  <script defer src="/__/firebase/7.5.0/firebase-app.js"></script>
  <script defer src="/__/firebase/7.5.0/firebase-auth.js"></script>
  <script defer src="/__/firebase/7.5.0/firebase-database.js"></script>
  <script defer src="/__/firebase/init.js"></script>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <!-- My html code -->
  <script type="text/javascript" defer src="auth.js"></script>
</body>

</html>

auth. js:

function toggleSignIn() {
    if (firebase.auth().currentUser) {
        firebase.auth().signOut();
    } else {
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;
        if (email.length < 4) {
            alert('Please enter an email address.');
            return;
        }
        if (password.length < 4) {
            alert('Please enter a password.');
            return;
        }
        firebase.auth().signInWithEmailAndPassword(email, password).catch(function (error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            if (errorCode === 'auth/wrong-password') {
                alert('Wrong password.');
            } else {
                alert(errorMessage);
            }
            console.log(error);
        });
    }
}

function initApp() {
    console.log('start initApp');
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            console.log('logged in');
            window.location = 'admin-console.html';
        } else {
            console.log('not logged in');
            window.location = 'index.html'; //causes endless loop
        }
    });
    document.getElementById('loginbutton').addEventListener('click', toggleSignIn, false);
}

window.onload = function () {
    console.log('initialize app');
    initApp();
};

Я вижу, что этот код бесконечно l oop. Но я не вижу, что я пропустил из инструкций. Похоже, эта инструкция должна работать.

1 Ответ

1 голос
/ 29 января 2020

Когда вы вызываете метод signInWithEmailAndPassword() и он успешен, пользователь входит в систему. Поэтому, если я правильно понимаю ваше функциональное требование, вам не нужно использовать onAuthStateChanged().

Вы можете сделать что-то вроде этого:

function login() {
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    if (email.length < 4) {
        alert('Please enter an email address.');
        return;
    }
    if (password.length < 4) {
        alert('Please enter a password.');
        return;
    }

    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(userCredential => {
       console.log("User " + userCredential.user.uid + " LOGGED IN");
       window.location = 'admin-console.html';
    })
    .catch(function (error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            if (errorCode === 'auth/wrong-password') {
                alert('Wrong password.');
            } else {
                alert(errorMessage);
            }
            console.log(error);
            //Throw an error
        });
}

function logout() {
    firebase.auth().signOut()
    .then(() => {
       console.log("User SIGNED OUT");
       window.location = 'index.html';';
    })
}

function initApp() {
    console.log('start initApp');
    document.getElementById('loginbutton').addEventListener('click', login, false);
    document.getElementById('logoutbutton').addEventListener('click', logout, false);
}

window.onload = function () {
    console.log('initialize app');
    initApp();
};

Обратите внимание, что вам нужно добавить кнопку logoutbutton. Если вы хотите иметь только одну кнопку переключения (а не одну кнопку loginbutton плюс одну кнопку logoutbutton), вы можете легко адаптировать приведенный выше код.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...