问题
In Firebase 2 I was able to do a synchronous check to see if the user was logged in, e.g:
if (!ref.getAuth()) ..go to login page
else ..show page
I can access the currentUser
state with firebase.auth().currentUser
so I tried to do:
if (!firebase.auth().currentUser) ..go to login page
else ..show page
The problem is that this is always initially null, so it redirects to the login page, then a few moments later onAuthStateChanged
happens and the user is logged in.
Is there still a way to synchronously check this? Or otherwise is there a promise I can listen to so that I can show a loading spinner or something? Thanks.
回答1:
I've been using an auth state listener to determine if the user is signed in.
auth.onAuthStateChanged(function(user) {
console.log('authStateChanged', user);
if (user) {
console.log("Welcome UID:" + user.uid);
}
});
When you attach that listener right away, it will fire with the correct state.
When I run the app, sign in and reload the page, the log outputs:
authStateChanged Fl {...}
Welcome UID:052289713245805425655890E9024AB4ADBA5404B3C0
So you can use the first time the listener is called to detect if the user is already signed in.
回答2:
I had the same issue, and because I'm using Angular, I found a synchronous call $getAuth() in AngularFire. https://github.com/firebase/angularfire/blob/master/docs/reference.md#getauth
Maybe there's an equivalent in ReactFire library as well. :)
来源:https://stackoverflow.com/questions/37367640/firebase-3-ref-getauth-equivalent