I have an application built in firebase and angular, and am wanting to be able to keep users logged in after refreshing the page. Right now I have a login screen with two basic input fields which bind to a controller
this.email = "";
this.pass = "";
this.emessage = "";
this.loginUser = function() {
ref.authWithPassword({
email: this.email,
password: this.pass
}, function(error, authData) {
if (error) {
console.log("Login Failed!", error);
this.emessage = error.message;
$scope.$apply();
} else {
dataStorage.uid = authData.uid;
$location.path('/projects');
$scope.$apply();
}
}.bind(this));
}
This is all fine and dandy and it works, but when the user refreshes the page they are logged back out. Is there some way to, when the controller loads, see if the user is already logged in and auto-redirect? Thanks!
The code you now have handles the case where the user logs on. To handle cases where the user has already logged, you use theonAuthStateChanged
method:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// User is not signed in.
}
});
Typically you only want to show the log on button in the else of this function.
Documentation: firebase.auth.Auth
Old answer (deprecated/archived):
The code you now have handles the case where the user logs on. To handle cases where the user has already logged, you monitor auth state. From the Firebase documentation on monitoring auth state:
// Create a callback which logs the current auth state
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
}
});
Typically you only want to show the log on button in the else
of this function.
As mentioned in a comment, the accepted answer no longer works. The current way of checking if a user is logged in is
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
}
});
(from https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With