Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

locationChangeStart and preventing route change

I'm trying to create basic validation whether user can access some route or not. I had progress in that, but there's one thing that I can't figure out.

I'm using $locationChangeStart to monitor route changes. Scenario is: 1. if user is logged in, then allow him to access all routes, except auth routes (login, register). I'm checking this by calling method isAuthenticated() from my AuthFactory 2. If user is not logged in, then he access only login and register routes. Any other route should be prevented, and user should be redirected to login in that case.

$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
  if(AuthFactory.isAuthenticated()){
    if(AuthFactory.isAuthRoute(newUrl)){
      event.preventDefault();
      $location.path('/');
    }
  } else {
    if(!AuthFactory.isAuthRoute(newUrl)){
      event.preventDefault();
      $location.path('/login');
    }

  }
});

Thing that troubles me, is the one with preventDefault(). If app reaches code with preventDefault(), location.path() that comes after that, simply doesn't work.

However, if I remove event.preventDefault(), location.path() works. Problem with this, is that I need that prevent, in case non-logged tries to access some non-auth page.

Basically, I want to be able to prevent or redirect based on requested route. What is the proper way to do that?

like image 661
Ned Avatar asked Dec 25 '13 12:12

Ned


1 Answers

Ok, you need to do this:

var authPreventer = $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
    if(AuthFactory.isAuthenticated()){
        if(AuthFactory.isAuthRoute(newUrl)){
            event.preventDefault();
            authPreventer(); //Stop listening for location changes
            $location.path('/');
        }
    } 
    else {
        if(!AuthFactory.isAuthRoute(newUrl)){
            event.preventDefault();
            authPreventer(); //Stop listening for location changes
            $location.path('/login');
        }
    }
});
like image 119
saike Avatar answered Nov 15 '22 05:11

saike