通用权限管理系统中数据权限功能开发及使用说明
数据权限指的是用户在某个权限域(一般是功能菜单)有哪些基础资源(用户,公司,角色等)的控制权限,这是权限管理系统的核心部分,也是最难掌握的。
应用场景:在某个页面,需要控制用户对地区的下拉菜单中只能显示部分城市。下面我来介绍一下说明方法及功能实现代码:
设置用户某个权限域(公司管理)上的地区访问权限
点击地区树的响应,选中时执行授权,取消选中时撤销授权。
授权和撤销权限的后台代码
/// <summary> /// 授予用户某个权限域的地区权限 /// 范围权限可以按照这个,不需要创建那么多scope /// </summary> /// <param name="userId"></param> /// <param name="areaIds"></param> /// <param name="permissionId"></param> /// <param name="systemCode"></param> /// <returns></returns> public ActionResult GrantUserAreaScopes(string userId, string areaIds, string permissionId, string systemCode = null) { BaseResult baseResult = new BaseResult(); try { if (string.IsNullOrWhiteSpace(systemCode)) { systemCode = BaseSystemInfo.SystemCode; } string tableName = systemCode + "PermissionScope"; var permissionScopeManager = new BasePermissionScopeManager(UserCenterDbHelper, OperateContext.Current.UserInfo, tableName); string resourceCategory = BaseUserEntity.TableName; string targetCategory = BaseAreaEntity.TableName; string[] grantTargetIds = areaIds.Split(','); baseResult.RecordCount = permissionScopeManager.GrantResourcePermissionScopeTarget(resourceCategory, userId, targetCategory, grantTargetIds, permissionId); baseResult.StatusMessage = "已成功授予用户的地区数据权限。"; baseResult.Status = true; } catch (Exception ex) { baseResult.Status = false; baseResult.StatusMessage = "用户对地区数据权限设置异常:" + ex.Message; } return Json(baseResult, JsonRequestBehavior.AllowGet); } /// <summary> /// 撤销用户某个权限域的地区权限 /// 范围权限可以按照这个,不需要创建那么多scope /// </summary> /// <param name="userId"></param> /// <param name="areaIds"></param> /// <param name="permissionId"></param> /// <param name="systemCode"></param> /// <returns></returns> public ActionResult RevokeUserAreaScopes(string userId, string areaIds, string permissionId, string systemCode = null) { BaseResult baseResult = new BaseResult(); try { if (string.IsNullOrWhiteSpace(systemCode)) { systemCode = BaseSystemInfo.SystemCode; } string tableName = systemCode + "PermissionScope"; var permissionScopeManager = new BasePermissionScopeManager(UserCenterDbHelper, OperateContext.Current.UserInfo, tableName); string resourceCategory = BaseUserEntity.TableName; string targetCategory = BaseAreaEntity.TableName; string[] grantTargetIds = areaIds.Split(','); baseResult.RecordCount = permissionScopeManager.RevokeResourcePermissionScopeTarget(resourceCategory, userId, targetCategory, grantTargetIds, permissionId); baseResult.StatusMessage = "已成功撤销用户的地区数据权限。"; baseResult.Status = true; } catch (Exception ex) { baseResult.Status = false; baseResult.StatusMessage = "用户对地区数据权限撤销出现异常:" + ex.Message; } return Json(baseResult, JsonRequestBehavior.AllowGet); }
后台获取用户对地区的数据权限的方法
/// <summary> /// 地区异步树 /// </summary> /// <param name="id"></param> /// <param name="userId"></param> /// <param name="permissionId"></param> /// <param name="systemCode"></param> /// <returns></returns> public ActionResult AsyncTree(int? id, string userId, string permissionId, string systemCode = null) { List<TreeNode> treeNodes = new List<TreeNode>(); List<BaseAreaEntity> list; //if (id.HasValue) //{ // list = new BaseAreaManager().GetList<BaseAreaEntity>(new KeyValuePair<string, object>(BaseAreaEntity.FieldParentId, id)); //} //else //{ // list = new BaseAreaManager().GetList<BaseAreaEntity>(BaseAreaEntity.FieldParentId + " IS NULl "); //} //if (list != null && list.Any()) //{ // treeNodes = list.Select(t => new TreeNode() // { // id = t.Id, // parentId = t.ParentId, // name = t.FullName, // drag = false, // drop = false // }).ToList(); //} if (string.IsNullOrWhiteSpace(systemCode)) { systemCode = BaseSystemInfo.SystemCode; } string tableName = systemCode + "PermissionScope"; BasePermissionScopeManager permissionScopeManager = new BasePermissionScopeManager(UserCenterDbHelper, OperateContext.Current.UserInfo, tableName); List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>(); // 某个用户 parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldResourceCategory, BaseUserEntity.TableName)); parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldResourceId, userId)); // 对某类目标资源 地区资源 要获取地区的Id parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldTargetCategory, BaseAreaEntity.TableName)); //parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldTargetId, areaId)); // 资源菜单 权限域 parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldPermissionId, permissionId)); parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldEnabled, 1)); parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldDeletionStateCode, 0)); // 用户基于权限域permissionId 对那些地区有权限 List<BasePermissionScopeEntity> permissionScopeliEntities = permissionScopeManager.GetList<BasePermissionScopeEntity>(parameters); string[] areaIds = new string[] { }; if (permissionScopeliEntities != null && permissionScopeliEntities.Any()) { areaIds = permissionScopeliEntities.Select(t => t.TargetId).ToArray(); } using (var dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection)) { // 查询语句 string sql = string.Format(@" SELECT A.{0},A.{1},A.{2},A.{3},(SELECT COUNT(1) FROM " + BaseAreaEntity.TableName + " WHERE " + BaseAreaEntity.TableName + "." + BaseAreaEntity.FieldParentId + "=A." + BaseAreaEntity.FieldId + ") CHILDCOUNT FROM " + BaseAreaEntity.TableName + " A WHERE " + BaseAreaEntity.FieldDeletionStateCode + " =0 ", BaseAreaEntity.FieldId, BaseAreaEntity.FieldParentId, BaseAreaEntity.FieldCode, BaseAreaEntity.FieldFullName); IDbDataParameter[] dbParameters = null; if (!id.HasValue) { sql += " AND " + BaseAreaEntity.FieldParentId + " IS NULL "; } else { sql += " AND " + BaseAreaEntity.FieldParentId + " = " + dbHelper.GetParameter(BaseAreaEntity.FieldId); dbParameters = new IDbDataParameter[] { dbHelper.MakeParameter(BaseAreaEntity.FieldId, id), }; } sql += " ORDER BY " + BaseAreaEntity.FieldCode + " ASC "; var dt = dbHelper.Fill(sql, dbParameters); if (dt != null && dt.Rows.Count > 0) { treeNodes = dt.AsEnumerable().Select(q => new TreeNode() { id = q[BaseAreaEntity.FieldId].ToString(), name = q[BaseAreaEntity.FieldFullName].ToString(), parentId = q[BaseAreaEntity.FieldParentId].ToString(), isParent = Convert.ToInt32(q["CHILDCOUNT"]) > 0, nodeChecked = Array.IndexOf(areaIds, q[BaseAreaEntity.FieldId].ToString()) >= 0, }).ToList(); } } Hashtable result = new Hashtable(); result.Add("treeNodes", treeNodes); return Json(result, JsonRequestBehavior.AllowGet); }
前端功能操作代码
@using DotNet.Model @using DotNet.MVC.Infrastructure @{ ViewBag.Title = "用户数据权限设置"; // 控制用户对那些数据有权限 Layout = "~/Views/QUILayout/MainContent.cshtml"; BaseUserEntity userEntity = ViewBag.userEntity; BaseModuleEntity moduleEntity = ViewBag.moduleEntity; var systemCode = ViewBag.systemCode; } @section Head { <!--数据表格start--> <script src="@BusinessSystemInfo.QuiPath/libs/js/table/quiGrid.js" type="text/javascript"></script> <!--数据表格end--> <!--布局控件start--> <script type="text/javascript" src="@BusinessSystemInfo.QuiPath/libs/js/nav/layout.js"></script> <!--布局控件end--> <!--基本选项卡start--> <script type="text/javascript" src="@BusinessSystemInfo.QuiPath/libs/js/nav/basicTab.js"></script> <!--基本选项卡end--> <!-- 树组件start --> <script type="text/javascript" src="@BusinessSystemInfo.QuiPath/libs/js/tree/ztree/ztree.js"></script> <link href="@BusinessSystemInfo.QuiPath/libs/js/tree/ztree/ztree.css" rel="stylesheet" type="text/css" /> <!-- 树组件end --> } <div id="layout1"> <div position="top" id="topCon" style=""> <div class="box_tool_min padding_top0 padding_bottom6 padding_right5"> <div class="center"> <div class="left"> <div class="right"> <div class="padding_top3 padding_left10 padding_right10"> <div style="float: left"> 设置用户【 @userEntity.RealName】在权限域【@moduleEntity.FullName】上的范围权限 </div> <div style="float: right"> @*<div style="float: left"> <a href="javascript:;" onclick="addUnit()"><span class="icon_add">区域权明细...</span></a> </div>*@ <div style="float: right"> <a href="javascript:;" onclick="addUnit()"><span class="icon_add">添加...</span></a> <a href="javascript:;" onclick="removeUnit()"><span class="icon_delete">移除</span></a> <a href="javascript:;" onclick="top.Dialog.close();"><span class="icon_exit">关闭</span></a> </div> </div> <div class="clear"></div> </div> </div> </div> </div> <div class="clear"></div> </div> </div> <div position="left" style="" paneltitle="数据权限范围"> <div class="layout_content"> <input type="radio" id="rdbAllData" name="dataScope" value="AllData" /><label for="rdbAllData" class="hand">所有数据</label><br /> <input type="radio" id="rdbProvince" name="dataScope" value="Province" /><label for="rdbProvince" class="hand">所在省</label><br /> <input type="radio" id="rdbCity" name="dataScope" value="City" /><label for="rdbCity" class="hand">所在市</label><br /> <input type="radio" id="rdbDistrict" name="dataScope" value="District" /><label for="rdbDistrict" class="hand">所在县区</label><br /> <input type="radio" id="rdbStreet" name="dataScope" value="Street" /><label for="rdbStreet" class="hand">所在街道</label><br /> <input type="radio" id="rdbUserCompany" name="dataScope" value="UserCompany" /><label for="rdbUserCompany" class="hand">所在公司</label><br /> <input type="radio" id="rdbUserSubCompany" name="dataScope" value="UserSubCompany" /><label for="rdbUserSubCompany" class="hand">所在分支机构</label><br /> @*<input type="radio" id="rdbUserDepartment" name="dataScope" value="UserDepartment" /><label for="rdbUserDepartment" class="hand">所在部门</label><br /> <input type="radio" id="rdbUserSubDepartment" name="dataScope" value="UserSubDepartment" /><label for="rdbUserSubDepartment" class="hand">所在子部门</label><br /> <input type="radio" id="rdbUserWorkgroup" name="dataScope" value="UserWorkgroup" /><label for="rdbUserWorkgroup" class="hand">所在工作组</label><br />*@ <input type="radio" id="rdbOnlyOwnData" name="dataScope" value="OnlyOwnData" /><label for="rdbOnlyOwnData" class="hand">仅本人</label><br /> <input type="radio" id="rdbByDetails" name="dataScope" value="ByDetails" /><label for="rdbByDetails" class="hand">按明细设置</label><br /> <input type="radio" id="rdbNotAllowed" name="dataScope" value="NotAllowed" /><label for="rdbNotAllowed" class="hand">无</label><br /> </div> </div> <div position="center" style="" id="centerCon"> <div class="basicTab" id="tabView" selectedidx="0"> <div name="区域" itemdisabled="false"> <ul id="areaTree" style="overflow: auto" class="ztree"></ul> </div> <div name="网点" itemdisabled="false"> <div id="dataBasicByOrganize"> </div> </div> <div name="用户" itemdisabled="false"> <div id="dataBasicByUser"> </div> </div> <div name="角色" itemdisabled="false"> <div id="dataBasicByRole"> </div> </div> </div> </div> @*<div position="bottom" id="bottomCon" style=""></div>*@ </div> @section Footer { <script type="text/javascript"> var userId = "@userEntity.Id"; var systemCode = "@ViewBag.SystemCode"; var permissionId = "@moduleEntity.Id"; var gridArea, gridOrganize, gridUser, gridRole; var id = "#dataBasicByArea"; var currentTabId = 0; // tab切换事件处理 function InitPage(iTab) { if (iTab === 0) { $.fn.zTree.init($("#areaTree"), settingTree); } else if (iTab === 1) { id = "#dataBasicByOrganize"; gridOrganize = $(id).quiGrid({ columns: [ { display: '编号', name: 'Code', align: 'center', width: 100 }, { display: '名称', name: 'FullName', align: 'center', width: 100 }, { display: '所属公司', name: 'ParentName', align: 'center', width: 100 }, { display: '省份', name: 'Province', align: 'center', wdith: 120 }, { display: '城市', name: 'City', align: 'center', wdith: 120 }, { display: '区县', name: 'District', align: 'center', wdith: 120 } ], url: '/Permission/GetUserScopeOrganizeList?systemCode=' + systemCode + "&userId=" + userId + "&permissionId=" + permissionId, sortName: 'Id', rownumbers: true, checkbox: true, height: '100%', width: '100%', pageSizeOptions: [30, 50, 100], pageSize: 50, showPageInfo: true, onLoading: gridonLoading, onLoaded: gridonLoaded, onBeforeShowData: gridOnBeforeShowData, // onSuccess: gridOnSuccess, onError: gridOnError }); } else if (iTab === 2) { id = "#dataBasicByUser"; gridUser = $(id).quiGrid({ columns: [ { display: '编号', name: 'Code', align: 'center', width: 100 }, { display: '登录账号', name: 'NickName', align: 'center', width: 100 }, { display: '姓名', name: 'RealName', align: 'center', width: 100 }, { display: '公司', name: 'CompanyName', align: 'center', width: 100 }, { display: '部门', name: 'DepartmentName', align: 'center', width: 100 } ], url: '/Permission/GetUserScopeUserList?systemCode=' + systemCode + "&userId=" + userId + "&permissionId=" + permissionId, sortName: 'Id', //params: $("#queryForm").formToArray(), rownumbers: true, height: '100%', width: '100%', pageSizeOptions: [30, 50, 100], pageSize: 50, checkbox: true, showPageInfo: true, onLoading: gridonLoading, onLoaded: gridonLoaded, onBeforeShowData: gridOnBeforeShowData, onSuccess: gridOnSuccess, onError: gridOnError }); } else if (iTab === 3) { id = "#dataBasicByRole"; gridRole = $(id).quiGrid({ columns: [ { display: '编号', name: 'Code', align: 'center', width: 100 }, { display: '名称', name: 'RealName', align: 'center', width: 100 }, { display: '备注', name: 'Description', align: 'center', width: 300 } ], url: '/Permission/GetUserScopeRoleList?systemCode=' + systemCode + "&userId=" + userId + "&permissionId=" + permissionId, sortName: 'Id', rownumbers: true, height: '100%', width: '100%', pageSizeOptions: [30, 50, 100], pageSize: 50, showPageInfo: true, checkbox: true, onLoading: gridonLoading, onLoaded: gridonLoaded, onBeforeShowData: gridOnBeforeShowData, // onSuccess: gridOnSuccess, onError: gridOnError }); } currentTabId = iTab; objGrid = id; } //因为返回的数据格式正确,因此,直接返回。正常使用时是不需要此方法的。 function filter(treeId, parentNode, childNodes) { for (var i = 0; i < childNodes.length; i++) { childNodes[i].checked = childNodes[i].nodeChecked; } return childNodes; } // 地区异步树设置 var settingTree = { check: { enable: true }, async: { enable: true, dataType: 'JSON', //返回的JSON数据的名字 dataName: 'treeNodes', url: "/Area/AsyncTree?userId=" + userId + "&permissionId=" + permissionId, autoParam: ["id"], dataFilter: filter }, callback: { //beforeCheck: beforeCheck, onCheck: onCheck } }; settingTree.check.chkboxType = { "Y": "", "N": "" }; // 设置用户的某个权限域的地区权限 用户可以操作那些地区 function onCheck(event, treeId, treeNode) { //top.Dialog.alert("onCheck,id:" + treeNode.id + ",name:" + treeNode.name + ",checked:" + treeNode.checked); $("#container").mask("系统处理中..."); var url = '/Permission/GrantUserAreaScopes'; if (!treeNode.checked) { // 撤销地区权限 url = '/Permission/revokeUserAreaScopes'; } $.ajax({ type: 'POST', url: url, data: { "userId": userId, "areaIds": treeNode.id, "permissionId": permissionId, "systemCode": systemCode }, dataType: 'json', success: function (result) { if (result.Status) { top.Dialog.alert("操作成功:" + result.StatusMessage, function () { //refreshGrid(currentTabId); //top.Dialog.close(); }); } else { top.Dialog.alert("添加失败:" + result.StatusMessage); } $("#container").unmask(); }, error: function (a) { top.Dialog.alert("访问服务器端出错!"); $("#container").unmask(); } }); } function initComplete() { $.fn.zTree.init($("#areaTree"), settingTree); var layout = $("#layout1").layout({ leftWidth: 150, topHeight: 0, bottomHeight: 0, onEndResize: function () { // triggerCustomHeightSet(); } }); var permissionOrganizeScope = "@ViewBag.permissionOrganizeScope"; $("input[type=radio][name='dataScope'][value='" + permissionOrganizeScope + "']:eq(0)").attr("checked", 'checked'); // 数据权限范围选中事件 $("input:radio[name='dataScope']").change(function () { var permissionOrganizeScope = $("input:radio[name='dataScope']:checked").val(); $.ajax({ type: 'POST', url: "/UserPermissionScope/SetUserOrganizeScope", data: { "targetUserId": "@userEntity.Id", "permissionOrganizeScope": permissionOrganizeScope, "permissionCode": "@moduleEntity.Code", "systemCode": "@systemCode" }, dataType: 'json', success: function (result) { if (result.Status) { top.Dialog.alert("设置成功!"); } else { top.Dialog.alert(result.StatusMessage); } }, error: function (a) { top.Dialog.alert("出错了!"); } }); }); // 绑定Tab点击事件 $("#tabView").bind("actived", function (e, i) { if (i === 0) { id = "#dataBasicByArea"; InitPage(0); //if (gridArea == null) { // InitPage(0); //} //gridArea.resetHeight(); } else if (i === 1) { id = "#dataBasicByOrganize"; if (gridOrganize == null) { InitPage(1); } gridOrganize.resetHeight(); } else if (i === 2) { id = "#dataBasicByUser"; if (gridUser == null) { InitPage(2); } gridUser.resetHeight(); } else if (i === 3) { id = "#dataBasicByRole"; if (gridRole == null) { InitPage(3); } gridRole.resetHeight(); } currentTabId = i; // 设置grid下方统计信息时使用 objGrid = id; //$(id + " .l-bar-text:first").show(); //$(id).unmask(); //$("#queryForm").unmask(); }); InitPage(0); } // 添加 function addUnit() { if (currentTabId === 0) { top.Dialog.open({ URL: "/Area/ChooseArea?systemCode=" + systemCode + "&from=userpermissionscope", Title: "请选择", Width: 800, Height: 600 }); } else if (currentTabId === 1) { top.Dialog.open({ URL: "/Organize/ChooseOrganize?systemCode=" + systemCode + "&from=userpermissionscope", Title: "请选择", Width: 800, Height: 600 }); } else if (currentTabId === 2) { top.Dialog.open({ URL: "/User/ChooseUser?systemCode=" + systemCode + "&from=userpermissionscope", Title: "请选择", Width: 800, Height: 600 }); } else if (currentTabId === 3) { top.Dialog.open({ URL: "/Role/ChooseRole?systemCode=" + systemCode + "&from=userpermissionscope", Title: "请选择", Width: 800, Height: 600 }); } }; // 设置用户的某个权限域的组织范围 用户可以操作那些网点 function grantUserOrganizeScopes(ids) { $("#container").mask("系统处理中..."); $.ajax({ type: 'POST', url: '/Permission/GrantUserOrganizeScopes', data: { "userId": userId, "organizeIds": ids, "permissionId": permissionId, "systemCode": systemCode }, dataType: 'json', success: function (result) { if (result.Status) { top.Dialog.alert("操作成功:" + result.StatusMessage, function () { refreshGrid(currentTabId); top.Dialog.close(); }); } else { top.Dialog.alert("添加失败:" + result.StatusMessage); } $("#container").unmask(); }, error: function (a) { top.Dialog.alert("访问服务器端出错!"); $("#container").unmask(); } }); }; // 设置用户的某个权限域的用户范围 function grantUserUserScopes(ids) { $("#container").mask("系统处理中..."); $.ajax({ type: 'POST', url: '/Permission/GrantUserUserScopes', data: { "userId": userId, "userIds": ids, "permissionId": permissionId, "systemCode": systemCode }, dataType: 'json', success: function (result) { if (result.Status) { top.Dialog.alert("操作成功:" + result.StatusMessage, function () { refreshGrid(currentTabId); top.Dialog.close(); }); } else { top.Dialog.alert("添加失败:" + result.StatusMessage); } $("#container").unmask(); }, error: function (a) { top.Dialog.alert("访问服务器端出错!"); $("#container").unmask(); } }); }; // 设置用户的某个权限域的角色范围 function grantUserRoleScopes(ids) { $("#container").mask("系统处理中..."); $.ajax({ type: 'POST', url: '/Permission/GrantUserRoleScopes', data: { "userId": userId, "roleIds": ids, "permissionId": permissionId, "systemCode": systemCode }, dataType: 'json', success: function (result) { if (result.Status) { top.Dialog.alert("操作成功:" + result.StatusMessage, function () { refreshGrid(currentTabId); top.Dialog.close(); }); } else { top.Dialog.alert("添加失败:" + result.StatusMessage); } $("#container").unmask(); }, error: function (a) { top.Dialog.alert("访问服务器端出错!"); $("#container").unmask(); } }); }; // 移除 function removeUnit() { if (currentTabId === 0) { // revokeUserAreaScopes(gridUser); } else if (currentTabId === 1) { revokeUserOrganizeScopes(gridOrganize); } else if (currentTabId === 2) { revokeUserUserScopes(gridUser); } else if (currentTabId === 3) { revokeUserRoleScopes(gridRole); } }; // 移除用户某个权限于的组织机构范围权限 function revokeUserOrganizeScopes(grid) { var rows = grid.getSelectedRows(); var rowsLength = rows.length; if (rowsLength === 0) { top.Dialog.alert("请选中一条记录。"); } else { top.Dialog.confirm("确定要移除这些公司吗?", function () { $("#container").mask("系统处理中..."); $.ajax({ type: 'POST', url: '/Permission/RevokeUserOrganizeScopes', data: { "userId": userId, "organizeIds": getSelectIds(grid), "permissionId": permissionId, "systemCode": systemCode }, dataType: 'json', success: function (result) { if (result.Status) { top.Dialog.alert("操作成功:" + result.StatusMessage, function () { //top.document.getElementById("_DialogFrame_selectWin").contentWindow.refreshGrid(currentTabId); }); } else { top.Dialog.alert("操作失败:" + result.StatusMessage); } refreshGrid(currentTabId); $("#container").unmask(); }, error: function (a) { top.Dialog.alert("访问服务器端出错!"); $("#container").unmask(); } }); }); } }; // 移除用户某个权限于的用户范围权限 function revokeUserUserScopes(grid) { var rows = grid.getSelectedRows(); var rowsLength = rows.length; if (rowsLength === 0) { top.Dialog.alert("请选中一条记录。"); } else { top.Dialog.confirm("确定要移除这些用户吗?", function () { $("#container").mask("系统处理中..."); $.ajax({ type: 'POST', url: '/Permission/RevokeUserUserScopes', data: { "userId": userId, "userIds": getSelectIds(grid), "permissionId": permissionId, "systemCode": systemCode }, dataType: 'json', success: function (result) { if (result.Status) { top.Dialog.alert("操作成功:" + result.StatusMessage, function () { //top.document.getElementById("_DialogFrame_selectWin").contentWindow.refreshGrid(currentTabId); }); } else { top.Dialog.alert("操作失败:" + result.StatusMessage); } refreshGrid(currentTabId); $("#container").unmask(); }, error: function (a) { top.Dialog.alert("访问服务器端出错!"); $("#container").unmask(); } }); }); } }; // 移除用户某个权限于的角色范围权限 function revokeUserRoleScopes(grid) { var rows = grid.getSelectedRows(); var rowsLength = rows.length; if (rowsLength === 0) { top.Dialog.alert("请选中一条记录。"); } else { top.Dialog.confirm("确定要移除这些角色吗?", function () { $("#container").mask("系统处理中..."); $.ajax({ type: 'POST', url: '/Permission/RevokeUserRoleScopes', data: { "userId": userId, "roleIds": getSelectIds(grid), "permissionId": permissionId, "systemCode": systemCode }, dataType: 'json', success: function (result) { if (result.Status) { top.Dialog.alert("操作成功:" + result.StatusMessage, function () { //top.document.getElementById("_DialogFrame_selectWin").contentWindow.refreshGrid(1); }); } else { top.Dialog.alert("操作失败:" + result.StatusMessage); } refreshGrid(currentTabId); $("#container").unmask(); }, error: function (a) { top.Dialog.alert("访问服务器端出错!"); $("#container").unmask(); } }); }); } }; // 获取所有选中行获取选中行的id function getSelectIds(objGrid) { var selectedRows = objGrid.getSelectedRows(); var selectedRowsLength = selectedRows.length; var ids = ""; for (var i = 0; i < selectedRowsLength; i++) { if (selectedRows[i].Id == null) continue; ids += selectedRows[i].Id + ","; } ids = ids.substring(0, ids.length - 1); return ids; }; // 刷新用户选择 function refreshGrid(iTab) { InitPage(iTab); } function customHeightSet(contentHeight) { $("#areaTree").height(contentHeight - 76); } </script> }
数据权限表的设计
有数据看的更直观些
授予数据权限和撤销数据权限的操作
string tableName = systemCode + "PermissionScope"; var permissionScopeManager = new BasePermissionScopeManager(UserCenterDbHelper, OperateContext.Current.UserInfo, tableName); string resourceCategory = BaseUserEntity.TableName; string targetCategory = BaseAreaEntity.TableName; string[] grantTargetIds = areaIds.Split(','); // 授权 permissionScopeManager.GrantResourcePermissionScopeTarget(resourceCategory, userId, targetCategory, grantTargetIds, permissionId); // 撤销权限 permissionScopeManager.RevokeResourcePermissionScopeTarget(resourceCategory, userId, targetCategory, grantTargetIds, permissionId);
认真看看底层这个方法,就能明白数据权限的设计原理了,用户(或角色)在某个权限域上可以操作那些用户,那些公司,那些角色,或系统选项,只要你想控制的数据都可以实现,这在某些系统要求的水平权限控制方面也可以使用。
获取数据权限的方法
string tableName = systemCode + "PermissionScope"; BasePermissionScopeManager permissionScopeManager = new BasePermissionScopeManager(UserCenterDbHelper, OperateContext.Current.UserInfo, tableName); List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>(); // 某个用户 parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldResourceCategory, BaseUserEntity.TableName)); parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldResourceId, userId)); // 对某类目标资源 地区资源 要获取地区的Id parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldTargetCategory, BaseAreaEntity.TableName)); //parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldTargetId, areaId)); // 资源菜单 权限域 parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldPermissionId, permissionId)); parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldEnabled, 1)); parameters.Add(new KeyValuePair<string, object>(BasePermissionScopeEntity.FieldDeletionStateCode, 0)); // 用户基于权限域permissionId 对那些地区有权限 List<BasePermissionScopeEntity> permissionScopeliEntities = permissionScopeManager.GetList<BasePermissionScopeEntity>(parameters); string[] areaIds = new string[] { }; if (permissionScopeliEntities != null && permissionScopeliEntities.Any()) { areaIds = permissionScopeliEntities.Select(t => t.TargetId).ToArray(); }
上面是获取某个用户在permissionId权限域上对那些地区有权限。
注意:权限一般指的是用户或角色才具有的,如菜单访问,按钮点击,添加,修改,删除等,数据权限指的是用户或角色基于某个权限域(菜单或按钮)对某些资源的范围权限。