我正在为一家律师事务所构建C#应用程序。在每个目录Form
中Control
,只有某些用户可以访问某些目录(对于其他用户-这些目录Control
将被禁用)。
我是这样构建的:有一个名为的类AuthorizedForm
,它继承自Form
。此类具有一种称为的方法SetAuthorization
,该方法可启用Control
用户可能访问的所有,并禁用其余的。应用程序中的每种形式都继承自AuthorizedForm
。
当用户登录时,该SetAuthorization
方法将被调用并接收登录用户的ID和规则列表作为参数。每个规则都包含一个Control
和可以访问该列表的用户列表Control
。
该列表实际上分为两个列表:用户组(例如律师,律师助理等)和个人用户。因此,例如,如果我将“管理员”组的ID和“律师”组的ID放在第一个列表中,而其中一个秘书的ID放在了第二个列表中-则将Control
定义Enabled
为所有管理员和律师,以及该秘书,而其他办公室员工的Control
定义为Disabled
。
该列表被调用AuthorizationList
,并且实际上是一个从List
type的类继承的类,该类Tuple
接收a Control
,aGroupList
和a UserList
(最后两个不过是List
type的a byte
)。
的定义 GroupList
和 UserList
:
public class GroupList : List<byte> { }
public class UserList : List<byte> { }
AuthorizedList
类的代码(在此答案的帮助下构建):
public class AuthorizationList : List<Tuple<Control, GroupList, UserList>>
{
public void Add(Control control, GroupList groups, UserList users)
{
Add(new Tuple<Control, GroupList, UserList>(control, groups, users));
}
}
本 AuthorizedForm
类:
public class AuthorizedForm : Form
{
public void SetAuthorization(User loggedInUser, AuthorizationList authorizationList)
{
foreach (var rule in authorizationList)
{
bool isAuthorized = false;
foreach (byte group in rule.Item2)
{
if (group == loggedInUser.Group)
{
isAuthorized = true;
break;
}
}
if (!isAuthorized)
{
foreach (byte user in rule.Item3)
{
if (user == loggedInUser.Id)
{
isAuthorized = true;
break;
}
}
}
if(!isAuthorized)
{
rule.Item1.Enabled = false;
}
}
}
}
该呼吁 SetAuthorization
从登录功能:
if (user.isLoggedIn)
{
SetAuthorization(user, new AuthorizationList()
{
/*
CONTROL | GROUPS IDS LIST | USER IDS LIST
*/
{ textBox1, new GroupList() { 1, 2, 3 }, new UserList() { 4 } },
{ textBox2, new GroupList() { 1, 2 }, new UserList() { 4 } },
{ button1, new GroupList() { 1 }, new UserList() { 4, 3 } },
});
}
现在,我也希望AuthorizationList
成为Tuple
接收aControl
和GroupList
only或aControl
和UserList
only的类型,因此我可以为用户组设置权限,也可以为单个用户设置权限。
我想不出一种方法,而无需显着更改我编写的代码。有没有办法以一种相对简单而优雅的方式做到这一点?如果不是,您将如何建议呢?
如何使用不是Tuple的对象来保存授权,它比Tuple <>更优雅:
public class GroupList : List<byte> { }
public class UserList : List<byte> { }
public class Authorization
{
public Control Control { get; set; }
public GroupList Groups { get; set; }
public UserList Users { get; set; }
}
public class AuthorizationList : List<Authorization>
{
public void Add(Control control, GroupList groupList, UserList userList)
{
Add(new Authorization
{
Control = control,
Groups = groupList,
Users = userList
});
}
public void Add(Control control, GroupList groupList)
{
Add(control, groupList, null);
}
public void Add(Control control, UserList userList)
{
Add(control, null, userList);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句