授权代码用于访问控制



如何编写AngularJS代码以检查数组中是否已经存在值,并且如果存在,则应授予用户访问权利,如果不是,则不应获得权利

我认为这应该有效

在您的HTML中,您需要使用一个按钮来绑定ng-click,该按钮将检查特权并相应地执行。假设按钮就像这样

<button type="button" ng-click="checkPrivilege();">Check Privilege</button>

在您的控制器内部,您需要进行一些操作

//say, this is our privilege JSON
$scope.privilege = [
                    {
                     accessName: "ACCOUNT_ADD", 
                     roles:['ADMIN','MANAGER']
                    },
                    {
                     accessName: "ACCOUNT_DELETE", 
                     roles:['ADMIN']
                    }
                ];
$scope.checkPrivilege = function(){
    //first you need to find out the role of the logged in user, lets say 
    //you get the role value from getLoggedInUserRole() function
    $scope.userRole = getLoggedInUserRole();
    //lets say the selected access name is 'ACCOUNT_ADD'
    $scope.allowedAccessName = "ACCOUNT_ADD";
    angular.forEach($scope.privilege, function(value, key) {
        var privilegedRoles = privilege[key].roles;
        var privilegedAccessName = privilege[key].accessName;
        //check if the json object contains the same accessName which we need
        if($scope.allowedAccessName === privilegedAccessName){
         //check if the role is allowed or not for this user
         if( privilegedRoles.indexOf(userRole) > -1 ){
            //the logged in user has this privilege to accessName
            break;
         }else{
            // the logged in user has no access to this accessName
         }
        }
    });
}

您可以查看评论并理解。此代码可能并不完全相同,您肯定会了解如何实现目标。

最新更新