码迷,mamicode.com
首页 > Web开发 > 详细

Web应用程序系统的多用户权限控制设计及实现-权限模块【10】

时间:2015-10-18 19:49:43      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

前五章均是从整体上讲述了Web应用程序的多用户权限控制实现流程,本章讲述Web权限管理系统的权限配置模块。页面模块涉及到的数据表为权限表。权限配置模块是按照用户组和页面,栏目结合组成的。通过配置一个用户组可以访问的页面即完成了该类型用户的访问权限管理。

1.1权限域

为了更规范和方便后期系统的二次开发和维护,对应特定的业务模块采用Area(域)的方式开发,权限模块的开发域如下图所示:

技术分享

由于在Areas下还建立了一个新的目录SystemManage,故需要改变原来的路由。权限模块的路由文件名称为RightManageAreaRegistration。改变路由代码的文件名称为如下:

using System.Web.Mvc;
namespace CodeForMvcTest.Areas.RightManage
{
    public class RightManageAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "SystemManage/RightManage";
            }
        }
        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "SystemManage_RightManage_default",
                "SystemManage/RightManage/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

 1.2Model

权限模块的Model可参看第三章项目架构的系统共有类,对应model为TreeModel.cs。文件路径为Areas/SystemManage/Models。

 1.3视图

权限模块的视图包含在权限域中,文件路径为Areas/SystemManage/OperatorManage/Views/RightManage,视图名称为RightMange.cshtml。视图的完整代码如下:

技术分享
 1 @{
 2     ViewBag.Title = "权限管理";
 3     Layout = "~/Views/Shared/_BaseLayout.cshtml";
 4 }
 5 
 6 <div class="easyui-layout" data-options="fit:true">
 7 
 8     <div data-options="region:‘north‘,split:true" style="height: 50px;">
 9         <table style="margin-left: 5px; margin-top: 5px;">
10             <tr>
11                 <td><span style="margin-left: 10px;">用户组:</span></td>
12                 <td>
13                     <select class="easyui-combobox" name="operatorGroupId" id="operatorGroupId" style="width: 150px;"
14                         data-options="editable:false,required:true,onSelect:GetRightList">
15                         @Html.Raw(ViewBag.GroupList)
16                     </select>
17                 </td>
18                 <td>
19                     <button id="btn_submit" style="margin-left: 10px; margin-right: 10px;" onclick="UpdateRight();">保存修改</button>               
20                 </td>
21             </tr>
22         </table>
23 
24     </div>
25 
26     <div data-options="region:‘center‘,split:true" style="padding-bottom: 10px; padding-top: 10px;">
27         <ul class="easyui-tree" id="pageTree"
28             data-options="
29                checkbox:true,
30                url:‘/SystemManage/RightManage/RightManage/GetRightTree‘,
31                method:‘get‘,
32                onLoadSuccess:GetRightList">
33         </ul>
34         <br />
35     </div>
36 
37 </div>
38 
39 @section scripts
40 {
41     <script type="text/javascript" src="/Areas/SystemManage/SystemJS/rightManage.js"></script>
42     <script type="text/javascript">    
43     </script>
44 }
RightManage.cshtml

 

 1.4JS文件

权限模块相关的JS文件路径为Areas/SystemManage/SystemJS,JS文件名称为rightManage.js。JS的完整代码如下:

技术分享
 1 //加载用户组对应的权限列表
 2 function GetRightList() {
 3     LoadMask("正在查询,请稍等... ...");
 4 
 5     var operatorGroupId = $("#operatorGroupId").combobox("getValue");
 6     var roots = $("#pageTree").tree(‘getRoots‘);
 7     if (roots != null && roots.length > 0) {
 8         for (var i = 0; i < roots.length; i++) {
 9             $("#pageTree").tree("uncheck", roots[i].target);
10         }
11     }
12 
13     $.ajax({
14         url: ‘/SystemManage/RightManage/RightManage/RightManage‘,
15         data: { operatorGroupId: operatorGroupId },
16         type: ‘POST‘,
17         dataType: ‘json‘,
18         success: function (data) {
19             if (data.isSuccess == "0") {
20                 alert("未能成功加载用户组对应权限!");
21             } else {
22                 if (data.dataList.length > 0) {
23                     for (var i = 0; i < data.dataList.length; i++) {
24                         var nodeId = data.dataList[i];
25                         var node = $("#pageTree").tree("find", nodeId);
26                         if (node != null && $("#pageTree").tree("isLeaf", node.target) == true) {
27                             $("#pageTree").tree("check", node.target);
28                         }
29                     }
30                 }
31             }
32             HideMask();
33         },
34         error: function (data) {
35             if (data.responseText.indexOf("/Login/Login") >= 0) {
36                 window.parent.location.href = ‘/Login/Login‘;
37             }
38             alert("加载用户组对应权限出错!");
39             HideMask();
40         }
41     });
42 };
43 
44 //修改用户组的权限
45 function UpdateRight() {
46     LoadMask("正在修改,请稍等... ...");
47     var operatorGroupId = $("#operatorGroupId").combobox("getValue");
48     var nodes = $("#pageTree").tree("getChecked");  //选中的所有节点
49     //将所有叶子节点(即页面节点)的ID值取出,组合为数组
50     var rightArray = [];
51     if (nodes.length > 0) {
52         var j = 0;
53         for (var i = 0; i < nodes.length; i++) {
54             if ($("#pageTree").tree(‘isLeaf‘, nodes[i].target) == true) {
55                 var nodeObj;
56                 nodeObj = {
57                     PageIndex: nodes[i].id
58                 };
59                 rightArray[j] = nodeObj;
60                 j++;
61             }
62         }
63     }
64 
65     $.ajax({
66         url: ‘/SystemManage/RightManage/RightManage/UpdateRight‘,
67         data: { operatorGroupId: operatorGroupId, rightIdListStr: JSON.stringify(rightArray) },
68         dataType: ‘text‘,
69         type: ‘POST‘,
70         traditional: true,
71         success: function (data) {
72             if (data.indexOf("/Login/Login") >= 0) {
73                 window.parent.location.href = ‘/Login/Login‘;
74             }
75             alert(data);
76             HideMask();
77         },
78         error: function (data) {
79             if (data.responseText.indexOf("/Login/Login") >= 0) {
80                 window.parent.location.href = ‘/Login/Login‘;
81             }
82             alert("修改权限出错!");
83             HideMask();
84         }
85     });
86 
87 
88 };
rightManage.js

 

