Search code examples
angularjsfirebaseangularjs-servicefirebase-security

angularjs with firebase auth share service


Halo all,

I want to use angularjs with firebase simple login (facebook). But I have no idea how to create the auth share service.

What I want to do is

  • create a authentication service
  • use this auth service to check if user loggedin in every controllers
  • controllers will do the $location if user loggedin/not-login

I also new to angularjs but I don't know which services should I use in this situation. service or factory?

How can I put the below code in angular service then tell each controller if user logged in or not?

var firebaseRef = new Firebase("https://test.firebaseio.com");
var auth = new FirebaseAuthClient(firebaseRef, function(error, user) {
   if (user) {
      console.log(user);
   } else if (error) {
      console.log(error);
   } else {
      console.log('user not login');
   }
});

Here is what i'm guessing, return user value from authService so in controllers if authService.user exists then redirect to loggedin page otherwise show login dialog with a login button to call the following code

authService.login('facebook');

Let me know if I can do like this, or there is a better way?


Solution

  • Here is what I'm using so far...

    I haven't implemented the redirecting yet but the rest works.

    p4pApp.factory('firebaseAuth', function($rootScope) {
    var auth = {},
        FBref = new Firebase(p4pApp.FIREBASEPATH);
    
    auth.broadcastAuthEvent = function() {
        $rootScope.$broadcast('authEvent');
    };
    
    auth.client = new FirebaseAuthClient(FBref, function(error, user) {
        if (error) {
        } else if (user) {
            auth.user = user;
            auth.broadcastAuthEvent();
        } else {
            auth.user = null;
            auth.broadcastAuthEvent();
        }
    });
    
    auth.login = function() {
        this.client.login('facebook');
    };
    
    auth.logout = function() {
        this.client.logout();
    };
    
    return auth;
    });
    

    The AuthCtrl is common to all/most of my pages.

    var AuthCtrl = function($scope, firebaseAuth) {
    $scope.login = function() {
        firebaseAuth.login();
    };
    
    $scope.logout = function() {
        firebaseAuth.logout();
    };
    
    $scope.isLoggedIn = function() {
        return !!$scope.user;   
    };
    
    // src: Alex Vanston (https://coderwall.com/p/ngisma)
    $scope.safeApply = function(fn) {
        var phase = this.$root.$$phase;
        if (phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) {
                fn();
            }
        } else {
            this.$apply(fn);
        }
    };
    
    $scope.$on('authEvent', function() {
        $scope.safeApply(function() {
            $scope.user = firebaseAuth.user;
        });
    });
    };