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?