數據權限指的是用戶在某個權限域(通常是功能菜單)有哪些基礎資源(用戶,公司,角色等)的控制權限,這是權限管理系統的核心部分,也是最難掌握的。javascript
應用場景:在某個頁面,須要控制用戶對地區的下拉菜單中只能顯示部分城市。下面我來介紹一下說明方法及功能實現代碼:css
點擊地區樹的響應,選中時執行受權,取消選中時撤銷受權。html
/// <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);
認真看看底層這個方法,就能明白數據權限的設計原理了,用戶(或角色)在某個權限域上能夠操做那些用戶,那些公司,那些角色,或系統選項,只要你想控制的數據均可以實現,這在某些系統要求的水平權限控制方面也能夠使用。java
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權限域上對那些地區有權限。node
注意:權限通常指的是用戶或角色才具備的,如菜單訪問,按鈕點擊,添加,修改,刪除等,數據權限指的是用戶或角色基於某個權限域(菜單或按鈕)對某些資源的範圍權限。
ajax