Andre Mendes
Andre Mendes

Reputation: 7687

Redirection on `$stateChangeStart` with angularJS + ui.router

Trying to redirect a user that is not authenticated to a login screen.

Im using ui.router and a directive to check logged users. But its not working as i expected. Its not checking before the page loads and i get stuck on that page with continuous redirections.

Route config:

//User profile
    .state('UserProfile', {
        url: "/u/:id",
        data: {
            restrict: true,
            name: "Your Profile",
            header: true,
            footer: false,
            css: true,
            transparentHeader: true
        },
        templateUrl: "app/partials/user/userProfile.html",
        controller: "userProfileController"
    })

//Login page for not authenticated users
    .state('LoginPage', {
        url: "/login/",
        data: {
            restrict: false,
            name: "Login",
            header: false,
            footer: false,
            css: false,
            transparentHeader: false
        },
        templateUrl: "app/partials/common/loginPage.html",
        controller: "loginController"
    })

service:

.factory('userService', ['$cookies', function($cookies){

   var userData = {
        isLogged: false,
        userId: "",
        firstName: "",
        profilePic: ""
    };


    return userData;

}]);

Directive:

socialMarkt.directive('checkUser', ['$rootScope', '$state', 'userService', function ($r, $state, userService) {
    return {
      link: function (scope, elem, attrs, ctrl) {
        $r.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){
          event.preventDefault();
          if($state.current.data.restrict){
            if(!userService.isLogged){
              $state.go('LoginPage');
            }
          }
        });
      }
    }
  }]);

i just added it to one page for testing. so if the user is not logged in, supposedly it would redirect to the login page using $state.go('LoginPage').

Upvotes: 1

Views: 2328

Answers (2)

Andre Mendes
Andre Mendes

Reputation: 7687

i changed the way i verify for login status.

im doing it on .run

.run(['$rootScope', '$state', 'userService', '$sessionStorage', function($rootScope, $state, userService, $sessionStorage){

  $rootScope.$on('$stateChangeStart'
    , function(event, toState, toParams, fromState, fromParams) {

    //Detecting sessions
    if($sessionStorage.userData){
        var goodORnot = $sessionStorage.userData.isLogged;
    }else{
        goodORnot = false;
    }

    var isAuthenticationRequired =  toState.data 
          && toState.data.requiresLogin 
          //&& !userService.isLogged
          && !goodORnot
      ;

    if(isAuthenticationRequired)
    {
      event.preventDefault();
      $state.go('LoginPage');
    }
  });
}]);

Upvotes: 5

Austin
Austin

Reputation: 1291

One problem I see is that you're calling preventDefault() too early. If the state is not restricted or the user is logged in, then the state change should go through without any issue whereas you're preventing it from happening. event.preventDefault() should go just before $state.go('loginPage');

Upvotes: 0

Related Questions