0
votes

I'm trying to persist the Firebase user authentication state across multiple pages.

    $scope.loginGoogle = function() {
        console.log("Got into google login");
        ref.authWithOAuthPopup("google", function(error, authData) { 
           $scope.loggedIn = true;
           $scope.uniqueid = authData.google.displayName;
                 }, {
           remember: "sessionOnly",
           scope: "email"
        });
    };


        function checkLogin() {
           ref.onAuth(function(authData) {
             if (authData) {
                // user authenticated with Firebase
                console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
             } else {
               console.log("Nope, user is not logged in.");
             }
           });
        };

However, when the checkLogin function is called in another page, authData is not defined, even though the user has logged in on the login page. What seems to be the matter?

1
Where are you defining your ref variable in onAuth. Can you provide a JSBin, or Plnker that shows your problem? - David East
We have a jsfiddle right here: jsfiddle.net/leeuwenhoek/9abg634q/1 - leeuwenhoek
Your example isn't loading properly. It's throwing errors in the console. - David East

1 Answers

6
votes

There are two things to know here.

First, you're using the JS Client auth methods in conjunction with AngularFire. While this is not a bad thing, you need to be aware of a few gotchas.

Second, you can use the $firebaseAuth module in AngularFire 0.9 to not deal with all of the crazy stuff below.

When using Firebase JS client level functions, Angular will not always pick up on them due to its digest loop. This is true for any external JS library. The way to get around this is to use the $timeout service.

CodePen

// inject the $timeout service
app.controller("fluttrCtrl", function($scope, $firebase, $timeout) {

  var url = "https://crowdfluttr.firebaseio.com/";
  var ref = new Firebase(url);
  $scope.loginGoogle = function() {
    console.log("Got into google login");

    ref.authWithOAuthPopup("google", function(error, authData) {

    // wrap this in a timeout to allow angular to display it on the next digest loop
    $timeout(function() {
      $scope.loggedIn = true;
      $scope.uniqueid = authData.google.displayName;
    });

    }, {
      remember: "sessionOnly",
      scope: "email"
    });

  });

});

By wrapping the $scope properties in the $timeout another cycle will be run and it will display on the page.

Ideally, you don't want to deal with this yourself. Use $firebaseAuth module built into AngularFire. You need to upgrade to the 0.9 version to use the module.