返回
基于SqlSugar框架的字段访问权限管理
后端
2023-10-16 19:10:55
结合Winform控件实现字段的权限控制
字段的权限控制,就是控制对应角色人员对某个业务对象的一些敏感字段的可访问性:包括可见、可编辑性等处理。
字段权限控制应用场景很多,比如:
- 部门负责人只能看到本部门员工的工资信息,而不能看到其他部门员工的工资信息;
- 普通员工只能编辑自己的联系方式,而不能编辑其他员工的联系方式;
- 管理员可以查看和编辑所有员工的信息;
基于SqlSugar的开发框架,我们通过自定义特性配合Winform控件实现字段的权限控制。
public class PermissionAttribute : Attribute
{
public string Role { get; set; }
public bool Visible { get; set; }
public bool Editable { get; set; }
}
public class Employee
{
[Permission(Role = "Manager", Visible = true, Editable = true)]
public int Id { get; set; }
[Permission(Role = "Manager", Visible = true, Editable = false)]
public string Name { get; set; }
[Permission(Role = "Employee", Visible = true, Editable = true)]
public string Contact { get; set; }
[Permission(Role = "Manager", Visible = true, Editable = true)]
public decimal Salary { get; set; }
}
在上述代码中,我们定义了一个PermissionAttribute
特性,用于标注需要权限控制的字段。特性中包含了Role
、Visible
和Editable
三个属性,分别表示该字段的角色、可见性和可编辑性。
public class EmployeeForm : Form
{
private Employee _employee;
public EmployeeForm(Employee employee)
{
_employee = employee;
// 获取当前登录用户的角色
string role = GetCurrentUserRole();
// 遍历Employee类的属性
foreach (PropertyInfo property in typeof(Employee).GetProperties())
{
// 获取属性上的PermissionAttribute特性
PermissionAttribute permissionAttribute = property.GetCustomAttribute<PermissionAttribute>();
// 判断当前登录用户是否有权限查看该字段
if (permissionAttribute != null && permissionAttribute.Role != role)
{
continue;
}
// 创建对应的Winform控件
Control control = CreateControl(property);
// 设置控件的可见性和可编辑性
control.Visible = permissionAttribute.Visible;
control.Enabled = permissionAttribute.Editable;
// 将控件添加到窗体上
this.Controls.Add(control);
}
}
private Control CreateControl(PropertyInfo property)
{
// 根据属性的类型创建相应的控件
switch (property.PropertyType.Name)
{
case "String":
return new TextBox();
case "Int32":
return new NumericUpDown();
case "Decimal":
return new NumericUpDown();
default:
return new TextBox();
}
}
private string GetCurrentUserRole()
{
// 模拟从数据库中获取当前登录用户的角色
return "Employee";
}
}
在上述代码中,我们定义了一个EmployeeForm
类,用于显示员工信息。在EmployeeForm
类的构造函数中,我们遍历Employee
类的属性,并根据属性上的PermissionAttribute
特性来判断当前登录用户是否有权限查看该字段。如果有权限,则创建对应的Winform控件并将其添加到窗体上。
这样,我们就可以实现字段的权限控制,不同角色的用户只能看到和编辑自己有权限的字段。