Search code examples
angularjsauthenticationdeferredresolve

authentication mechanism in angularjs


i am newbie in AngularJS, i have read a tutorial about login and authentication with angular js but i still confused in many points of my code, for now i have arrived to login and to store a token in browser's session, but i can't redirect to home page after loggin in, here is myservice :

function authenticationSvc ($http, $q, $window, auth_uri) {

  var userInfo;

  function login(username, password) {

    var deferred = $q.defer();

    $http.post(auth_uri, {
      username: username,
      password: password
    }).then(function(result) {

      userInfo = {
        accessToken: result.data.token
      };

      $window.sessionStorage["pallas_token"] = result.data.token;

      deferred.resolve(userInfo);
    }, 
    function(error) {
      deferred.reject(error);
    });

    return deferred.promise;
  }

  function getUserInfo() {
    return userInfo;
  }

  return {
    login: login,
    getUserInfo: getUserInfo
  };

};

and this is my state config

.state('dashboard', {
  url:'/dashboard',
  controller: 'HomeController',
  templateUrl: 'partials/dashboard/main.html',
  resolve:{
    auth: function($q, authenticationSvc) {
      var userInfo = authenticationSvc.getUserInfo();                    
      if (userInfo) {                      
        return $q.when(userInfo);

      } else {
        return $q.reject({ authenticated: false });
      }
    }
  }
} 

finally this my .run block:

angular
  .module ( 'mainApp' )
  .run ( function ( $rootScope, $state, $location) {

    $rootScope.$on('$stateChangeSuccess', function( userInfo) {
      console.log( userInfo );            
    });

    $rootScope.$on('$stateChangeError', function(evt, toState, toParams, fromState, fromParams, error) {
      if (error.authenticated == false) {      
        $state.transitionTo("login");
      }
    });
  });

please help me to resolve this issue, i need help my friends :(

i am sorry for missing to post my login controller, there is:

function LoginController($scope, $state, authenticationSvc){ 
  $scope.submit = function(credentials){ 
    authenticationSvc.login(credentials.username, credentials.password); 
  };
};

Solution

  • Your login method return a success promise when the user pass the authentication. So.. you can edit your controller in this way:

    function LoginController($scope, $state, authenticationSvc){ 
      $scope.submit = function(credentials){ 
        authenticationSvc.login(credentials.username, credentials.password).then(function(){
          $state.go('dashboard');
          console.log('User logged in!');
        }).catch(function(){
          console.log('User NOT logged in!');
        }); 
      };
    };
    

    UPDATE

    To maintain the state after a page refresh you need to restore the userInfo object from sessionStorage. I also added the logout logic! Take a look:

    function authenticationSvc ($http, $q, $window, auth_uri) {
    
      var userInfo;
    
      function login(username, password) {
        ...
      }
    
      function logout() {
        $window.sessionStorage.removeItem("pallas_token");
        userInfo = null;
      }
    
      function getUserInfo() {
        return userInfo;
      }
    
      function init(){
        if ($window.sessionStorage["pallas_token"]){
          userInfo = {
            accessToken: $window.sessionStorage["pallas_token"]
          };    
        }
      }
    
      init();
    
      return {
        login: login,
        logout: logout,
        getUserInfo: getUserInfo
      };
    
    };
    

    Logout:

    function LoginController($scope, $state, authenticationSvc){ 
      $scope.submit = function(credentials){ 
        ...
      };
    
      $scope.logout = function(){
        authenticationSvc.logout();
        $state.go('login');
        console.log('User logged out!');
      };
    };
    

    Enjoy!