Skip to main content

angularFire - bug in angularFireAuth

4 min read

Older Article

This article was published 13 years ago. Some information may be outdated or no longer applicable.

I’m working on a project that uses angularFire and its new angularFireAuth function to authenticate users via the Firebase Authentication system. I hit a bug, reported it to the angularFire team, and here’s what went wrong, plus a proposed fix (with one remaining issue).

To show the problem, I’m using the code from the official AngularJS phone tutorial. The application requirements:

  • Display a list of phones from the Firebase database
  • Clicking a phone name should redirect to the phone detail page
  • If the user is authenticated, show the details; otherwise redirect to the login page

The router:

angular.module('phonecat', ['firebase']).config([
  '$routeProvider',
  function ($routeProvider) {
    $routeProvider
      .when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: PhoneListCtrl,
        authRequired: false,
        pathTo: '/phones',
      })
      .when('/phones/:age', {
        templateUrl: 'partials/phone-detail.html',
        controller: PhoneDetailCtrl,
        authRequired: true,
        pathTo: '/phones/:phoneId',
      })
      .when('/login', {
        templateUrl: 'partials/login.html',
        controller: LoginCtrl,
        authRequired: false,
        pathTo: '/login',
      })
      .otherwise({
        redirectTo: '/phones',
      });
  },
]);

The controller:

'use strict';

function PhoneListCtrl($scope, angularFire, angularFireAuth) {
  var url = 'https://<link>.firebaseio.com/';
  var promise = angularFire(url, $scope, 'phones', []);
  angularFireAuth.initialize(url, { scope: $scope, name: 'user' });
}

function PhoneDetailCtrl($scope, $routeParams, angularFire, angularFireAuth) {
  var url = 'https://<link>.firebaseio.com/' + $routeParams.age;
  angularFireAuth.initialize(url, { scope: $scope, path: '/login' });
  $scope.$on('angularFireAuth:login', function (evt, user) {
    var promise = angularFire(url, $scope, 'phone', {});
  });
  $scope.$on('angularFireAuth:logout', function (evt) {
    console.log('you are logged out.');
  });
  $scope.$on('angularFireAuth:error', function (evt, err) {
    console.log(err);
  });
}

function LoginCtrl($scope, angularFire, angularFireAuth) {
  var url = 'https://<link>.firebaseio.com';
  angularFireAuth.initialize(url, { scope: $scope });
  $scope.form = {};
  $scope.login = function () {
    console.log('called');
    var username = $scope.form.username;
    var password = $scope.form.password;
    angularFireAuth.login('password', {
      email: username,
      password: password,
      rememberMe: false,
    });
  };
}

Some HTML snippets:


<div class="container-fluid">
    <div class="row-fluid">
      <div class="span4">
        <ul class="phones">
          <li ng-repeat="phone in phones">
            <a href="#/phones/{{phone.age}}">{{phone.id}}</a>
            <p>{{phone.snippet}}</p>
          </li>
        </ul>
      </div>
    </div>
  </div>

  {{user.email}} | <a ng-click="logout()">Logout</a>
  you are look looking at {{ phone.name }}
</span>
<span ng-hide="user">
  login pls!
</span>

<input type="text" name="username" ng-model="form.username"><br>
<input type="text" name="password" ng-model="form.password"><br>
<button name="login" id="login" ng-click="login()">login</button>

The index.html would of course have the app declaration, paths to all required angular.js files, plus your app.js and controller.js files.

For the data structure, I imported the phones.json file into Firebase. The original structure looked like this:

[
  {
    "age": 0,
    "id": "motorola-xoom-with-wi-fi",
    "imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
    "name": "Motorola XOOM\u2122 with Wi-Fi",
    "snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
  },
  {
    "age": 1,
    "id": "motorola-xoom",
    "imageUrl": "img/phones/motorola-xoom.0.jpg",
    "name": "MOTOROLA XOOM\u2122",
    "snippet": "The Next, Next Generation\n\nExperience the future with MOTOROLA XOOM, the world's first tablet powered by Android 3.0 (Honeycomb)."
  }
]

Note Don’t forget to enable the correct Firebase authentication method and add a user. Refer to this documentation for more information.

Run the application. Click a phone name and you’ll be redirected to the login page. Enter valid credentials. Instead of landing on the correct page, you’ll hit an endless loop: /phone/:age, then /login, then /phone/:age again, until the browser gives up. (My browser crashed because I was debugging in the JS console and the loop generated hundreds of entries.)

After some digging (and help from Anant, the developer behind angularFire), I found the root cause. It boils down to variable declarations in the angularFire.js code.

Here’s the fix. Find the this._redirectTo = null; and this._authenticated = false; lines in the initialise function, and comment them out. Then find the client declaration and modify it:

var client = new FirebaseSimpleLogin(this._ref, function(err, user) {
  self._cb(err, user);
    if (err) {
      $rootScope.$broadcast("angularFireAuth:error", err);
    } else if (user) {
        this._authenticated = true;
        this._redirectTo = $route.current.pathTo;
        self._loggedIn(user)
    } else {
        this._authenticated = false;
        self._loggedOut();
    }
  });
  this._authClient = client;
},

I moved the commented-out lines into the else if block. Retry now and you’ll be redirected to the correct page after entering valid credentials.

Note There’s another open issue with angularFire: /phones/:id will redirect to /phones/:id literally, without replacing :id with the actual value. Follow this issue on GitHub to learn more.

One remaining issue: if a user is already logged in (valid user object exists) and navigates to /login, they won’t be automatically redirected, nor will the user object be visible. I’ll keep thinking about a fix. If you want to track progress, follow the issue on GitHub.