onAuthStateChanged firing incrementally each time I log in and out.

1,815 views
Skip to first unread message

Irman Ahmetovic

unread,
Jul 28, 2016, 11:33:57 PM7/28/16
to Firebase Google Group
I'm working off of the SBAdmin Dashboard template and attempting to add Firebase auth. I have a log in state with the LoginController. I also use the LoginController in a dashboard directive (Top right, profile icon with log in/out button). 

I can log in and out fine, however each time a log in and out the onAuthStateChanged fires an additional time. So when I log in it fires once, then when I log out It fires twice, then 3 times and so on. 


LoginController:

angular.module('sbAdminApp')
  .controller('LoginCtrl', ['$scope', '$rootScope', '$state', 'Auth', function($scope, $rootScope, $state, Auth) {
    console.log('LoginCtrl');

    var auth = Auth;
    $rootScope.user = {};

    $scope.toggleSignIn  = function () {
      console.log("toggleSignIn");
      if (typeof $rootScope.user.displayName === 'undefined') {
      //if(!currentAuth)
        auth.$signInWithPopup("google")
          .then(function(firebaseUser) {
            console.log("Signed in as:", firebaseUser.uid);
            $state.go('dashboard.home')

        })
          .catch(function(error) {
            console.log("Authentication failed:", error);
        });
      }else{
        auth.$signOut();
        $rootScope.user = {};
        $state.go('login');
      }
    } // end toggleSignIn


    // any time auth state changes, add the user data to scope
    auth.$onAuthStateChanged(function(user) {
      console.log("onAuthStateChanged");
      //console.log(user);
      if (user) {
          console.log('logged in');
          // User is signed in.
          $rootScope.user.displayName = user.displayName;
          $rootScope.user.email = user.email;
          $rootScope.user.emailVerified = user.emailVerified;
          $rootScope.user.photoURL = user.photoURL;
          $rootScope.user.isAnonymous = user.isAnonymous;
          $rootScope.user.uid = user.uid;
          $rootScope.user.refreshToken = user.refreshToken;
          $rootScope.user.providerData = user.providerData;

          console.log('Rootscope.user set');
          //console.log($rootScope.user);

          $state.go('dashboard.home');
        }
        else{
          console.log('logged out');
          $rootScope.user = {};
        }

    });

also have the below in the run() block:

  $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
        // We can catch the error thrown when the $requireSignIn promise is rejected
        // and redirect the user back to the home page
        if (error === "AUTH_REQUIRED") {
          $state.go("login");
        }
      });


What can be causing this?

Sorry if I'm missing something or not submitting the question in the right format I'm fresh to Angular and this is my first post here. 

Thanks in advance. 


Jacob Wenger

unread,
Jul 29, 2016, 1:26:15 PM7/29/16
to fireba...@googlegroups.com
I assume this is because you are setting up multiple onAuthStateChanged() listeners. Can you put together a minimal repro in JSFiddle or Plunker? Also, please let us know what versions of Firebase, Angular, and AngularFire you are using. Using the latest stable versions is a good place to start in case you aren't.

Cheers,
Jacob

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To post to this group, send email to fireba...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/firebase-talk/a4bd1086-3bf9-4a5c-a647-39df997bf127%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Irman Ahmetovic

unread,
Jul 31, 2016, 10:14:05 PM7/31/16
to Firebase Google Group
Hey Jacob, 

Thanks for the reply. 

I'm using Angular 1.5.7, Firebase 3.0.3, AngularFire 2.0.0
Here's a stripped down Plunker however I was not able to get it to work: https://plnkr.co/edit/U3jxqGvq9UcsmNgG61qc?p=preview

Hope it's still helpful. 
Thanks again, 

Irman

Kasbolat Kumakhov

unread,
Aug 1, 2016, 6:52:40 AM8/1/16
to Firebase Google Group
BTW, i'm having almost same issue with onAuthStateChanged() but with some small distinction.
My app is an Android app and FirebaseAuth.getInstance().addAuthStateListener() is sure called only once per app, because it's being called inside Application class constructor.
Still, i get several onAuthStateChanged() events with the same state.

public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
MainApplication.logInfo("DB_AUTH_STATE: " + (user != null));
}

With this code i get several "DB_AUTH_STATE: true" calls in a row (one after another).

пятница, 29 июля 2016 г., 20:26:15 UTC+3 пользователь Jacob Wenger написал:

Ron Royston

unread,
Aug 1, 2016, 12:59:56 PM8/1/16
to Firebase Google Group
onAuthStateChanged fires on every page reload as well as any time the users auth state changes.  Simple add a console.log('onAuthStateChange ran with user = ' + user.email) and watch your console.  Don't have more than one onAuthStateChange listener in your page.

Irman Ahmetovic

unread,
Aug 1, 2016, 7:22:29 PM8/1/16
to Firebase Google Group
For Angular, does that mean it should then be in the run() block?

Jacob Wenger

unread,
Aug 2, 2016, 12:22:38 PM8/2/16
to fireba...@googlegroups.com
Unfortunately, your Plunkrr doesn't work. When I first visit the page, it says' I'm not logged in but all I see is the "Logout" button. Looking at your onAuthStateChanged() code, it looks correct. Are you sure you are not just misunderstanding how it is supposed to work? As Ron said, it will re-fire every time there is a change in the authentication state. Without a working repro, I can't debug any further.

Cheers,
Jacob

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To post to this group, send email to fireba...@googlegroups.com.

Irman Ahmetovic

unread,
Aug 5, 2016, 6:04:42 PM8/5/16
to Firebase Google Group
I may totally be misunderstanding how it works. What I'm going by is the console log. This is what I'm seeing when I log in and out:

Initial page (logged out):

LoginCtrl   - ( First line in Login Controller)
onAuthStateChanged - ( First line in onAuthStateChanged function)
logged out  (if else inside onAuthStateChanged function)

Click login button:

toggleSignIn   - (toggleSignIn inside the Login Controller)
onAuthStateChanged 
logged in  (if else inside onAuthStateChanged function)
Rootscope.user set (if else inside onAuthStateChanged function)
LoginCtrl      (******Here's where it starts repeating *******)
onAuthStateChanged
logged in
Rootscope.user set


Click logout button:

toggleSignIn
LoginCtrl
onAuthStateChanged
logged out
onAuthStateChanged
logged out
onAuthStateChanged
logged out


Click log in:

toggleSignIn
onAuthStateChanged
logged in
Rootscope.user set
LoginCtrl
onAuthStateChanged
logged in
Rootscope.user set
onAuthStateChanged
logged in
Rootscope.user set
onAuthStateChanged
logged in
Rootscope.user set


This is what I was going by. Logging in and out seems to work fine app flow seems to work, but from the log i thought i didn't do something right as it seems to be repeating the login/out process.

Thanks again, 
Irman

Jacob Wenger

unread,
Aug 5, 2016, 7:06:48 PM8/5/16
to fireba...@googlegroups.com
I'm sorry, but the Plunkr you provided still does not work. Here is what it looks like when I load it:



As you can see, the console tells me I'm logged out, but the UI tells me I'm logged in.

Without being able to repro this issue, I can't tell you exactly what in your code is causing the issue.

Cheers,
Jacob



To unsubscribe from this group and stop receiving emails from it, send an email to firebase-talk+unsubscribe@googlegroups.com.

To post to this group, send email to fireba...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages