我有以下代码:
var config = {
apiKey: "xxxxx",
authDomain: "xxxxx",
databaseURL: "xxxxx",
projectId: "xxxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx"
};
firebase.initializeApp(config);
$("#loginButton").on('click', function(){
logIn($("#email").val(), $("#pwd").val());
});
$("#logoutButton").on('click', function(){
firebase.auth().signOut();
console.log("clicked logout button");
});
function logIn(email, password){
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert(error.message);
});
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("Signed in");
firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
console.log("Token = " + idToken);
console.log("Logged in!");
$("#loginButton").val(idToken);
$("#loginForm").submit();
}).catch(function(error) {
// Handle error
console.log(error);
});
}
else{
console.log("User signed out");
}
});
我在这里试图完成的是:用户填写电子邮件和密码字段,单击带有id="loginButton"
的按钮,我登录,获取令牌id并将其发送到服务器(推荐使用此表单的黑客方式发送吗?)并通过我的express应用程序(Node.js)中的Admin SDK验证令牌id。
关键是。用户登录和登出(通过刷新页面,我可以看到打印了“登录”和“用户登出”)。
但是为什么 onAuthStateChanged
只调用一次,而它应该观察/侦听身份验证状态的每个更改?
为什么我可以登录和注销,但只在开始时(页面加载时)调用onAuthStateChanged
,而不再在单击按钮时调用(loginButton
和logoutButton
)?
发布于 2018-06-15 08:54:13
首先,在身份验证状态侦听器中将firebase.auth().currentUser.getIdToken
更改为user.getIdToken
。
其次,您应该向signInWithEmailPassword promise添加一个then,并打印一些消息以查看登录是否成功。
最后,如果您登录同一用户两次而没有在其间注销,则不会触发身份验证状态侦听器。如果您希望每次用户登录时都触发某些逻辑,则应该将其放入signInWithEmailPassword promise的then块中。
https://stackoverflow.com/questions/50867561
复制相似问题