Benjamin Li Benjamin Li - 1 month ago 16
AngularJS Question

angular how to prevent user typing url directly to access pages when he is logout

I am using

$stateProvider
, so I have lots of states.

considering below scenario:
user is already logout, and he types url in the browser directly, like
www.example.com/home
, I should redirect it to the login page, which is
www.example.com/login


how to implement this? one of the methods is to check if the session is active in run block. is it a good practice to call backend API in the run block?

UPDATE:
According to Ryan's suggestion, it calls backend api to check if user is logged in

$transitions.onBefore({to: 'home'}, function(transition) {
var $state = transition.router.stateService;
let promise = jsonService.heartBeat()
promise.then(data => {
if(!data.hasOwnProperty('data')) {
$state.go('login')
}
}, () => {
$state.go('login')
})
});

Answer

Levi's answer is correct for UI-Router pre-version 1.0. For UI-Router 1.0, the state change events such as $stateChangeStart are deprecated and this will no longer work. You can use the $transitions service instead.

function run ($transitions, Auth) {
  // 'to' param is the state name; 'main.**' will match 'main' and all sub-states
  $transitions.onBefore({to: 'main.**'}, function (transition) {
    var $state = transition.router.stateService;
    if (!Auth.isAuthenticated()) {
      $state.go('login');
    }
  });
}

run.$inject = ['$transitions', 'Auth'];

app.run(run);