2016-02-26 33 views
3

我试图建立角色的权限系统,我要初始化根状态的决心:上$ stateChangeStart每次

$stateProvider 
    .state('common', { 
    resolve:{ 
     user: function(AclService, UserService) { 
     UserService.getCurrent().then((currentUser) => { 
      AclService.initialize(currentUser); 
     }); 
     } 
    } 
    }) 

和检查权限:

$rootScope.$on('$stateChangeStart', ($event, toState) => AclService.interceptStateChange($event, toState)); 

但我遇到了一个问题,首先在解析之前触发了$ stateChangeStart,因此权限尚未初始化。

你会在这种情况下推荐什么?

回答

0

你可以在你的应用的运行功能中做到这一点。以下是我如何加载认证数据的精简版本。

(function() { 

    "use strict"; 

    angular 
     .module("myModule", [ //dependencies here...]); 

    angular 
     .module("myModule") 
     .run(run); 

    run.$inject = ["$rootScope", "$state", "authService"]; 

function run($rootScope, $state, authService) { 

    authService.fillAuthData(); //front load auth stuff here... 

    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { 

     var isPublic = (toState.data && toState.data.isPublic && toState.data.isPublic === true); 
     var requiredRole = (toState.data && toState.data.requiredRole) ? toState.data.requiredRole : null; 
     var authorized = isPublic || authService.isUserInRole(requiredRole); 

     if (authService.authentication.isAuth || isPublic) { 

      //if the user doesn't have the requisite permission to view the page, redirect them to an unauthorized page 
      if (!authorized) { 
       event.preventDefault(); 
       $state.go("unauthorized"); 
       return; 
      } 

     } else { 

      event.preventDefault(); 
      $state.go("login"); 
      return; 
     } 
    }); 
} 

})(); 

一个国家的定义可能是这样的:

.state("someState", { 
    url: "/someState", 
    templateUrl: "my/folder/file.html", 
    data: { 
     pageTitle: "Some Page", 
     isPublic: false, 
     requiredRole: "Admin" 
    } 
}) 
+0

我越来越从服务器使用权限异步,我没有看到它在你的解决方案 –

+0

里面authService.fillAuthData发生() 。 – BBauer42

+0

但你怎么能确定它会在这样的同步检查之前解决 - 如果(authService.authentication? –

0

你不应该做一些权威性的逻辑状态消退。更好的做法是在angular.run功能设置监听器$ stateChangeStart事件:

angular.module('yourModule', []) 
    .run(['$rootScope', 'principal', '$state', function ($rootScope, principal, $state) { 
     var firstOpen = true; 
     $rootScope.$on('$stateChangeStart', function(event, toState, toParams) { 
      if (!principal.isAuthenticated() && firstOpen) { 
       firstOpen = false; 
       event.preventDefault(); 
       principal.checkAuthentication().then(function() { 
        $state.go(toState, toParams); 
       }); 
      } else if (principal.isAuthenticated() && toState.name === 'login') { 
       event.preventDefault(); 
       // Do some stuff here, for example, redirect to main page 
      } 
     }); 
    } 
]);