📜 ⬆️ ⬇️

Divide and rule. Or a rights sharing system for ASP MVC

Very often in my work I face the problem of separation of access rights to sections of the site and controls.
At first, I had enough of the tools that the ASP MVC provides out of the box, but over time, I was faced with the need to create my own rights sharing tool. If you, dear% habrauser%, wonder how you can solve this problem, welcome under cat.

Some lyrics


In one of the projects I encountered the problem of separation of access rights to sections and elements of the site. This is the company's internal website where employees can plan their vacation. TK was written, surprisingly, well. The work went at an accelerated pace and in a month of work a working prototype was ready. Everyone was delighted exactly until the moment when the “clarifications” on the operation of the system did not begin. And since the bureaucrat has been sitting in our man since birth, there was a bunch of agreements and discussions, the result of which was something like this: “Everything is fine. But this is not an ordinary user to see. And this should only see the administrator. And this must be seen only by a highly secret administrator and no one else! ” And this, unfortunately, is not the end of the customer's hectic fantasy.
Standard means of managing roles and access can be done, but it is too dreary. Therefore, I took up the creation of a module of separation of access rights, which can be easily managed.

Getting started


To begin with, the basic requirements for the module were derived.
  1. Simple separation of access rights to controller methods (according to the principle of the Authorize attribute)
  2. An easy-to-use mechanism for sharing access to site elements
  3. The ability to create roles with any variations of access
  4. Ability to use in different projects

