2015-05-15 32 views
0

我有一個AngularJS單頁應用程序,其中有很多HTML塊,我根據它們的權限級別向用戶展示。根據權限級別顯示/隱藏部件的最佳方式 - Angular JS

用戶權限由service調用確定,並根據權限設置值。

$scope.permission = 'admin'

我可以用ng-hide/show指令隱藏基於權限的那些塊。但我擔心安全。通過更改css display屬性,那些未被授權的人也可以查看這些塊。

另一個選項是ng-if,目前我正在使用它。但我想知道我是否應該這樣做,routing,我相信這更安全。我可以使用ui.router角模塊來實現這一點。但是,正確的方法是什麼?

我應該用ng-hide/show,ng-if還是routing

期待一些好的想法。

任何幫助,非常感謝。提前致謝。

+1

http://stackoverflow.com/questions/21869283/when-to-favor-ng-if-vs-ng-show-ng-hide –

回答

3

基本上ng-if將元素添加/刪除到DOM,其中ad-show/ng-hide只是用css隱藏元素。

路由也是一個可行的選擇,但這種方式你將有不同用戶的多個部分。如果你只想隱藏部分用戶一些東西,我會去與NG-如果

+0

感謝您的答案。目前我正在使用ng-if。 – Wishnu

6

你應該創造這樣的目的的指令:

app.directive('checkPermissions', ['PermissionsServices', function(PermissionsServices) { 
    return { 
     restrict: 'A', 
     link: function(scope, elem, attrs, ctrl) { 

      if (attrs.permissions != '') { 
       var hasPermission = PermissionsServices.hasAccess(attrs.checkPermissions); 

       if (false == hasPermission) { 
        elem.remove(); 
       } 
      } else { 
       elem.remove(); 
      } 
     } 
    }; 
}]); 

HTML科

<a href="http://some_url" check-permissions="state1.name1" >Some URL</a> 
<a ui-sref="state2.name2" check-permissions="state2.name2">State 2</a> 
<button ng-click="state3.name" check-permissions="state3.name3">State 3</button> 

PermissionsServices.hasAcces PermissionsServices服務中的s()函數將檢查用戶是否有權訪問您的應用程序的特定狀態。您可能正在使用Angular Router或UI路由器來處理狀態。我正在使用UI路由器,所以我的代碼在函數中。這個函數只會返回true或false。

PermissionsServices.hasAccess = function(stateName) { 
     var hasAccess     = false; 


     //Some complex checking algorithm based on your requirement 
     hasAccess = true 

     return hasAccess; 
}; 

希望幫助!

+0

很好的例子和超級完整。正是我需要的。我將在ES6中實現它。謝謝! –

4

要處理來自路由角度的授權,我們可以爲角度路由基礎結構構建一些自定義擴展。路線可以定義爲

$routeProvider.when('/admin', { 
    templateUrl: 'admin.html', 
    controller: 'AdminController', 
    roles: ['admin'] //custom extension 
}); 
$routeProvider.when('/home', { 
    templateUrl: 'home.html', 
    controller: 'HomeController', 
    roles: ['admin', 'user'] //custom extension 
}) 

這裏角色數組定義誰可以訪問路線。

爲了執行它,我們可以使用routeChangeStart事件來驗證權限。這是我的一本書的摘錄其中強調如何執行角色

angular.module('app').run(function ($rootScope, $location, 
SessionContext) { 
    $rootScope.$on('$routeChangeStart', function (event, next) { 
     if (next.roles && !SessionContext.authenticated) { 
      $location.path('/login'); //needs to login 
     } 
     if (next.roles && SessionContext.authenticated && !SessionContext.isInRole(next.roles)) { 
      $location.path('/unauthorized'); //un-authorized 
     } 
    }); 
}); 

SessionContext服務跟蹤的loggedIn用戶角色。

相關問題