MVC website development permission management, mvc website development

Source: Internet
Author: User

MVC website development permission management, mvc website development

I. Preface

It didn't take long for the company to get started with MVC. Now I can't understand it. I can only say that it will use this level. I feel that MVC is powerful in Web writing and Its layers are clear.

Today, I want to write about permission management. I feel that the permissions of a website are mainly divided into menu permissions and role permissions. First, role permissions, it is relatively simple for different roles to see different pages. This is role permissions. Menu permissions can also be called Operation permissions, that is, specific buttons, or viewing or using permissions in a drop-down box.

Ii. Role Permissions

1. User Role

First, role permissions. each user has a variety of roles and one-to-many relationships.

2. menu management

In menu management, we can manage a menu in this way. It is easier to control a role by √.

3. Database

Let's take a look at the tables with roles and the user-role relationship tables in the database.

The relationship table between the role and the menu. The PermissionIDs field is separated by | as the operation permission.

4. User Logon

When a user logs on, he/she can obtain all his/her roles and store them in the Session based on the login user's ID, and find the corresponding menu based on the login user.

// Role basic information SqlHelperParameter sqlHelperParameterRole = new SqlHelperParameter (); sqlHelperParameterRole. add ("UserId", dtUserRow ["UserId"]. toString (); DataTable dtRole = SqlHelper. executeDataTable (@ "select Sys_Roles.RoleId, Sys_Roles.RoleName, Sys_Roles.Weight from (select UserId, RoleId from Sys_UsersInRoles where UserId = @ UserId) as a left join Sys_Roles on. roleId = Sys_Roles.RoleId ", sqlHelperParameterRole); int dtRoleCount = dtRole. rows. count; RoleWeightMax = int. maxValue; for (int I = 0; I <dtRoleCount; I ++) {RolesSession rs = new RolesSession (); rs. roleID = Guid. parse (dtRole. rows [I] ["RoleId"]. toString (); rs. roleName = dtRole. rows [I] ["RoleName"]. toString (); rs. weight = Convert. toInt32 (dtRole. rows [I] ["Weight"]); if (RoleWeightMax> rs. weight) {RoleWeightMax = rs. weight;} RoleList. add (rs );}
Public class RolesSession {public Guid RoleID {get; set;} public string RoleName {get; set ;}// Weight public int Weight {get; set ;}}

Front-end code:

<Div data-options = "region: 'west', split: true" title = "navigation menu" style = "width: 200px; padding1: 1px; overflow: hidden; "id =" left_nav "> <div class =" easyui-accordion "data-options =" fit: true, border: false "> @ H9C. PMS. BLL. logOn. menuList. getMenu (ViewBag. userName) </div>

Controller:

Public static MvcHtmlString GetMenu (string userName) {Menu menu = new Menu (); MenuStructure MS = menu. GetMenuListStructure (userName); if (MS! = Null) {ms. children. remove (ms. children. firstOrDefault (o => o. modelCode = "0" & o. parentID = "0");} return new MvcHtmlString (MenuNav ("0", MS);} private static string MenuNav (string menuCode, MenuStructure menuStruc) {if (menuStruc = null) {return "<div> no menu available </div>" ;}list <MenuStructure> List = menuStruc. children. where (m => m. parentID = menuCode ). toList (); StringBuilder sbMenu = new St RingBuilder (); foreach (var item in list) {if (item. parentID = "0") {sbMenu. append ("<div title = \" "+ item. title + "\" style = \ "overflow: auto; \"> "); sbMenu. append ("<ul id = \" menu "+ item. parentID + "\" class = \ "easyui-tree \" animate = \ "true \" dnd = \ "true \"> "); sbMenu. append ("<li>");} else {sbMenu. append ("<ul id = \" menu "+ item. parentID + "\" class = \ "easyui-tree \" animate = \ "true \" dnd = \ "true \"> "); I F (item. children. count = 0) {sbMenu. append ("<li>");} else {sbMenu. append ("<li state = \" closed \ ">") ;}} sbMenu. append ("<span>"); if (item. url = "/") {sbMenu. append ("<a class = \" e-submenu \ "href = \" javascript: void (0); \ "title = \" "+ item. title + "\"> ");} else {string tabsIcon =" 14 "; if (! String. isNullOrWhiteSpace (item. icon) {tabsIcon = item. icon. replace ("/Content/images /",""). replace (". png "," ");} sbMenu. append ("<a class = \" e-submenu \ "href = \" # \ "onclick = \" addTab ('"+ item. url + "','" + item. title + "') \"> "); sbMenu. append (" ");} sbMenu. append ("" + item. title + ""); sbMenu. append ("</a> </span>"); if (IsExistParent (item. modelCode, item) {sbMenu. append (MenuNav (item. modelCode, item);} sbMenu. append ("</li>"); sbMenu. append ("</ul>"); if (item. parentID = "0") {sbMenu. append ("</div>") ;}} return sbMenu. toString ();} private static bool IsExistParent (string modelCode, MenuStructure menuModels) {var query = menuModels. children. firstOrDefault (m => m. parentID = modelCode); if (query = null) {return false;} return true ;}

Menu type:

public class MenuStructure {  public string ModelCode;  public string Title;  public string Icon;  public string Url;  public string ParentID;  public List<MenuStructure> Children = new List<MenuStructure>(); }

The GetMenuListStructure () method obtains the menu list structure based on the user name. Here, the user name is unique in the database, note that the menu has a parent Menu Sub-menu according to the class. Therefore, there must be two loops in the method to add the Sub-menu.

Iii. Menu Permissions
That is, the Operation permission, such as the operation permission of a button. First, we store all the operation permissions on the button in a class. (For better methods, please recommend it to me)

Public class Menus {public static int gongdan = 503000000; // task ticket}

Then, the Controllers (load page) of the page on which the button for Operation permission is located is stored in ViewBag, as shown below:

Public ActionResult Index () {H9C. PMS. BLL. RBAC. permission pm = new BLL. RBAC. permission (); ViewBag. isReportPlan = pm. isRoleHavePermissions (Roles. shigongduizhang, Menus. gongdan, base. userSessionModel, Menus. gongdanReportPlanByShiGongTeamer); // report the construction plan return View ();}
/// <Summary> /// determine whether a permission is in the list of permissions granted to a role. /// </summary> /// <param name = "roleId"> </param> /// <param name = "modelCode"> </param> /// <param name = "userSessionModel"> </param> /// <param name = "permissionCode"> </param> // <returns> </returns> public bool IsRoleHavePermissions (Guid roleId, int modelCode, UserSessionModel userSessionModel, int permissionCode) {List <PermissionModel> permissionModelList = this. getRolePermissionList (roleId, modelCode, userSessionModel); if (permissionModelList = null) {return false;} foreach (var o in permissionModelList) {if (o. PCode = permissionCode) {return true ;}} return false ;}
/// <Summary> /// obtain the list of permissions of a role /// </summary> /// <param name = "roleId"> </param> /// <param name = "modelCode"> </param> /// <param name = "userSessionModel"> </param> /// <returns> </returns> public List <permissionModel> GetRolePermissionList (Guid roleId, int modelCode, UserSessionModel userSessionModel) {foreach (var o in userSessionModel. roleList) {if (o. roleID = roleId) {List <Model. RBAC. permissionModel> permissionList = this. permissionList (roleId, modelCode); return permissionList ;}} return null ;}
/// <Summary> /// obtain the permissions of a role under a menu /// </summary> /// <param name = "modelId"> </param> /// <param name = "menuId"> </param> /// <returns> </returns> public List <PermissionModel> PermissionList (Guid roleId, int menuId) {List <PermissionModel> pmList = new List <PermissionModel> (); using (RBACContext connEF = new RBACContext () {Sys_Role_Model_Permissions srmp = connEF. sys_Role_Model_Permissions.FirstOrDefau Lt (o => o. ModelID = menuId & o. RoleId = roleId); if (srmp! = Null) {string permissions = srmp. PermissionIDs; if (! String. isNullOrWhiteSpace (permissions) {string [] pids = permissions. split (new char [] {'|'}); for (int I = 0; I <pids. length; I ++) {if (! String. isNullOrWhiteSpace (pids [I]) {pmList. add (new PermissionModel () {ModelCode = menuId, PCode = Convert. toInt32 (pids [I]), PName = ""}) ;}}}return pmList ;}

In the last method, EF is used to obtain permissions of a role under a menu based on the menu and role.
The front-end is very simple:

@ If (ViewBag. isReportPlan = true) {@: <a href = "#" class = "easyui-linkbutton l-btn" iconcls = "icon-add"> button </a>}

Iv. Conclusion 

To sum up, you must first have a menu management module, which can not only manage menus, but also manage permissions in menus and permissions of each role on menus, and then control the background, the weight stored in the above permission Model indicates that each role has a weight, and each user has its maximum weight. Based on this weight, we can control many conditions, simply put, it is also for convenience.
The first technical document requires a lot of training. I will try to write more blog posts in the future. coders who do not write documents are not good programmers.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.