Then the “work” was done on drawing various schemes and viewing a huge pile of materials on the topic. As a result, the module concept was developed.
The data needed for the module will be stored in the MSSQL database (and what else, if we write in c #). The centralized repository did not do because of the peculiarities of the corporate network structure and the idea of ​​using (in theory) on any project. Therefore, we will write our own module data set in the project database.
Also, based on the idea that the module should work with any project, it should read the settings from the web.config file of the project to which the module is connected.
Well, let the module know how to prepare a base for itself and makes the initial configuration so that the deployment on a new project is as simple as ... ahem. Well, you understand.
And on delicious, let it by default enter all newly created or added elements and sections into tables and give access to “supermin”, so that when working, you do not have to go into the settings every time.

Beginning of work

First I want to say a few words about the resulting module. For his work, he uses a samopisny RoleProvider. And the reason for its use again became the peculiarities of the corporate network. Thus, on one of the servers a reference book is made in which all the data on employees and binding to the domain login are located. Do not ask why. This is an established state of affairs.
So, for internal needs in the directory there are groups for employees. Therefore, its role provider was written, which not only performed its main functions, but operated in groups in the directory on the server. I will not bring it, because it does not represent special interest and you will not find anything new in the writing of the provider. (in the code snippets there will be an appeal to the AuthLib namespace, which contains the role provider).
')
Until the code has gone, I want to apologize for the comments and other garbage in the code. The above code is obsolete (in the realities of current projects) and is given only to demonstrate the idea.

First of all, create a class that describes the user. So it will be easier to work in the future.

Class 'Employee'
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; namespace Ekzo.BaseClasses { public class Employee : IEquatable<Employee> { /// <summary> ///     /// </summary> public int Id { get; set; } /// <summary> ///   /// </summary> public string Name { get; set; } /// <summary> ///   /// </summary> /// <param name="id">  </param> public Employee(int id) { InitClass(id); } /// <summary> ///   /// </summary> /// <param name="employeeName"> </param> public Employee(string employeeName) { using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SELECT employee_id FROM employee WHERE employee_name LIKE @employeeName+'%' AND date_fired IS NULL", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@employeeName", string.Join("%", employeeName.Split(char.Parse(" ")))); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.Id = reader.GetInt32(0); } reader.Close(); } catch (Exception ex) { if (Ekzo.Web.Configuration.s_log != null) Ekzo.Web.Configuration.s_log.Error("[  ] [   ]", ex); } } } if (this.Id != 0) InitClass(this.Id); } /// <summary> ///   /// </summary> public Employee() { } /// <summary> ///    /// </summary> /// <param name="id">   </param> private void InitClass(int id) { this.Id = id; using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SELECT employee_name FROM employee WHERE employee_id=@employeeID AND date_fired IS NULL", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@employeeID", this.Id); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.Name = reader.GetString(0); } reader.Close(); } catch (Exception ex) { if (Ekzo.Web.Configuration.s_log != null) Ekzo.Web.Configuration.s_log.Error("[  ] [   ]", ex); } } } } public bool Equals(Employee x, Employee y) { if (x.Name == y.Name && x.Id == y.Id) return true; else return false; } public override int GetHashCode() { int hasEmployeeName = this.Name == null ? 0 : this.Name.GetHashCode(); int hasID = this.Id == 0 ? 0 : this.Id.GetHashCode(); return hasEmployeeName ^ hasID; } public bool Equals(Employee other) { if (this.Name == other.Name && this.Id == other.Id) return true; else return false; } bool IEquatable<Employee>.Equals(Employee other) { if (this.Name == other.Name && this.Id == other.Id) return true; else return false; } } } 



Now we will prepare classes that describe the elements of the system (sections, links, controls, etc.)

Class 'Action'
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Ekzo.Web.Security.Utilization.Authorization { /// <summary> ///   .        ,    . /// </summary> public class Action { /// <summary> ///    /// </summary> public int id { get; private set; } /// <summary> /// ,     /// </summary> private int[] _ActionGroups; /// <summary> /// ,     /// </summary> public ActionGroup[] ActionGroups { get { List<ActionGroup> Groups = new List<ActionGroup>(); if (_ActionGroups != null) { for (int i = 0; i < _ActionGroups.Count(); i++) Groups.Add(new ActionGroup(_ActionGroups[i])); return Groups.ToArray(); } return null; } } /// <summary> ///       /// </summary> public string ActionName { get; set; } /// <summary> ///     /// </summary> public bool Active { get; private set; } #region ClassBuilder public Action() { } public Action(string ActionName) { InitClass(ActionName); } public Action(int id) { InitClass(null, id); } private void InitClass(string name, int id = 0, int actionGroup = 0) { if (id != 0) this.id = id; if (!string.IsNullOrEmpty(name)) this.ActionName = name; //this._ActionGroups = actionGroup; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Authorization_Actions WHERE id=@id OR Name=@actionName", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", id); cmd.Parameters.AddWithValue("@actionName", string.IsNullOrEmpty(name) ? "" : name); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.id = reader.GetInt32(0); this.ActionName = reader.GetString(1); this.Active = reader.GetBoolean(2); } reader.Close(); List<int> actionGroups = new List<int>(); cmd.CommandText = "SELECT GroupID FROM Authorization_ActionToGroup WHERE ActionID=@id"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@id", this.id); reader = cmd.ExecuteReader(); while (reader.Read()) actionGroups.Add(reader.GetInt32(0)); this._ActionGroups = actionGroups.ToArray(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } } #endregion /// <summary> ///   /// </summary> public void Save() { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(@" IF((SELECT COUNT(*) FROM Authorization_Actions WHERE id=@id OR Name=@name)=0) BEGIN INSERT INTO Authorization_Actions(Name) VALUES(@name) INSERT INTO Authorization_ActionToGroup(ActionID,GroupID) VALUES((SELECT TOP(1) id FROM Authorization_Actions WHERE Name=@name),0) END ELSE UPDATE Authorization_Actions SET Name=@name, Active=@active SELECT * FROM Authorization_Actions WHERE Name=@name", conn)) { try { conn.Open(); if (!string.IsNullOrEmpty(this.ActionName) && this.id == 0) cmd.CommandText = cmd.CommandText.Replace("WHERE id=@id OR Name=@name", "WHERE Name=@name"); cmd.Parameters.AddWithValue("@id", this.id); cmd.Parameters.AddWithValue("@name", this.ActionName); cmd.Parameters.AddWithValue("@active", this.Active); //cmd.Parameters.AddWithValue("@groupID", this._ActionGroup); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); List<int> actionGroups = new List<int>(); while (reader.Read()) { this.id = reader.GetInt32(0); this.ActionName = reader.GetString(1); this.Active = reader.GetBoolean(2); } reader.Close(); cmd.CommandText = "SELECT GroupID FROM Authorization_ActionToGroup WHERE ActionID=@id"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@id", this.id); reader = cmd.ExecuteReader(); while (reader.Read()) actionGroups.Add(reader.GetInt32(0)); this._ActionGroups = actionGroups.ToArray(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } } /// <summary> ///   /// </summary> public void Delete() { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_Actions WHERE id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM Autorization_ActionToGroup WHERE ActionID=@id"; cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } } /// <summary> ///     /// </summary> /// <returns></returns> public bool IsExist() { return IsExist(this.ActionName); } /// <summary> ///    /// </summary> /// <param name="ActionName"> </param> /// <returns></returns> public static bool IsExist(string ActionName) { bool result = false; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM Authorization_Actions WHERE Name=@name", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@name", ActionName); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) result = reader.GetInt32(0) == 0 ? false : true; } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } return result; } /// <summary> ///      /// </summary> /// <returns></returns> public static List<Action> GetAllActions() { List<Action> result = new List<Action>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT id FROM Authorization_Actions ORDER BY Name ", conn)) { try { conn.Open(); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) result.Add(new Action(reader.GetInt32(0))); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } return result; } /// <summary> ///     /// </summary> /// <param name="groupID"></param> public void AddToGroup(int groupID) { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(@" IF((SELECT COUNT(*) FROM Authorization_ActionToGroup WHERE ActionID=@action AND GroupID=@group)=0) INSERT INTO Authorization_ActionToGroup(ActionID,GroupID) VALUES(@action,@group)", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@action", groupID); cmd.Parameters.AddWithValue("@group", this.id); cmd.ExecuteNonQuery(); new Action(this.id); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } } } } 



Class 'Action Groups'
 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ekzo.Web.Security.Utilization.Authorization { /// <summary> ///     /// </summary> public class ActionGroup { /// <summary> ///     /// </summary> public int id { get; private set; } /// <summary> ///  ,      /// </summary> public SystemRole[] Roles { get; private set; } /// <summary> ///   /// </summary> public string Name { get; private set; } /// <summary> ///   .    ,   . /// </summary> public bool Active { get; set; } /// <summary> ///  . /// </summary> public Action[] GroupActions { get; private set; } #region ClassBuilder public ActionGroup(int id) { InitClass(null, id); } public ActionGroup(string name) { InitClass(name); } private void InitClass(string name, int id = 0) { if (id != 0) this.id = id; if (!string.IsNullOrEmpty(name)) this.Name = name; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Authorization_ActionGroups WHERE id=@id OR Name=@groupName", conn)) { try { conn.Open(); if (!string.IsNullOrEmpty(name) && id == 0) cmd.CommandText = "SELECT * FROM Authorization_ActionGroups WHERE Name=@groupName"; cmd.Parameters.AddWithValue("@id", this.id); cmd.Parameters.AddWithValue("@groupName", this.Name == null ? "" : this.Name); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.id = reader.GetInt32(0); if (string.IsNullOrEmpty(this.Name)) this.Name = reader.GetString(1); this.Active = reader.GetBoolean(2); } reader.Close(); cmd.CommandText = "SELECT * FROM Authorization_RoleToActionGroup WHERE ActionGroup=@groupID"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@groupID", this.id); reader = cmd.ExecuteReader(); List<SystemRole> rolesList = new List<SystemRole>(); while (reader.Read()) rolesList.Add(new SystemRole(this.id, reader.GetString(2))); this.Roles = rolesList.ToArray(); reader.Close(); cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@id", this.id); List<Action> actionsList = new List<Action>(); cmd.CommandText = "SELECT ActionID FROM Authorization_ActionToGroup WHERE GroupID=@id"; reader = cmd.ExecuteReader(); while (reader.Read()) { actionsList.Add(new Action(reader.GetInt32(0))); } this.GroupActions = actionsList.Distinct().ToArray(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } } #endregion /// <summary> ///   /// </summary> public void Save() { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(@" IF((SELECT COUNT(*) FROM Authorization_ActionGroups WHERE Name=@name)=0) INSERT INTO Authorization_ActionGroups(Name) VALUES(@name) ELSE UPDATE Authorization_ActionGroups SET Name=@name, Active=@active WHERE id=@id SELECT * FROM Authorization_ActionGroups WHERE Name=@name", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.Parameters.AddWithValue("@name", this.Name); cmd.Parameters.AddWithValue("@active", this.Active); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.id = reader.GetInt32(0); this.Name = reader.GetString(1); this.Active = reader.GetBoolean(2); } reader.Close(); cmd.CommandText = "SELECT * FROM Authorization_RoleToActionGroup WHERE ActionGroup=@id"; reader = cmd.ExecuteReader(); List<SystemRole> rolesList = new List<SystemRole>(); while (reader.Read()) rolesList.Add(new SystemRole(reader.GetString(2))); this.Roles = rolesList.ToArray(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } } /// <summary> ///  . /// </summary> /// <remarks>        .</remarks> public void Delete() { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_ActionGroups WHERE id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM Authorization_RoleToActionGroup WHERE ActionGroup=@id"; cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM Authorization_ActionToGroup WHERE GroupID=@id"; cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } } /// <summary> ///     /// </summary> /// <param name="actionID"> </param> public void DeleteAction(int actionID) { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_ActionToGroup WHERE ActionID=@action AND GroupID=@group", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@action", actionID); cmd.Parameters.AddWithValue("@group", this.id); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } } /// <summary> ///     /// </summary> /// <param name="roleID"> </param> public void DeleteRole(int roleID) { string roleName = ""; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT group_name FROM groups WHERE group_id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", roleID); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) roleName = reader.GetString(0); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_RoleToActionGroup WHERE ActionGroup=@group AND Role=@roleName", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@roleName", roleName); cmd.Parameters.AddWithValue("@group", this.id); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } } /// <summary> ///     /// </summary> /// <returns></returns> public static List<ActionGroup> GetAllgroups() { List<ActionGroup> result = new List<ActionGroup>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT id FROM Authorization_ActionGroups", conn)) { try { conn.Open(); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) result.Add(new ActionGroup(reader.GetInt32(0))); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } return result; } } } 



Class 'Controls'
 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ekzo.Web.Security.Utilization.Authorization { /// <summary> ///   ,     /// </summary> public class PageControl { /// <summary> ///       /// </summary> public int id { get; private set; } /// <summary> ///     /// </summary> public string Name { get; set; } /// <summary> /// ,     /// </summary> public List<PageControlsGroup> Groups { get; set; } #region ClassBuilder public PageControl(int id) { InitClass(id, null); } public PageControl(string name) { InitClass(0, name); } private void InitClass(int id, string Name) { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { //      ,     using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(@"IF((SELECT COUNT(*) FROM Authorization_Controls WHERE Name=@name OR id=@id)=0) INSERT INTO Authorization_Controls(Name) VALUES (@name)", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@name", Name == null ? "" : Name); cmd.Parameters.AddWithValue("@id", id); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT id,Name FROM Authorization_Controls WHERE Name=@name OR id=@id"; System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.id = reader.GetInt32(0); this.Name = reader.GetString(1); } reader.Close(); //        ,  //  -1 cmd.CommandText = "IF((SELECT COUNT(*) FROM Authorization_ControlToGroup WHERE ControlID=@id AND GroupID=-1)=0) INSERT INTO Authorization_ControlToGroup(ControlID,GroupID) VALUES(@id,-1)"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@id", this.id); cmd.Parameters.AddWithValue("@name", this.Name); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } this.Groups = new List<PageControlsGroup>(); List<int> groupsIDs = new List<int>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT GroupID FROM Authorization_ControlToGroup WHERE ControlID=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) groupsIDs.Add(reader.GetInt32(0)); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } for (int i = 0; i < groupsIDs.Count; i++) this.Groups.Add(new PageControlsGroup(groupsIDs[i])); } #endregion /// <summary> ///     /// </summary> /// <param name="groupID"></param> public void AddToGroup(int groupID) { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(@"IF((SELECT COUNT(*) FROM Authorization_ControlToGroup WHERE ControlID=@id AND GroupID=@group)=0) INSERT INTO Authorization_ControlToGroup(ControlID,GroupID) VALUES(@id,@group)", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.Parameters.AddWithValue("@group", groupID); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } } /// <summary> ///   /// </summary> public void Save() { string commandText = this.id == 0 ? "INSERT INTO Authorization_Controls (Name) VALUES(@name)" : "UPDATE Authorization_Controls SET Name=@name WHERE id=@id"; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(commandText, conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@name", this.Name); cmd.Parameters.AddWithValue("@id", this.id); cmd.ExecuteNonQuery(); cmd.CommandText = "IF((SELECT COUNT(*) FROM Authorization_ControlToGroup WHERE ControlID=(SELECT TOP(1) id FROM Authorization_Controls WHERE Name=@name) AND GroupID=-1)=0) INSERT INTO Authorization_ControlToGroup(ControlID,GroupID) VALUES(SELECT TOP(1) id FROM Authorization_Controls WHERE Name=@name,-1)"; cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } } /// <summary> ///   /// </summary> public void Delete() { if (this.id == 0) return; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_Controls WHERE id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } } /// <summary> ///     /// </summary> /// <returns></returns> public static PageControl[] GetAllControls() { List<PageControl> result = new List<PageControl>(); List<int> controlsIDs = new List<int>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT id FROM Authorization_Controls ORDER BY Name", conn)) { try { conn.Open(); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) controlsIDs.Add(reader.GetInt32(0)); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } for (int i = 0; i < controlsIDs.Count; i++) result.Add(new PageControl(controlsIDs[i])); return result.ToArray(); } } } 



Class 'Control Groups'
 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ekzo.Web.Security.Utilization.Authorization { /// <summary> ///     /// </summary> public class PageControlsGroup : IEquatable<PageControlsGroup>, IEqualityComparer<PageControlsGroup> { /// <summary> ///       /// </summary> public int id { get; private set; } /// <summary> ///   /// </summary> public string Name { get; set; } /// <summary> ///  ,   /// </summary> public List<ControlsGroupRole> Roles { get; set; } #region ClassBuilder public PageControlsGroup(int id) { InitClass(id, ""); } public PageControlsGroup(string Name) { this.Name = Name; InitClass(0, Name); } public PageControlsGroup(int id, string Name) { this.id = id; this.Name = Name; this.Roles = new PageControlsGroup(id).Roles; } private void InitClass(int id, string name) { //this.Controls = new List<PageControl>(); this.Roles = new List<ControlsGroupRole>(); List<int> pageControls = new List<int>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Authorization_ControlsGroup WHERE id=@id OR Name=@name", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", id); cmd.Parameters.AddWithValue("@name", name); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.id = reader.GetInt32(0); this.Name = reader.GetString(1); } reader.Close(); cmd.CommandText = @"SELECT Authorization_Controls.id AS ControlID FROM Authorization_ControlToGroup INNER JOIN Authorization_ControlsGroup ON Authorization_ControlToGroup.GroupID = Authorization_ControlsGroup.id INNER JOIN Authorization_Controls ON Authorization_ControlToGroup.ControlID = Authorization_Controls.id WHERE Authorization_ControlsGroup.id=@id OR Authorization_ControlsGroup.Name=@name"; reader = cmd.ExecuteReader(); while (reader.Read()) pageControls.Add(reader.GetInt32(0)); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } //for(int i=0;i<pageControls.Count;i++) // this.Controls.Add(new PageControl(pageControls[i])); List<int> groupRoles = new List<int>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT RoleID FROM Authorization_RoleToControlGroup WHERE GroupID=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) groupRoles.Add(reader.GetInt32(0)); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [     ] ", ex); } } } for (int i = 0; i < groupRoles.Count; i++) this.Roles.Add(new ControlsGroupRole(groupRoles[i], this.id)); } #endregion /// <summary> ///     /// </summary> /// <returns></returns> public static PageControlsGroup[] GetAllGroups() { List<PageControlsGroup> result = new List<PageControlsGroup>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Authorization_ControlsGroup", conn)) { try { conn.Open(); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) result.Add(new PageControlsGroup(reader.GetInt32(0), reader.GetString(1))); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } return result.ToArray(); } /// <summary> ///   /// </summary> public void Save() { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("IF((SELECT COUNT(*) FROM Authorization_ControlsGroup WHERE Name=@name)=0) INSERT INTO Authorization_ControlsGroup(Name) VALUES(@name)", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@name", this.Name); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } PageControlsGroup newGroup = new PageControlsGroup(this.Name); this.id = newGroup.id; this.Roles = newGroup.Roles; newGroup = null; } /// <summary> ///   /// </summary> public void Delete() { if (this.id != 0) using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_ControlsGroup WHERE id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM Authorization_RoleToControlGroup WHERE GroupID=@id"; cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } } /// <summary> ///     /// </summary> /// <param name="controlID"> </param> public void DeleteControl(int controlID) { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_ControlToGroup WHERE ControlID=@control AND GroupID=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@control", controlID); cmd.Parameters.AddWithValue("@id", this.id); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } } /// <summary> ///   /// </summary> /// <param name="roleID"> </param> public void DeleteRole(int roleID) { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_RoleToControlGroup WHERE RoleID=@role AND GroupID=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.Parameters.AddWithValue("@role", roleID); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } } #region InterfaceImplementation bool IEquatable<PageControlsGroup>.Equals(PageControlsGroup other) { return this.id == other.id & this.Name == other.Name; } public bool Equals(PageControlsGroup x, PageControlsGroup y) { return x.id == y.id & x.Name == y.Name; } public int GetHashCode(PageControlsGroup obj) { return this.id.GetHashCode() + this.Name.GetHashCode() + this.Roles.GetHashCode(); } #endregion } } 



' '
 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ekzo.Web.Security.Utilization.Authorization { /// <summary> ///        /// </summary> public class ControlsGroupRole { /// <summary> ///     ConsUser /// </summary> public int id { get; private set; } /// <summary> ///   /// </summary> public string Role { get { string result = null; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT group_name FROM groups WHERE group_id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.RoleID); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) result = reader.GetString(0); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } return result; } } /// <summary> ///   /// </summary> public int RoleID { get; set; } /// <summary> ///   /// </summary> public int GroupID { get; set; } public ControlsGroupRole(int id, int groupID) { this.id = id; this.GroupID = groupID; InitClass(id, groupID); } private void InitClass(int id, int groupID) { this.RoleID = id; this.GroupID = groupID; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Authorization_RoleToControlGroup WHERE RoleID=@role AND GroupID=@group", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@role", id); cmd.Parameters.AddWithValue("@group", groupID); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) this.id = reader.GetInt32(0); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [     ] ", ex); } } } } /// <summary> ///      /// </summary> public void Save() { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(@"IF((SELECT COUNT(*) FROM Authorization_RoleToControlGroup WHERE RoleID=@id AND GroupID=@group)=0) INSERT INTO Authorization_RoleToControlGroup(RoleID,GroupID) VALUES(@id,@group)", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.Parameters.AddWithValue("@group", this.GroupID); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } } } } 



' '
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Ekzo.Web.Security.Utilization.Authorization { /// <summary> ///     ConsUser /// </summary> public class SystemRole { /// <summary> ///       /// </summary> public int id { get; private set; } /// <summary> ///     ConsUser /// </summary> public int baseID { get; private set; } /// <summary> ///   /// </summary> public string Role { get; private set; } public int ActionGroup { get; private set; } public SystemRole() { } public SystemRole(string role) { InitClass(role); } public SystemRole(int actionGorup, string role) { InitClass(role, actionGorup); } public SystemRole(int baseID, int actionGroup = 0) { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT group_name FROM groups WHERE group_id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", baseID); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) this.Role = reader.GetString(0); this.baseID = baseID; this.ActionGroup = actionGroup; } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } } private void InitClass(string role, int actionGroup = -1) { this.ActionGroup = actionGroup; this.Role = role; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Authorization_RoleToActionGroup WHERE ActionGroup=@groupID AND Role=@role", conn)) { try { if (actionGroup == -1) cmd.CommandText = "SELECT * FROM Authorization_RoleToActionGroup WHERE Role=@role"; conn.Open(); cmd.Parameters.AddWithValue("@groupID", actionGroup); cmd.Parameters.AddWithValue("@role", role); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.id = reader.GetInt32(0); this.Role = reader.GetString(2); this.ActionGroup = reader.GetInt32(1); } } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [ ] ", ex); } } } using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT group_id FROM groups WHERE group_name=@name", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@name", this.Role); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) this.baseID = reader.GetInt32(0); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [ .    ] ", ex); } } } } /// <summary> ///    /// </summary> /// <param name="Name"> </param> /// <returns></returns> public static SystemRole CreateRole(string Name) { SystemRole role = new SystemRole(); role.Role = Name; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("INSERT INTO groups(group_id,group_name) SELECT MIN(group_id)-1,@name FROM groups WHERE group_id>-1000", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@name", Name); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT group_id FROM groups WHERE group_name=@name"; System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) role.baseID = reader.GetInt32(0); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("INSERT INTO Authorization_RoleToActionGroup(ActionGroup,Role) VALUES(@group,@name)", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@name", role.Role); cmd.Parameters.AddWithValue("@group", -1); cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } role.ActionGroup = -1; return role; } /// <summary> ///     /// </summary> /// <param name="employeeID"> </param> /// <returns></returns> public static string[] GetEmployeeRoles(int employeeID) { List<string> roles = new List<string>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT group_name FROM employee2group INNER JOIN groups ON intranet_employee2group.group_id = groups.group_id WHERE employee_id=@employeeID ORDER BY group_name", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@employeeID", employeeID); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) roles.Add(reader.GetString(0)); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } List<string> roleToDelete = new List<string>(); foreach (string role in roles) if (!HttpContext.Current.User.IsInRole(role)) roleToDelete.Add(role); for (int i = 0; i < roleToDelete.Count; i++) roles.Remove(roleToDelete[i]); return roles.ToArray(); } /// <summary> ///   /// </summary> public void Save() { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(@" IF((SELECT COUNT(*) FROM Authorization_RoleToActionGroup WHERE id=@id OR Role=@name AND ActionGroup=@groupID)=0) INSERT INTO Authorization_RoleToActionGroup(ActionGroup,Role) VALUES(@groupID, @name) ELSE UPDATE Authorization_RoleToActionGroup SET ActionGroup=@groupID, Role=@name WHERE id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.Parameters.AddWithValue("@name", this.Role); cmd.Parameters.AddWithValue("@groupID", this.ActionGroup); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Authorization_RoleToActionGroup WHERE Role=@name AND ActionGroup=@groupID"; System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { this.id = reader.GetInt32(0); this.ActionGroup = reader.GetInt32(1); this.Role = reader.GetString(2); } } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } } /// <summary> ///   /// </summary> /// <remarks>       ,    ConsUser</remarks> public void Delete() { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM Authorization_RoleToActionGroup WHERE id=@id", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@id", this.id); cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM Authorization_RoleToActionGroup WHERE ActionGroup=@id"; cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("DELETE FROM employee2group WHERE group_id=@groupID", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@groupID", this.baseID); cmd.ExecuteNonQuery(); cmd.Parameters.AddWithValue("@name", this.Role); cmd.CommandText = "DELETE FROM groups WHERE group_name=@name"; cmd.ExecuteNonQuery(); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [      ] ", ex); } } } } #region StaticFields /// <summary> ///       /// </summary> /// <returns></returns> public static List<string> GetAllRoles() { List<string> result = new List<string>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT DISTINCT Role FROM Authorization_RoleToActionGroup ORDER BY Role", conn)) { try { conn.Open(); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) result.Add(reader.GetString(0)); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [     ] ", ex); } } } return result; } /// <summary> ///      /// </summary> /// <returns></returns> public static List<string> GetAllIntranetRoles() { List<string> result = new List<string>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT DISTINCT group_name FROM groups ORDER BY group_name", conn)) { try { conn.Open(); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) result.Add(reader.GetString(0)); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [    ] ", ex); } } } return result; } /// <summary> ///      /// </summary> /// <param name="role"> </param> /// <returns></returns> public static List<BaseClasses.Employee> EmployeesInRole(string role) { List<BaseClasses.Employee> result = new List<BaseClasses.Employee>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT intranet_employee2group.employee_id FROM groups INNER JOIN intranet_employee2group on groups.group_id=intranet_employee2group.group_id WHERE group_name=@groupName", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@groupName", role); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) result.Add(new BaseClasses.Employee(reader.GetInt32(0))); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ,  ] ", ex); } } } return result; } /// <summary> ///      /// </summary> /// <param name="GroupName"> </param> /// <returns></returns> public static SystemRole[] GetGroupRoles(string GroupName) { ActionGroup group = new ActionGroup(GroupName); return GetGroupRoles(group.id); } /// <summary> ///      /// </summary> /// <param name="groupID">      </param> /// <returns></returns> public static SystemRole[] GetGroupRoles(int groupID) { List<SystemRole> rolesList = new List<SystemRole>(); using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Authorization_RoleToActionGroup WHERE ActionGroup=@groupID", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@groupID", groupID); System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) rolesList.Add(new SystemRole(reader.GetInt32(1), reader.GetString(2))); } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } return rolesList.ToArray(); } public static int? IntranetRoleID(string roleName) { int? result = null; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.StringName].ConnectionString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT group_id FROM groups WHERE group_name=@name", conn)) { try { conn.Open(); cmd.Parameters.AddWithValue("@name", roleName); using (System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader()) while (reader.Read()) result = reader.GetInt32(0); } catch (Exception ex) { Configuration.s_log.Error("[  ] [  ]", ex); } } } return result; } #endregion } } 



, (AuthorizeAttribute), , ( , ).

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Ekzo.Web.Security.Utilization { /// <summary> ///         /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class ActionAuthorization : AuthorizeAttribute { /// <summary> ///    /// </summary> public string ActionName { get; set; } /// <summary> ///        /// </summary> /// <param name="httpContext"></param> /// <returns>  ,  .      .</returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { bool result = false; var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) return false; Authorization.Action currentAction = new Authorization.Action(this.ActionName); //     , . if (!currentAction.IsExist()) currentAction.Save(); //  ,  . if (!currentAction.Active) return true; string[] currentUserRoles = AuthLib.Helpers.RoleProviderHelper.GetUserGroups(httpContext.User.Identity.Name); foreach (string role in currentUserRoles) { if (currentAction.ActionGroups != null && currentAction.ActionGroups.Where(o => o.Roles.Select(n => n.Role).Contains(role)).Count() != 0) { result = true; break; } } return result; } } } 



. AuthorizeCore, true , , . , false 401.
, , :

 if (!currentAction.IsExist()) currentAction.Save(); 

. , . , , ( , , , ).

, ( ).

 using System; using System.Linq; using System.Web; using System.Web.Mvc; namespace Ekzo.Web.Security { /// <summary> ///      /// </summary> public class ControlAccesSecurity { /// <summary> ///       /// </summary> /// <param name="controlName"> ,  </param> /// <returns>     -  true,  false</returns> public static bool HasControlAccess(string controlName) { BaseClasses.Employee employee = new BaseClasses.Employee(AuthLib.Helpers.RoleProviderHelper.GetUserId(HttpContext.Current)); Utilization.Authorization.PageControl currentControl = new Utilization.Authorization.PageControl(controlName); foreach (Utilization.Authorization.PageControlsGroup group in currentControl.Groups) if (group.Roles.Where(o => Utilization.Authorization.SystemRole.GetEmployeeRoles(employee.Id).Contains(o.Role)).Count() != 0) return true; return false; } } } namespace Ekzo.Web.Security.SecurityExtensions { /// <summary> ///    ,     /// </summary> public static class StringExtensions { /// <summary> ///       /// </summary> /// <param name="controlName"> ,  </param> /// <returns>     -  ,   </returns> public static MvcHtmlString HasControlAccess(this MvcHtmlString s, string controlName) { BaseClasses.Employee employee = new BaseClasses.Employee(AuthLib.Helpers.RoleProviderHelper.GetUserId(HttpContext.Current)); Utilization.Authorization.PageControl currentControl = new Utilization.Authorization.PageControl(controlName); foreach (Utilization.Authorization.PageControlsGroup group in currentControl.Groups) if (group.Roles.Where(o => Utilization.Authorization.SystemRole.GetEmployeeRoles(employee.Id).Contains(o.Role)).Count() != 0) return s; return MvcHtmlString.Create(""); } /// <summary> ///       /// </summary> /// <param name="controlName"> ,  </param> /// <returns>     -  ,   </returns> public static IHtmlString HasControlAccess(this IHtmlString s, string controlName) { BaseClasses.Employee employee = new BaseClasses.Employee(AuthLib.Helpers.RoleProviderHelper.GetUserId(HttpContext.Current)); Utilization.Authorization.PageControl currentControl = new Utilization.Authorization.PageControl(controlName); foreach (Utilization.Authorization.PageControlsGroup group in currentControl.Groups) if (group.Roles.Where(o => Utilization.Authorization.SystemRole.GetEmployeeRoles(employee.Id).Contains(o.Role)).Count() != 0) return s; return MvcHtmlString.Create(string.Empty); } /// <summary> ///       /// </summary> /// <param name="controlName"> ,  </param> /// <returns>     -  ,   </returns> public static string HasControlAccess(this string s, string controlName) { BaseClasses.Employee employee = new BaseClasses.Employee(AuthLib.Helpers.RoleProviderHelper.GetUserId(HttpContext.Current)); Utilization.Authorization.PageControl currentControl = new Utilization.Authorization.PageControl(controlName); foreach (Utilization.Authorization.PageControlsGroup group in currentControl.Groups) if (group.Roles.Where(o => Utilization.Authorization.SystemRole.GetEmployeeRoles(employee.Id).Contains(o.Role)).Count() != 0) return s; return String.Empty; } } /// <summary> ///   TagBuilder'a     /// </summary> public static class TagBuilderExtensions { /// <summary> ///       /// </summary> /// <param name="controlName"> ,  </param> /// <returns>     -  ,   </returns> public static TagBuilder HasControlAccess(this TagBuilder s, string controlName) { BaseClasses.Employee employee = new BaseClasses.Employee(AuthLib.Helpers.RoleProviderHelper.GetUserId(HttpContext.Current)); Utilization.Authorization.PageControl currentControl = new Utilization.Authorization.PageControl(controlName); foreach (Utilization.Authorization.PageControlsGroup group in currentControl.Groups) if (group.Roles.Where(o => Utilization.Authorization.SystemRole.GetEmployeeRoles(employee.Id).Contains(o.Role)).Count() != 0) return s; return new TagBuilder("b"); } } } 



, .

 [ActionAuthorization(ActionName = "  ")] public ActionResult RequestsInWork() { ViewBag.Title = "  "; return View(); } 



 ... @Html.MainMenu().HasControlAccess(" ") ... 




, .
-, , «» .
-, , --« »-« » . . . .
, . , . « , - -» , .
, , HtmlHelper'.

AJAX .


-

 using System; using System.Collections.Generic; using System.Data.SqlClient; using log4net; namespace Ekzo.Web { public static class Configuration { /// <summary> ///        web.config,      . ///  DataSource /// </summary> public static string ConnectionStringName = "DataSource"; /// <summary> ///        web.config,    ///  /// </summary> public static string StringName = "ConsUser"; /// <summary> ///   /// </summary> public static string ProjectName = "Project Name"; /// <summary> ///   log4net /// </summary> public static ILog s_log = null; /// <summary> ///     /// </summary> private static string[] tables = { "Authorization_ActionGroups", "Authorization_Actions", "Authorization_ActionToGroup", "Authorization_Controls", "Authorization_ControlsGroup", "Authorization_ControlToGroup", "Authorization_RoleToActionGroup", "Authorization_RoleToControlGroup"}; /// <summary> ///        /// </summary> /// <returns>        ,   </returns> public static bool BaseHasTables() { List<string> dbTables = new List<string>(); using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("select TABLE_NAME from information_schema.tables WHERE TABLE_NAME LIKE 'Authorization_%'", conn)) { try { conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) dbTables.Add(reader.GetString(0)); } foreach (string securityTable in tables) if (dbTables.Contains(securityTable)) dbTables.Remove(securityTable); } catch (Exception ex) { Configuration.s_log.Error("[  ] [  ] ", ex); } } } if (dbTables.Count == 0) return false; else return true; } /// <summary> ///       /// </summary> /// <param name="superAdminGroup">   ,      </param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] public static void CreateSecurityTables(string superAdminGroup = null) { List<string> dbTables = new List<string>(); using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_NAME LIKE 'Authorization_%'", conn)) { try { conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) dbTables.Add(reader.GetString(0)); } foreach (string securityTable in tables) if (dbTables.Contains(securityTable)) dbTables.Remove(securityTable); cmd.Parameters.AddWithValue("@database", conn.Database); if (dbTables.Count == 0) foreach (string table in tables) dbTables.Add(table); if (dbTables.Count != 0) foreach (string table in dbTables) { switch (table) { case "Authorization_ControlsGroup": cmd.CommandText = "USE " + conn.Database + @" SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON SET ANSI_PADDING ON CREATE TABLE [dbo].[Authorization_ControlsGroup]( [id] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](500) NOT NULL, CONSTRAINT [PK_Authorization_ControlsGroup] PRIMARY KEY CLUSTERED ([id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] SET ANSI_PADDING OFF SET IDENTITY_INSERT [dbo].[Authorization_ControlsGroup] ON INSERT INTO [dbo].[Authorization_ControlsGroup](id,Name) VALUES(-1,' ') SET IDENTITY_INSERT [dbo].[Authorization_ControlsGroup] OFF"; break; case "Authorization_Actions": cmd.CommandText = "USE " + conn.Database + @" SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON SET ANSI_PADDING ON CREATE TABLE [dbo].[Authorization_Actions]( [id] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](500) NOT NULL, [Active] [bit] NOT NULL, CONSTRAINT [PK_Authorization_Actions] PRIMARY KEY CLUSTERED ([id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] SET ANSI_PADDING OFF ALTER TABLE [dbo].[Authorization_Actions] ADD CONSTRAINT [DF_Authorization_Actions_Active] DEFAULT ((1)) FOR [Active]"; break; case "Authorization_ActionToGroup": cmd.CommandText = "USE " + conn.Database + @" SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON CREATE TABLE [dbo].[Authorization_ActionToGroup]( [id] [int] IDENTITY(1,1) NOT NULL, [ActionID] [int] NOT NULL, [GroupID] [int] NOT NULL, CONSTRAINT [PK_Authorization_ActionToGroup] PRIMARY KEY CLUSTERED ([id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]"; break; case "Authorization_Controls": cmd.CommandText = "USE " + conn.Database + @" SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON SET ANSI_PADDING ON CREATE TABLE [dbo].[Authorization_Controls]( [id] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](500) NOT NULL, CONSTRAINT [PK_Authorize_Controls] PRIMARY KEY CLUSTERED ([id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] SET ANSI_PADDING OFF"; break; case "Authorization_ControlToGroup": cmd.CommandText = "USE " + conn.Database + @" SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON CREATE TABLE [dbo].[Authorization_ControlToGroup]( [id] [int] IDENTITY(1,1) NOT NULL, [ControlID] [int] NOT NULL, [GroupID] [int] NOT NULL, CONSTRAINT [PK_Authorization_ControlToGroup] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]"; break; case "Authorization_RoleToActionGroup": cmd.CommandText = "USE " + conn.Database + @" SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON SET ANSI_PADDING ON CREATE TABLE [dbo].[Authorization_RoleToActionGroup]( [id] [int] IDENTITY(1,1) NOT NULL, [ActionGroup] [int] NOT NULL, [Role] [varchar](500) NOT NULL, CONSTRAINT [PK_Authorization_RoleToActionGroup] PRIMARY KEY CLUSTERED ([id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] SET ANSI_PADDING OFF ALTER TABLE [dbo].[Authorization_RoleToActionGroup] ADD CONSTRAINT [DF_Authorization_RoleToActionGroup_ActionGroup] DEFAULT ((-1)) FOR [ActionGroup]"; break; case "Authorization_RoleToControlGroup": cmd.CommandText = "USE " + conn.Database + @" SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON CREATE TABLE [dbo].[Authorization_RoleToControlGroup]( [id] [int] IDENTITY(1,1) NOT NULL, [RoleID] [int] NOT NULL, [GroupID] [int] NOT NULL, CONSTRAINT [PK_Authorization_RoleToControlGroup] PRIMARY KEY CLUSTERED ([id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]"; break; case "Authorization_ActionGroups": cmd.CommandText = "USE " + conn.Database + @" SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON SET ANSI_PADDING ON CREATE TABLE [dbo].[Authorization_ActionGroups]( [id] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](500) NOT NULL, [active] [bit] NOT NULL, CONSTRAINT [PK_Authorization_ActionGroups] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] SET ANSI_PADDING OFF ALTER TABLE [dbo].[Authorization_ActionGroups] ADD CONSTRAINT [DF_Authorization_ActionGroups_active] DEFAULT ((1)) FOR [active] SET IDENTITY_INSERT [dbo].[Authorization_ActionGroups] ON INSERT INTO [dbo].[Authorization_ActionGroups](id,Name) VALUES(0,' ') SET IDENTITY_INSERT [dbo].[Authorization_ActionGroups] OFF"; break; } cmd.ExecuteNonQuery(); } if (!string.IsNullOrEmpty(superAdminGroup) && Web.Security.Utilization.Authorization.SystemRole.IntranetRoleID(superAdminGroup) != null) { cmd.CommandText = @"INSERT INTO Authorization_RoleToActionGroup(ActionGroup,Role) VALUES(0,@group) INSERT INTO Authorization_RoleToControlGroup(RoleID,GroupID) VALUES(@role,-1)"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@group", superAdminGroup); cmd.Parameters.AddWithValue("@role", Web.Security.Utilization.Authorization.SystemRole.IntranetRoleID(superAdminGroup)); cmd.ExecuteNonQuery(); } } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [  ] ", ex); } } } } public static void RecreateTables(string superAdminGroup = null) { string command = "DROP TABLE {0}"; using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("", conn)) { try { conn.Open(); foreach (string table in tables) { cmd.CommandText = string.Format(command, table); cmd.ExecuteNonQuery(); } } catch (Exception ex) { if (Configuration.s_log != null) Configuration.s_log.Error("[  ] [   ] ", ex); } } } CreateSecurityTables(superAdminGroup); } } } 



, .

GitHub

Instead of conclusion

Employee , , .
, // . , .
. , GitHub' .

Source: https://habr.com/ru/post/191218/


All Articles