Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep a user logged into a firebase app after refresh?

Tags:

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!

like image 548
Justin Haddock Avatar asked Aug 27 '15 15:08

Justin Haddock


2 Answers

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.

like image 188
Frank van Puffelen Avatar answered Oct 26 '22 14:10

Frank van Puffelen


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)

like image 31
mflodin Avatar answered Oct 26 '22 14:10

mflodin