| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185 |
- using Model;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection.Emit;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace Permission
- {
- public static class PermissionManager
- {
- public const PermissionLevel DefaultPermissionLevel = PermissionLevel.无权限;
- public static User CurrentUser { get => AppSession.CurrentUser; private set => AppSession.CurrentUser = value; }//当前的权限等级
- public static event Action<PermissionLevel> OnPermissionLevelChanged; // 定义一个事件,当权限级别改变时触发
- public static void SignIn(User user)
- {
- CurrentUser = user;
- OnPermissionLevelChanged?.Invoke(user.PermissionLevel);
- }
- public static void SignOut()
- {
- CurrentUser.PermissionLevel = DefaultPermissionLevel;
- CurrentUser.Username = "";
-
- // 触发事件:通知所有订阅者权限已变更
- OnPermissionLevelChanged?.Invoke(DefaultPermissionLevel);
- }
- public static void LogOffAndSignInOperator()
- {
- //SignOut();
- if (CurrentUser.PermissionLevel != PermissionLevel.操作工 && CurrentUser.PermissionLevel != PermissionLevel.开发者)
- {
- User user = new User(CurrentUser.Username + "_自动注销", "", PermissionLevel.操作工);
- SignIn(user);
- }
- }
- public static void ApplyPermissions(Form form)
- {
- foreach (Control control in GetAllControls(form))
- {
- // 控件本身实现了接口
- if (control is IPermissionControl pc)
- {
- pc.CurrentPermissionLevel = CurrentUser.PermissionLevel;
- }
- else
- {
- var hasPermission = CurrentUser.PermissionLevel >= control.GetPermissionLevel();
- control.Enabled = hasPermission;
- //control.Visible = hasPermission;
- //if (control is Control c && !(c is Form))
- // c.Enabled = hasPermission;
- }
- }
- }
- private static IEnumerable<Control> GetAllControls(Control parent)
- {
- var controls = new List<Control>();
- foreach (Control ctrl in parent.Controls)
- {
- controls.Add(ctrl);
- if(!(ctrl is IPermissionControl pc) && ctrl.HasChildren)
- controls.AddRange(GetAllControls(ctrl)); // 递归
- }
- return controls;
- }
- private static readonly object _lock = new object();
- private static bool _initialized = false;
- private static readonly Dictionary<PermissionLevel, PermissionProfile> roleProfiles = new Dictionary<PermissionLevel, PermissionProfile>();
- private static readonly string[] _roleFileNames = { "operator", "engineer", "technician", "admin" };
- private const string roleDir = "Role";
- /// <summary>
- /// 初始化权限管理器(建议在程序启动时调用一次)
- /// </summary>
- public static void Initialize()
- {
- if (_initialized) return;
- lock (_lock)
- {
- if (_initialized) return;
- for (int i = 0; i < _roleFileNames.Length; i++)
- {
- string filePath = GetPermissionFilePath(_roleFileNames[i]);
- if (File.Exists(filePath))
- {
- try
- {
- string json = File.ReadAllText(filePath);
- var profile = JsonHelper.DeserializeFromString<PermissionProfile>(json) ?? new PermissionProfile();
- roleProfiles[(PermissionLevel)i] = profile;
- }
- catch (Exception)
- {
- roleProfiles[(PermissionLevel)i] = new PermissionProfile(); // 损坏则新建
- }
- }
- else
- {
- roleProfiles[(PermissionLevel)i] = new PermissionProfile(); // 文件不存在,空权限
- }
- }
- _initialized = true;
- }
- }
- public static void ResetPermissions()
- {
- lock (_lock)
- {
- roleProfiles.Clear();
- _initialized = false;
- Initialize();
- }
- }
- private static string GetPermissionFilePath(string roleName)
- {
- return Path.Combine(Application.StartupPath, roleDir, $"permissions_{roleName}.json");
- }
- /// <summary>
- /// 获取指定角色被授权的控件列表
- /// </summary>
- /// <param name="role">0=操作工, 1=工程师, 2=技术员, 3=管理员</param>
- /// <returns>授权控件列表(只读副本)</returns>
- public static IReadOnlyList<AuthorizedControl> GetAuthorizedControlsForRole(PermissionLevel roleLevel)
- {
- if (!_initialized)
- Initialize(); // 懒加载(也可强制要求提前初始化)
- lock (_lock)
- {
- if (roleProfiles.TryGetValue(roleLevel, out var profile))
- {
- // 返回副本,防止外部修改缓存
- return profile.AuthorizedControls.ToList().AsReadOnly();
- }
- return new List<AuthorizedControl>();
- }
- }
- public static PermissionProfile GetRoleProfile(PermissionLevel roleLevel)
- {
- if (!_initialized)
- Initialize();
- lock (_lock)
- {
- if (roleProfiles.TryGetValue(roleLevel, out var profile))
- {
- return profile;
- }
- return new PermissionProfile();
- }
- }
- public static void SaveRoleProfile(PermissionLevel roleLevel, PermissionProfile profile)
- {
- roleProfiles[roleLevel] = profile;
- string filePath = GetPermissionFilePath(_roleFileNames[(int)roleLevel]);
- JsonHelper.SerializeObject(filePath, profile);
- }
- /// <summary>
- /// (可选)检查某个控件对当前角色是否授权
- /// </summary>
- public static bool IsControlAuthorized(PermissionLevel roleLevel, string formType, string controlName)
- {
- var authorized = GetAuthorizedControlsForRole(roleLevel);
- return authorized.Any(c => c.FormType == formType && c.ControlName == controlName);
- }
- }
- }
|