PermissionManager.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. using Model;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection.Emit;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace Permission
  11. {
  12. public static class PermissionManager
  13. {
  14. public const PermissionLevel DefaultPermissionLevel = PermissionLevel.无权限;
  15. public static User CurrentUser { get => AppSession.CurrentUser; private set => AppSession.CurrentUser = value; }//当前的权限等级
  16. public static event Action<PermissionLevel> OnPermissionLevelChanged; // 定义一个事件,当权限级别改变时触发
  17. public static void SignIn(User user)
  18. {
  19. CurrentUser = user;
  20. OnPermissionLevelChanged?.Invoke(user.PermissionLevel);
  21. }
  22. public static void SignOut()
  23. {
  24. CurrentUser.PermissionLevel = DefaultPermissionLevel;
  25. CurrentUser.Username = "";
  26. // 触发事件:通知所有订阅者权限已变更
  27. OnPermissionLevelChanged?.Invoke(DefaultPermissionLevel);
  28. }
  29. public static void LogOffAndSignInOperator()
  30. {
  31. //SignOut();
  32. if (CurrentUser.PermissionLevel != PermissionLevel.操作工 && CurrentUser.PermissionLevel != PermissionLevel.开发者)
  33. {
  34. User user = new User(CurrentUser.Username + "_自动注销", "", PermissionLevel.操作工);
  35. SignIn(user);
  36. }
  37. }
  38. public static void ApplyPermissions(Form form)
  39. {
  40. foreach (Control control in GetAllControls(form))
  41. {
  42. // 控件本身实现了接口
  43. if (control is IPermissionControl pc)
  44. {
  45. pc.CurrentPermissionLevel = CurrentUser.PermissionLevel;
  46. }
  47. else
  48. {
  49. var hasPermission = CurrentUser.PermissionLevel >= control.GetPermissionLevel();
  50. control.Enabled = hasPermission;
  51. //control.Visible = hasPermission;
  52. //if (control is Control c && !(c is Form))
  53. // c.Enabled = hasPermission;
  54. }
  55. }
  56. }
  57. private static IEnumerable<Control> GetAllControls(Control parent)
  58. {
  59. var controls = new List<Control>();
  60. foreach (Control ctrl in parent.Controls)
  61. {
  62. controls.Add(ctrl);
  63. if(!(ctrl is IPermissionControl pc) && ctrl.HasChildren)
  64. controls.AddRange(GetAllControls(ctrl)); // 递归
  65. }
  66. return controls;
  67. }
  68. private static readonly object _lock = new object();
  69. private static bool _initialized = false;
  70. private static readonly Dictionary<PermissionLevel, PermissionProfile> roleProfiles = new Dictionary<PermissionLevel, PermissionProfile>();
  71. private static readonly string[] _roleFileNames = { "operator", "engineer", "technician", "admin" };
  72. private const string roleDir = "Role";
  73. /// <summary>
  74. /// 初始化权限管理器(建议在程序启动时调用一次)
  75. /// </summary>
  76. public static void Initialize()
  77. {
  78. if (_initialized) return;
  79. lock (_lock)
  80. {
  81. if (_initialized) return;
  82. for (int i = 0; i < _roleFileNames.Length; i++)
  83. {
  84. string filePath = GetPermissionFilePath(_roleFileNames[i]);
  85. if (File.Exists(filePath))
  86. {
  87. try
  88. {
  89. string json = File.ReadAllText(filePath);
  90. var profile = JsonHelper.DeserializeFromString<PermissionProfile>(json) ?? new PermissionProfile();
  91. roleProfiles[(PermissionLevel)i] = profile;
  92. }
  93. catch (Exception)
  94. {
  95. roleProfiles[(PermissionLevel)i] = new PermissionProfile(); // 损坏则新建
  96. }
  97. }
  98. else
  99. {
  100. roleProfiles[(PermissionLevel)i] = new PermissionProfile(); // 文件不存在,空权限
  101. }
  102. }
  103. _initialized = true;
  104. }
  105. }
  106. public static void ResetPermissions()
  107. {
  108. lock (_lock)
  109. {
  110. roleProfiles.Clear();
  111. _initialized = false;
  112. Initialize();
  113. }
  114. }
  115. private static string GetPermissionFilePath(string roleName)
  116. {
  117. return Path.Combine(Application.StartupPath, roleDir, $"permissions_{roleName}.json");
  118. }
  119. /// <summary>
  120. /// 获取指定角色被授权的控件列表
  121. /// </summary>
  122. /// <param name="role">0=操作工, 1=工程师, 2=技术员, 3=管理员</param>
  123. /// <returns>授权控件列表(只读副本)</returns>
  124. public static IReadOnlyList<AuthorizedControl> GetAuthorizedControlsForRole(PermissionLevel roleLevel)
  125. {
  126. if (!_initialized)
  127. Initialize(); // 懒加载(也可强制要求提前初始化)
  128. lock (_lock)
  129. {
  130. if (roleProfiles.TryGetValue(roleLevel, out var profile))
  131. {
  132. // 返回副本,防止外部修改缓存
  133. return profile.AuthorizedControls.ToList().AsReadOnly();
  134. }
  135. return new List<AuthorizedControl>();
  136. }
  137. }
  138. public static PermissionProfile GetRoleProfile(PermissionLevel roleLevel)
  139. {
  140. if (!_initialized)
  141. Initialize();
  142. lock (_lock)
  143. {
  144. if (roleProfiles.TryGetValue(roleLevel, out var profile))
  145. {
  146. return profile;
  147. }
  148. return new PermissionProfile();
  149. }
  150. }
  151. public static void SaveRoleProfile(PermissionLevel roleLevel, PermissionProfile profile)
  152. {
  153. roleProfiles[roleLevel] = profile;
  154. string filePath = GetPermissionFilePath(_roleFileNames[(int)roleLevel]);
  155. JsonHelper.SerializeObject(filePath, profile);
  156. }
  157. /// <summary>
  158. /// (可选)检查某个控件对当前角色是否授权
  159. /// </summary>
  160. public static bool IsControlAuthorized(PermissionLevel roleLevel, string formType, string controlName)
  161. {
  162. var authorized = GetAuthorizedControlsForRole(roleLevel);
  163. return authorized.Any(c => c.FormType == formType && c.ControlName == controlName);
  164. }
  165. }
  166. }