受角度保护的页面

时间:2016-01-10 19:58:45

标签: javascript angularjs authentication

对于只有被记录用户应该能够查看的页面,我在该页面的控制器中有这样的功能;

if ( user is not logged in ) {

    $state.go('someState')

} else {

    // prepare the page as normal

}

考虑到我需要在每个要验证的页面上写这样的东西,我觉得可能有更优雅的解决方案。

我应该在app.run中执行此操作吗?像

这样的东西
  var protectedPages = a list of protected pages

  if ( protectedPages && user is not logged in ) {

        $state.go('someState')

    } else {

        // prepare the page as normal

    }

或者是否有更标准的方法完全不同?

1 个答案:

答案 0 :(得分:2)

一般而且我认为针对这种情况的最佳方法是设置页面更改事件并在那里定义逻辑......

但是对于定义逻辑,您需要了解下一个状态的某些属性,以便为每个状态添加一些数据,如 requiresLogin 。这些属性是完全自定义的,因此您可以定义所需的任何内容。

让我们定义一些 requiresLogin

的状态
$stateProvider
        .state('exampleState', {
            url: '/example',
            controller: 'ExampleController as vm',
            templateUrl: 'example.html',
            data: {
                requiresLogin: true,
                someOtherCustomProperty: 'It can be anything'
            }
        })

如您所见 exampleState 现在在配置块中有requireLogin属性,我们可以获取此数据并允许用户进入exampleState或将其重定向到其他状态。

$rootScope.$on('$stateChangeStart', function (event, toState) {
        // if next state requires login and user is not loged in
        if (toState.data.requiresLogin && userNotLogedIn) {
            // prevent default behaviour and implement your logic here
            event.preventDefault();

            // TODO

            // as an example you can redirect user to login state
            $state.go('login');
        }
    });

那就是它。您所要做的就是将该逻辑放在配置块中,因为它应该检查每个状态的变化......

相关问题