即使身份验证持久性更改,Firebase 用户也不会保持登录状态



我有一个非常简单的问题,可能会让我看起来很愚蠢。我正在尝试为我的用户创建一个登录页面,当他们登录时,将他们重定向到索引页面。当我在登录页面上让用户登录时,我将AUTH PERSISTENCE设置为SESSION。它让用户在该页面上登录没有问题,但当它将用户发送到索引页面时,他们就不再登录了。我没有从登录、身份验证持久性更改、重定向或任何相关的事情中收到任何错误。

以下是登录页面的登录代码:

var remember = 0;
console.log(document.getElementById('rember').value);
function signIn() {
var email = document.getElementById('email').value;
var pass = document.getElementById('password').value;

firebase.auth().signInWithEmailAndPassword(email, pass).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log('Error Code: ' + errorCode + ' Error Message: ' + errorMessage);

});
setTimeout(function(){
if (remember == 0) {
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(function() {
// Existing and future Auth states are now persisted in the current
// session only. Closing the window would clear any existing state even
// if a user forgets to sign out.
// ...
// New sign-in will be persisted with session persistence.
return firebase.auth().signInWithEmailAndPassword(email, pass);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;

console.log('Error Code: ' + errorCode + ' Message: ' + errorMessage)
});
} else {
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(function() {
// Existing and future Auth states are now persisted in the current
// session only. Closing the window would clear any existing state even
// if a user forgets to sign out.
// ...
// New sign-in will be persisted with session persistence.
return firebase.auth().signInWithEmailAndPassword(email, pass);
})

}
var user = firebase.auth().currentUser;
if (user) {
//
} else {
console.log('Well, crap')
}
setTimeout(function(){
window.location = "https://golfcoachcentral.com/dash/html/student/index.html";
},8000)  },4000);
}

这是索引页的代码,它位于正文中:

setTimeout(function(){
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
var database = firebase.database();
var nameRef = firebase.database().ref('users/' + firebase.auth().currentUser.uid + '/name');
nameRef.on('value', function(snapshot1) {
document.getElementById('upclassnamepro').innerHtml = snapshot1.val();
});
var emailRef = firebase.database().ref('users/' + firebase.auth().currentUser.uid + '/email');
emailRef.on('value', function(snapshot2) {
document.getElementById('upclassemailpro').innerHtml = snapshot2.val();
console.log(snapshot2.val())
});
} else {
console.log('not working...');
console.log(firebase.auth().currentUser.uid);
}
},6000);

我做错了什么,导致我无法让用户登录?

firebase.auth().currentUser不会在首次加载新页面时为您提供当前登录的用户。当Firebase auth SDK首次知道用户对象时,应该使用身份验证状态观测器来获取回调。如果您需要对该用户对象执行某些操作,或者对Firebase数据库进行经过身份验证的查询,则应该等待此回调。

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
// ...
} else {
// User is signed out.
// ...
}
});

相关内容

最新更新