1.5控制器

权限模块的控制器包含在权限域中,文件路径为Areas/SystemManage/PageMange/Controllers,控制器名称为RightManageController.cs。控制器的完整代码如下:

技术分享
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.Mvc;
  6 using Session;
  7 using OdbcDbAccess;
  8 using System.Data;
  9 using Models;
 10 using Controllers;
 11 using System.Data.SqlClient;
 12 using Newtonsoft.Json;
 13 using LogInfo;
 14 using System.IO;
 15 using System.Text;
 16 
 17 namespace CodeForMvcTest.Areas.RightManage.Controllers
 18 {
 19     public class RightManageController : BaseController
 20     {
 21         /// <summary>
 22         /// ****************************
 23         /// 功能:权限处理类
 24         /// 作者:Author
 25         /// 时间:2015-7-18
 26         /// 邮箱:1129137758@qq.com
 27         /// ****************************
 28         
 29         public ActionResult RightManage()
 30         {
 31             IList<OperatorGroup> groupList = GetOperatorGroup();
 32             ViewBag.GroupList = DataTransfor.ListToComboboxHtml(groupList, "GroupId", "GroupName", false);
 33             return View();
 34         }
 35 
 36         /// <summary>
 37         /// 获取权限树
 38         /// </summary>
 39         /// <returns></returns>
 40         public ActionResult GetRightTree()
 41         {
 42             IList<TreeModel> catalogNodeList = new List<TreeModel>();
 43             //查询语句
 44             string sql = "select * from catalog where isavailable=1 order by catalogid,showno";
 45             try
 46             { 
 47                 //获取目录数据,并封装
 48                 DataSet categoryDs = SqlHelper.ExecuteQuery(SqlSeverConnectionName, sql);
 49                 if (categoryDs != null && categoryDs.Tables.Count > 0)
 50                 {
 51                     catalogNodeList = TreeModel.BuildTreeNodeList(categoryDs.Tables[0].Rows, "catalogid", "catalogname",
 52                         "parentid", false);
 53                     //获取页面数据
 54                     sql = "select catalogid,pageid,pagename from pageinfo where isavailable=1 order by catalogid,showno";
 55                     DataSet pageDs = SqlHelper.ExecuteQuery(SqlSeverConnectionName, sql);
 56 
 57                     if (pageDs != null && pageDs.Tables.Count > 0)
 58                     {
 59                         DataTable table = pageDs.Tables[0];
 60                         foreach (DataRow pageRow in table.Rows)
 61                         {
 62                             decimal parentId = DBNull.Value.Equals(pageRow["catalogid"]) ? 0 : Convert.ToDecimal(pageRow["catalogid"]);
 63                             decimal id = DBNull.Value.Equals(pageRow["pageid"]) ? 0 : Convert.ToDecimal(pageRow["pageid"]);
 64                             id = Convert.ToDecimal(parentId + id.ToString("0000"));
 65                             string pageName = DBNull.Value.Equals(pageRow["pagename"]) ? "" : Convert.ToString(pageRow["pagename"]);
 66 
 67                             var node = new TreeModel
 68                             {
 69                                 id = id,
 70                                 text = pageName,
 71                                 state = "close"
 72                             };
 73 
 74                             if (!TreeModel.FoundTreeNode(catalogNodeList, node, parentId))
 75                             {
 76                                 catalogNodeList.Add(node);
 77                             }
 78 
 79                         }
 80                     }
 81                 }
 82             }
 83             catch (Exception ex)
 84             {
 85                 Log.SaveErrorLog(ex.ToString(), "构建页面列表树出错!");
 86             }
 87             return Json(catalogNodeList, JsonRequestBehavior.AllowGet);
 88         }
 89 
 90 
 91         /// <summary>
 92         /// 通过用户组ID获取拥有的页面权限
 93         /// </summary>
 94         /// <param name="operatorGroupId">用户组ID</param>
 95         /// <returns></returns>
 96         [HttpPost]
 97         public ActionResult RightManage(int operatorGroupId)
 98         {
 99             //对应的节点ID
100             IList<decimal> nodeId = new List<decimal>();
101 
102             try
103             {
104                 string sql = "select * from rightlist where operatorgroupid=‘" + operatorGroupId + "";
105                 DataSet dataSet = SqlHelper.ExecuteQuery(SqlSeverConnectionName, sql);
106                 if (dataSet != null && dataSet.Tables.Count > 0)
107                 {
108                     DataTable table = dataSet.Tables[0];
109                     decimal categoryId, pageId;
110                     foreach (DataRow dr in table.Rows)
111                     {
112                         categoryId = Convert.ToDecimal(dr["categoryid"]);
113                         pageId = Convert.ToDecimal(categoryId + Convert.ToInt32(dr["pageid"]).ToString("0000"));
114                         if (!nodeId.Contains(categoryId))
115                         {
116                             nodeId.Add(categoryId);
117                         }
118                         nodeId.Add(pageId);
119                     }
120                 }
121                 object result = new
122                 {
123                     isSuccess = 1,
124                     dataList = nodeId
125                 };
126                 return Json(result);
127             }
128             catch (Exception ex)
129             {
130                 Log.SaveErrorLog(ex.ToString(), "查询用户组权限出错");
131                 object result = new
132                 {
133                     isSuccess = 0
134                 };
135                 return Json(result);
136             }
137         }
138 
139 
140         /// <summary>
141         /// 修改用户组权限
142         /// </summary>
143         /// <param name="operatorGroupId">用户组ID</param>
144         /// <param name="rightIdList">权限ID列表</param>
145         /// <returns></returns>
146         [HttpPost]
147         public ActionResult UpdateRight(int operatorGroupId, string rightIdListStr)
148         {
149             IList<Page> rightIdList = JsonConvert.DeserializeObject<IList<Page>>(rightIdListStr);
150             var sql = new StringBuilder();
151             sql.Append("delete from rightlist where operatorgroupid=").Append(operatorGroupId);
152         
153                 try
154                 {
155                     if (rightIdList != null && rightIdList.Count > 0)
156                     {
157                         string sqlItem = "insert into rightlist (pageid,categoryid,operatorgroupid,state,issys) values ({0},{1},{2},1,0)";
158                         foreach (Page item in rightIdList)
159                         {
160                             string pageNodeId = item.PageIndex.ToString();
161                             if (pageNodeId.Length > 4)
162                             {
163                                 string categoryId = pageNodeId.Substring(0, pageNodeId.Length - 4);
164                                 string pageId = pageNodeId.Substring(pageNodeId.Length - 4, 4);
165 
166                                 sql.Append(";").Append(string.Format(sqlItem, Convert.ToInt32(pageId), categoryId, operatorGroupId));
167                             }
168                         }                   
169                     }
170                     string sqlinfo=sql.ToString ();
171                    int result=SqlHelper .ExecuteTran(SqlSeverConnectionName,sqlinfo);
172 
173                     Log.SaveOperatorLog("", 1, "修改权限成功");
174                     return Content("修改成功!");
175                 }
176                 catch (Exception ex)
177                 {
178                     
179                     Log.SaveErrorLog(ex.ToString(), "修改权限出错");
180                     return Content("未能成功修改权限!");
181                 }
182            
183         }
184 
185 
186         /// <summary>
187         /// 获取用户组列表
188         /// </summary>
189         /// <returns></returns>
190         private IList<OperatorGroup> GetOperatorGroup()
191         {
192             IList<OperatorGroup> groupList = new List<OperatorGroup>();
193             string sql = "select * from operatorgroup order by groupid";
194             try
195             {
196                 DataSet dataSet = SqlHelper.ExecuteQuery(SqlSeverConnectionName, sql);
197                 int[] columnIndexArray = { 0, 1, 3, 4, 7 };
198                 string[] propertyArray = { "GroupId", "GroupName", "OrderNum", "State", "ParentId" };
199                 groupList = DataTransfor.DataSetTransfor<OperatorGroup>(dataSet, columnIndexArray, propertyArray);
200             }
201             catch (Exception ex)
202             {
203                 Log.SaveErrorLog(ex.ToString(), "获取用户组出错!");
204             }
205             return groupList;
206         }
207     }
208 }
RightManage.cs

 

1.6界面运行截图

权限管理主界面如下图所示:

技术分享

 

Web应用程序系统的多用户权限控制设计及实现-权限模块【10】

标签:

原文地址:http://www.cnblogs.com/wlandwl/p/rightMange.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!