Angular ui-router:如何防止访问状态

时间:2015-02-14 17:25:32

标签: javascript angularjs angular-ui-router

您好我是angularJS的新手,并且一直试图阻止根据用户标准访问某些状态。

This, from ui-router's FAQ描述了我想要做的事情,但我无法让它正常工作。我需要做什么,但在数据对象中完全要做到这一点?

(我看到有人投入" true"在一些博客文章教程中使用它,就像我的方式一样,但这似乎没有用,因为我得到一个错误,说明needAdmin没有定义)

这是我的代码:

angular.module('courses').config(['$stateProvider',
    function($stateProvider) {
        // Courses state routing
        $stateProvider.
        state('listCourses', {
            url: '/courses',
            templateUrl: 'modules/courses/views/list-courses.client.view.html'
        }).
        state('createCourse', {
            url: '/courses/create',
            templateUrl: 'modules/courses/views/create-course.client.view.html',
            data: {
                needAdmin: true
            }
        }).
        state('viewCourse', {
            url: '/courses/:courseId',
            templateUrl: 'modules/courses/views/view-course.client.view.html'
        }).
        state('editCourse', {
            url: '/courses/:courseId/edit',
            templateUrl: 'modules/courses/views/edit-course.client.view.html',
            data: {
                needAdmin: true
            }
        });     

    }
]);


angular.module('courses').run(['$rootScope', '$state', 'Authentication', function($rootScope, $state, Authentication) {
  $rootScope.$on('$stateChangeStart', function(e, to) {

    var auth = Authentication;

    console.log(auth.user.roles[0]);
    if (to.data.needAdmin && auth.user.roles[0] !== 'admin') {
      e.preventDefault();
      $state.go('/courses');
    }

  });
}]);

2 个答案:

答案 0 :(得分:90)

我发现这样做的最佳方法是使用resolve:

    $stateProvider.        
    state('createCourse', {
        url: '/courses/create',
        templateUrl: 'modules/courses/views/create-course.client.view.html',
        resolve: {
           security: ['$q', function($q){
               if(/*user is not admin*/){
                  return $q.reject("Not Authorized");
               }
           }]
        }
    });

这将触发错误,阻止用户在不允许的情况下访问此状态。

如果您需要显示错误或将用户发送到其他状态,请处理$ stateChangeError事件:

$rootScope.$on('$stateChangeError', function(e, toState, toParams, fromState, fromParams, error){

    if(error === "Not Authorized"){
        $state.go("notAuthorizedPage");
    }

如果要检查所有状态的管理员访问权限,可以使用装饰器将解析添加到所有状态。像这样:

$stateProvider.decorator('data', function(state, parent){
    var stateData = parent(state);
    var data = stateData.data || {};

    state.resolve = state.resolve || {};
    if(data.needAdmin){
       state.resolve.security = ['$q', function($q){
               if(/*user is not admin*/){
                  return $q.reject("Not Authorized");
               }
           }];
    return stateData;
});

我为我当前的应用程序实现了类似的功能。如果用户未登录,我们会将用户转发到登录表单。如果非管理员用户尝试访问任何管理员状态,我们会转到错误页面。

答案 1 :(得分:10)

如果某个州没有data,则to.data未定义。试试这个:

if (to.data && to.data.needAdmin && auth.user.roles[0] !== 'admin') {