访问控制的授权代码

时间:2017-06-26 11:56:47

标签: angularjs

如何编写一个angularjs代码来检查值传递是否已存在于数组中,如果存在,则应为用户提供访问权限,否则,不应授予他权限

1 个答案:

答案 0 :(得分:0)

我认为这应该有用

在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
         }
        }
    });
}

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