Obasi Obeny Oj Obasi Obeny Oj - 3 months ago 15
AngularJS Question

How to move the angularfire log in object to a service file

I want to be able to use the logged in object globally on my site. I was wondering , how I can move the object to a service and utilize it to check for loggedin. Here is my log in controller:

.controller('LoginCtrl', function ($scope, $location, userAuth) {
$scope.login = function() {
$scope.authData = null;
$scope.error = null;

userAuth.$signInWithEmailAndPassword($scope.loginemail, $scope.loginpassword)
.then(function(authData) {
$scope.authData = authData;
console.log(authData);
}).catch(function(error) {
$scope.error = error.message;
});
};


And my service is:

.service('userAuth', ["$firebaseAuth", function($firebaseAuth) {
return $firebaseAuth();
}


I am able to log in successfully but I want to be able to use the logged in credentials globally. By so doing, how I should also prevent certain routes unless user is authenticated.

If a route is only for loggedin users, redirect them to the loggedin page.
If they are already loggedin and they try to visit the signup page, logged them out.
And if they are loggedin and they try to visit the login page, redirect them to profile page.

Answer

I would suggest to store user data in service itself instead of returning it to caller. For example:

.service('userAuth', ["$firebaseAuth", function($firebaseAuth) {
    var userData;
    this.login = function(loginEmail, loginPassword){
       return $firebaseAuth
       .$signInWithEmailAndPassword(loginEmail, loginPassword)
       .then(function(authData) {
           userData = authData;
       });
    }
    this.getUserData = function(){
       return userData;
    }
  }

And use it in controller:

.controller('LoginCtrl', function ($scope, $location, userAuth) {
     $scope.login = function() {
      $scope.authData = null;
      $scope.error = null;

      userAuth.login($scope.loginemail, $scope.loginpassword)
      .then(function() {
        $scope.authData = userAuth.getUserData();
        console.log($scope.authData);
      }).catch(function(error) {
        $scope.error = error.message;
      });
    };

Using this approach you gain couple of benefits:

  1. Encapsulates login logic. This way you can easily change login service without disrupting any other parts of application.

  2. You can get access to user data in any part of your application by injecting auth service and calling getUserData function.

To prevent user from accessing to particular routes you can use $routeChangeStart event to capture route change to stop navigation and then redirect to some other route depending on your business logic.

Comments