革博士V2程序
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1 рік тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. using MaiMuControl.Device.IOCardDev;
  2. using MaiMuControl.SysStatusMgr.UserMgr;
  3. using MySql.Data.MySqlClient;
  4. using SqlSugar;
  5. using System;
  6. using System.CodeDom;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Data;
  10. using System.Data.SqlClient;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Reflection;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using System.Windows.Forms;
  18. using ToolKits.Ini;
  19. namespace GeBoShi.UI.User
  20. {
  21. #region 基础表
  22. /// <summary>
  23. /// 基础表格
  24. /// </summary>
  25. public class BaseTable
  26. {
  27. [SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
  28. public int Id { get; set; }
  29. public string ModifyUserCode { get; set; }
  30. [SugarColumn(UpdateServerTime = true, InsertServerTime = true)]
  31. public DateTime ModifyTime { get; set; }
  32. [SugarColumn(IsOnlyIgnoreUpdate = true)]
  33. public string CreateUserCode { get; set; }
  34. //insert时使用DB时间填充,不更新
  35. [SugarColumn(InsertServerTime = true, IsOnlyIgnoreUpdate = true)]
  36. public DateTime CreateTime { get; set; } = DateTime.Now;//程序中需要用
  37. }
  38. #endregion
  39. #region 权限集,权限,对应关系
  40. [SugarIndex("index_{table}_code", nameof(Right.Code), OrderByType.Asc, isUnique: true)]
  41. public class Right : BaseTable
  42. {
  43. public Right() { }
  44. public Right(string code, string name, string groupName = "默认")
  45. {
  46. Code = code;
  47. Name = name;
  48. GroupName = groupName;
  49. CreateUserCode = "admin";
  50. ModifyUserCode = "admin";
  51. }
  52. public bool check { get; set; }
  53. public string GroupName { get; set; }//分组名
  54. [SugarColumn(Length = 16)]
  55. public string Code { get; set; }
  56. public string Name { get; set; }
  57. //用于根据权限查所有角色时用
  58. //[Navigate(typeof(RoleRightMap), nameof(RoleRightMap.RightId), nameof(RoleRightMap.RoleId))]//注意顺序
  59. //public List<Role> RoleList { get; set; }
  60. }
  61. public class RoleRightMap : BaseTable
  62. {
  63. public int RoleId { get; set; }
  64. public int RightId { get; set; }
  65. /// <summary>
  66. /// 0-无权 1-查看 2-修改
  67. /// </summary>
  68. public int Level { get; set; }
  69. }
  70. [SugarIndex("index_{table}_code", nameof(Role.Code), OrderByType.Asc, isUnique: true)]
  71. public class Role : BaseTable
  72. {
  73. [SugarColumn(Length = 16)]
  74. public string Code { get; set; }
  75. public string Name { get; set; }
  76. [Navigate(typeof(RoleRightMap), nameof(RoleRightMap.RoleId), nameof(RoleRightMap.RightId))]//注意顺序
  77. public List<Right> RightList { get; set; }
  78. }
  79. #endregion
  80. #region 用户表
  81. [SugarIndex("index_{table}_code", nameof(User.Code), OrderByType.Asc, isUnique: true)]
  82. public class User : BaseTable
  83. {
  84. [SugarColumn(Length = 16)]
  85. public string Code { get; set; }
  86. public string Name { get; set; }
  87. [SugarColumn(IsNullable = true)]
  88. public string Password { get; set; }
  89. public int RoleId { get; set; }
  90. [Navigate(NavigateType.ManyToOne, nameof(RoleId))]
  91. public Role RoleInfo { get; set; }
  92. public bool State { get; set; } = true;
  93. /// <summary>
  94. /// 是否自动登出
  95. /// </summary>
  96. public bool AutoLogOut { get; set; } = false;
  97. /// <summary>
  98. /// 自动登出时间 5分钟
  99. /// </summary>
  100. public int LogOutTimeMinutes { get; set; } = 5;
  101. [SugarColumn(IsNullable = true)]
  102. public string Note { get; set; }
  103. }
  104. #endregion
  105. #region 初始化用户数据库
  106. public class ConteolUserDB
  107. {
  108. public static string GetSqlDBCode()
  109. {
  110. string path = Path.Combine(Directory.GetCurrentDirectory(), "SystemDefault.ini");
  111. if (File.Exists(path))
  112. {
  113. string sValue;
  114. IniHelper iniHelper = new IniHelper(path);
  115. iniHelper.ReadString("SystemDefault", "MySqlCode", out sValue);
  116. return sValue.Replace("\0", "");
  117. }
  118. else
  119. {
  120. // write default value
  121. IniHelper iniHelper = new IniHelper(path);
  122. iniHelper.WriteString("SystemDefault", "MySqlCode", "Maimu888");
  123. return "Maimu888";
  124. }
  125. }
  126. //server=localhost;Database=ProductionDB;Uid=root;Pwd=123456; AllowLoadLocalInfile=true
  127. /// <summary>
  128. /// 用户数据库,链接地址
  129. /// </summary>
  130. public static string ConnectionString { get; private set ; }
  131. /// <summary>
  132. /// 设置需要联机的数据库IP
  133. /// </summary>
  134. /// <param name="addrIP"></param>
  135. public static void SetServerIP(string addrIP)
  136. {
  137. //server = localhost; Database = ProductionDB; Uid = root; Pwd = 123456; AllowLoadLocalInfile = true
  138. ConnectionString = "server = " + addrIP + "; Database = UserDB; Uid = root; Pwd = " + GetSqlDBCode() + "; AllowLoadLocalInfile = true;";
  139. //ConnectionString = "server=127.0.0.1;port=3306;database=UserDB;uid=testUser;pwd=123456;";
  140. //ConnectionString = "server = localhost; Database = UserDB; Uid = root; Pwd = 123456; AllowLoadLocalInfile = true";
  141. }
  142. /// <summary>
  143. /// 初始化用户数据表
  144. /// </summary>
  145. /// <param name="RightArray"></param>
  146. /// <param name="dropTable"></param>
  147. public static void initDB( bool dropTable = false)
  148. {
  149. ConnectionConfig connectionConfig = new ConnectionConfig()
  150. {
  151. ConnectionString = ConnectionString,
  152. DbType = SqlSugar.DbType.MySql,
  153. IsAutoCloseConnection = true
  154. };
  155. //创建数据库对象
  156. using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
  157. {
  158. db.Aop.OnLogExecuting = (sql, pars) =>
  159. {
  160. Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响
  161. };
  162. //create db
  163. db.DbMaintenance.CreateDatabase();
  164. //db.DbMaintenance.TruncateTable<Order>();//删除记录
  165. //===建表
  166. if (dropTable && db.DbMaintenance.IsAnyTable("Right", false)) db.DbMaintenance.DropTable("Right");
  167. if (dropTable && db.DbMaintenance.IsAnyTable("Role", false)) db.DbMaintenance.DropTable("Role");
  168. if (dropTable && db.DbMaintenance.IsAnyTable("RoleRightMap", false)) db.DbMaintenance.DropTable("RoleRightMap");
  169. if (dropTable && db.DbMaintenance.IsAnyTable("User", false)) db.DbMaintenance.DropTable("User");
  170. //===添加与更新表
  171. db.CodeFirst.InitTables<Right>();
  172. db.CodeFirst.InitTables<Role>();
  173. db.CodeFirst.InitTables<RoleRightMap>();
  174. db.CodeFirst.InitTables<User>();
  175. //更新新列数据
  176. //db.Ado.ExecuteCommand("update Step set Tag=0 where Tag is null");
  177. //try
  178. //{
  179. // db.Ado.ExecuteCommand("ALTER TABLE Product DROP COLUMN HoleCountId");
  180. //}
  181. //catch { }
  182. //try {
  183. // db.Ado.ExecuteCommand("ALTER TABLE Product DROP COLUMN HoleCount");
  184. //}
  185. //catch { }
  186. //===初始数据 注意*********会清空这些表数据
  187. //User
  188. db.DbMaintenance.TruncateTable<User>();
  189. db.DbMaintenance.TruncateTable<Role>();
  190. if (db.Queryable<User>().Count() < 1)
  191. {
  192. //db.Insertable(new Models.User() { Code = "admin", Name = "管理员", RoleId = id }).ExecuteCommand();
  193. db.InsertNav(new User()
  194. {
  195. Code = "admin",
  196. Name = "管理员",
  197. //Password = GetMD5(""),
  198. Password = "",
  199. RoleInfo = new Role() { Code = "admin", Name = "管理员", ModifyUserCode = "admin", CreateUserCode = "admin" },//多表添加
  200. CreateUserCode = "admin",
  201. ModifyUserCode = "admin",
  202. }).Include(x => x.RoleInfo)
  203. .ExecuteCommand();
  204. }
  205. //===权限
  206. db.DbMaintenance.TruncateTable<RoleRightMap>();
  207. db.DbMaintenance.TruncateTable<Right>();
  208. if (db.Queryable<Right>().Where(m => m.Code == "Step").Count() < 1) db.Insertable(new Right("Step", "流程管理")).ExecuteCommand();
  209. if (db.Queryable<Right>().Where(m => m.Code == "Product").Count() < 1) db.Insertable(new Right("Product", "产品管理")).ExecuteCommand();
  210. if (db.Queryable<Right>().Where(m => m.Code == "Order").Count() < 1) db.Insertable(new Right("Order", "报表查询")).ExecuteCommand();
  211. if (db.Queryable<Right>().Where(m => m.Code == "Statistics").Count() < 1) db.Insertable(new Right("Statistics", "统计分析")).ExecuteCommand();
  212. if (db.Queryable<Right>().Where(m => m.Code == "Role").Count() < 1) db.Insertable(new Right("Role", "角色管理")).ExecuteCommand();
  213. if (db.Queryable<Right>().Where(m => m.Code == "User").Count() < 1) db.Insertable(new Right("User", "用户管理")).ExecuteCommand();
  214. //if (db.Queryable<Models.Right>().Where(m => m.Code == "Right").Count() < 1) db.Insertable(new Models.Right("Right", "权限管理")).ExecuteCommand();
  215. if (db.Queryable<Right>().Where(m => m.Code == "Calibration").Count() < 1) db.Insertable(new Right("Calibration", "标定设置")).ExecuteCommand();
  216. if (db.Queryable<Right>().Where(m => m.Code == "SysSetting").Count() < 1) db.Insertable(new Right("SysSetting", "系统设置")).ExecuteCommand();
  217. if (db.Queryable<Right>().Where(m => m.Code == "ParamsSetting").Count() < 1) db.Insertable(new Right("ParamsSetting", "参数设置")).ExecuteCommand();
  218. if (db.Queryable<Right>().Where(m => m.Code == "Manual").Count() < 1) db.Insertable(new Right("Manual", "手动操作")).ExecuteCommand();
  219. if (db.Queryable<Right>().Where(m => m.Code == "Debug").Count() < 1) db.Insertable(new Right("Debug", "设备调试")).ExecuteCommand();
  220. if (db.Queryable<Right>().Where(m => m.Code == "Operation1").Count() < 1) db.Insertable(new Right("Operation1", "特色操作1")).ExecuteCommand();
  221. if (db.Queryable<Right>().Where(m => m.Code == "Operation2").Count() < 1) db.Insertable(new Right("Operation2", "特色操作2")).ExecuteCommand();
  222. if (db.Queryable<Right>().Where(m => m.Code == "Operation3").Count() < 1) db.Insertable(new Right("Operation3", "特色操作3")).ExecuteCommand();
  223. //==触发器
  224. //string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  225. //string sqlPath = rootPath + "\\ConfigFiles\\SqlPath\\";
  226. //if (Directory.Exists(sqlPath))
  227. //{
  228. // int count;
  229. // string triggerName = "trigger_order_update";
  230. // if (File.Exists(sqlPath + triggerName + ".sql"))
  231. // {
  232. // count = db.Ado.GetInt($"SELECT count(*) FROM information_schema.TRIGGERS where TRIGGER_NAME = '{triggerName}'");
  233. // if (count > 0)
  234. // db.Ado.ExecuteCommand($"drop trigger {triggerName}");
  235. // db.Ado.ExecuteCommand(File.ReadAllText(sqlPath + triggerName + ".sql"));
  236. // }
  237. //}
  238. //==清理垃圾数据
  239. //db.Ado.ExecuteCommand($"delete from `Order` where ProductId not in (select id from product)");
  240. }
  241. }
  242. /// <summary>
  243. /// 备份DB (还原:mysql -uroot -p < d:\dbName.sql)
  244. /// </summary>
  245. /// <param name="result"></param>
  246. public static void BackupDataBase(string outFilePath)
  247. {
  248. using (var conn = new MySqlConnection(ConnectionString))
  249. {
  250. using (var cmd = new MySqlCommand())
  251. {
  252. using (MySqlBackup mb = new MySqlBackup(cmd))
  253. {
  254. // 设置数据库连接
  255. cmd.Connection = conn;
  256. cmd.Connection.Open();
  257. // 导出数据库到文件
  258. mb.ExportToFile(outFilePath);
  259. conn.Close();
  260. }
  261. }
  262. }
  263. }
  264. private static string GetMD5(string str)
  265. {
  266. byte[] data = Encoding.UTF8.GetBytes(str);
  267. data = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
  268. string ret = "";
  269. for (int i = 0; i < data.Length; i++)
  270. {
  271. ret += data[i].ToString("x1").PadLeft(2, '0');//ToString("x1"):转换为16进制
  272. }
  273. return ret.ToUpper();
  274. }
  275. //private static string Jiami(string code)
  276. //{
  277. // DataProtectionScope scope = DataProtectionScope.CurrentUser;
  278. // byte[] encrypted = ProtectedData.Protect(original, null, scope);
  279. //}
  280. }
  281. #endregion
  282. #region 数据库操作
  283. public class UserRepository<T> : SimpleClient<T> where T : class, new()
  284. {
  285. public UserRepository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
  286. {
  287. if (context == null)
  288. {
  289. base.Context = new SqlSugarClient(new ConnectionConfig()
  290. {
  291. DbType = SqlSugar.DbType.MySql,
  292. //InitKeyType = InitKeyType.Attribute,
  293. IsAutoCloseConnection = true,
  294. ConnectionString = ConteolUserDB.ConnectionString
  295. });
  296. base.Context.Aop.OnLogExecuting = (s, p) =>
  297. {
  298. Console.WriteLine(s);
  299. };
  300. }
  301. }
  302. /// <summary>
  303. /// 扩展方法,自带方法不能满足的时候可以添加新方法
  304. /// </summary>
  305. /// <returns></returns>
  306. public List<T> CommQuery(string json)
  307. {
  308. T t = Context.Utilities.DeserializeObject<T>(json);
  309. var list = base.Context.Queryable<T>().WhereClass(t).ToList();
  310. return list;
  311. }
  312. }
  313. public class RoleService : UserRepository<Role>
  314. {
  315. public List<Role> GetListNav()
  316. {
  317. return base.AsSugarClient().Queryable<Role>()
  318. .Includes(m => m.RightList)
  319. .Where(m => m.Code != "admin")
  320. .ToList();
  321. }
  322. public bool DelNav(Role model)
  323. {
  324. return base.AsSugarClient().DeleteNav<Role>(model)
  325. .Include(a => a.RightList)
  326. .ExecuteCommand();
  327. }
  328. public bool UpdateNav(Role model)
  329. {
  330. return base.AsSugarClient().UpdateNav(model)
  331. .Include(a => a.RightList)//.ThenInclude(z1 => z1.RoomList) //插入2层 Root->ShoolA->RoomList
  332. .ExecuteCommand();
  333. }
  334. //获取所有子
  335. public List<Right> GetRightItems()
  336. {
  337. var db = base.Change<Right>();//切换仓仓(新功能)
  338. var list = db.GetList();
  339. return list;
  340. }
  341. //public List<Right> GetRightItems1()
  342. //{
  343. // var db = base.Change<Right>();//切换仓仓(新功能)
  344. // base.AsSugarClient().ThenMapper(list, map =>
  345. // {
  346. // });
  347. //}
  348. //分页
  349. //public List<Models.Role> GetOrderPage(Expression<Func<Models.Role, bool>> where, int pagesize, int pageindex)
  350. //{
  351. // return base.GetPageList(where, new SqlSugar.PageModel() { PageIndex = pageindex, PageSize = pagesize }); //使用自已的仓储方法
  352. //}
  353. //调用仓储扩展方法
  354. public List<Role> GetOrderByJson(string Json)
  355. {
  356. return base.CommQuery(Json);
  357. }
  358. }
  359. public class UserService : UserRepository<User>
  360. {
  361. public List<User> GetListNav()
  362. {
  363. return base.AsSugarClient().Queryable<User>()
  364. .Includes(m => m.RoleInfo, info => info.RightList)
  365. .ToList();
  366. }
  367. public User GetModel(string userCode, string userPw)
  368. {
  369. //return base.GetFirst(t=>t.Code.Equals(userCode) && SqlFunc.IsNull(t.Password,"") .Equals(userPw));
  370. return base.AsSugarClient().Queryable<User>()
  371. .Includes(m => m.RoleInfo, info => info.RightList)
  372. .Where(t => t.Code.Equals(userCode) && SqlFunc.IsNull(t.Password, "").Equals(userPw))
  373. .First();
  374. }
  375. public bool ModifyPw(int userId, string newPW)
  376. {
  377. //更新一个字段
  378. var result = base.AsSugarClient().Updateable<User>().SetColumns("Password", newPW).Where("id=" + userId).ExecuteCommand();
  379. //更新多个字段
  380. //var result = base.AsSugarClient().Updateable<User>().SetColumns(p => new User { Password = newPW, Name = Name }).Where("id=" + userId).ExecuteCommand();
  381. return result > 0;
  382. }
  383. //获取所有子
  384. public List<Role> GetRoleItems()
  385. {
  386. var db = base.Change<Role>();//切换仓仓(新功能)
  387. return db.GetList();
  388. }
  389. //分页
  390. //public List<Models.User> GetOrderPage(Expression<Func<Models.User, bool>> where, int pagesize, int pageindex)
  391. //{
  392. // return base.GetPageList(where, new SqlSugar.PageModel() { PageIndex = pageindex, PageSize = pagesize }); //使用自已的仓储方法
  393. //}
  394. //调用仓储扩展方法
  395. public List<User> GetOrderByJson(string Json)
  396. {
  397. return base.CommQuery(Json);
  398. }
  399. }
  400. #endregion
  401. public enum UserRightEnum
  402. {
  403. [Description("Step")]
  404. Step = 0,
  405. [Description("Product")]
  406. Product = 1,
  407. [Description("Order")]
  408. Order = 2,
  409. [Description("Statistics")]
  410. Statistics = 3,
  411. [Description("Role")]
  412. Role = 4,
  413. [Description("User")]
  414. User = 5,
  415. [Description("Calibration")]
  416. Calibration = 6,
  417. [Description("SysSetting")]
  418. SysSetting = 7,
  419. [Description("ParamsSetting")]
  420. ParamsSetting = 8,
  421. [Description("Manual")]
  422. Manual = 9,
  423. [Description("Debug")]
  424. Debug = 10,
  425. [Description("Operation1")]
  426. Operation1 = 11,
  427. [Description("Operation2")]
  428. Operation2 = 12,
  429. [Description("Operation3")]
  430. Operation3 = 13,
  431. }
  432. #region 用户管理
  433. public class UserMgr
  434. {
  435. #region #权限集
  436. #endregion
  437. private User _LoginUser;
  438. /// <summary>
  439. /// 获取当前登入用户
  440. /// </summary>
  441. public User LoginUser { get { return _LoginUser; } }
  442. private bool _IsLogin;
  443. /// <summary>
  444. /// 是否登入
  445. /// </summary>
  446. public bool IsLogin { get { return _IsLogin; } }
  447. private string _MySqlIP;
  448. private bool _IsRememberUserCode;
  449. public bool IsRememberUserCode { get { return _IsRememberUserCode; } }
  450. private bool _IsRememberUserPw;
  451. public bool IsRememberUserPw { get { return _IsRememberUserPw; } }
  452. private string _UserCfgPath;
  453. public UserMgr(string MySqlIP)
  454. {
  455. ConteolUserDB.SetServerIP(MySqlIP);
  456. _MySqlIP = MySqlIP;
  457. _LoginUser = new User();
  458. _UserCfgPath = Application.StartupPath + "\\ConfigFiles\\Login.ini";
  459. if(!File.Exists(Application.StartupPath + "\\ConfigFiles"))
  460. {
  461. DirectoryInfo directoryInfo = new DirectoryInfo(Application.StartupPath + "\\ConfigFiles");
  462. directoryInfo.Create();
  463. }
  464. }
  465. public bool InitialUserMgrDB(bool dropTable = true)
  466. {
  467. bool ret = false;
  468. //List<string[]> RightList = new List<string[]>();
  469. try
  470. {
  471. //初始化用户数据库
  472. ConteolUserDB.initDB(dropTable);
  473. ret = true;
  474. }
  475. catch (Exception ex)
  476. {
  477. MessageBox.Show("错误信息:" + ex.Message, "报警", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
  478. }
  479. return ret;
  480. }
  481. public string CheckUser(string UserName, string Password)
  482. {
  483. string ret = "";
  484. //查询数据库,比对账号密码
  485. try
  486. {
  487. UserService service = new UserService();
  488. var model = service.GetModel(UserName, Password);
  489. if (model == null)
  490. {
  491. ret = "帐号或密码错误!";
  492. return ret;
  493. }
  494. if (UserName != "admin" && !model.State)
  495. {
  496. ret = "帐号已停用!";
  497. return ret;
  498. }
  499. if (string.IsNullOrWhiteSpace(model.Password))
  500. model.Password = "";
  501. _LoginUser = model;
  502. }
  503. catch (Exception ex)
  504. {
  505. MessageBox.Show("错误信息:" + ex.Message , "报警", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
  506. ret = "数据库异常!";
  507. }
  508. return ret;
  509. }
  510. public void SetRememberUser(bool code, bool pw)
  511. {
  512. _IsRememberUserCode = code;
  513. _IsRememberUserPw = pw;
  514. }
  515. public bool GetUserCfg()
  516. {
  517. bool ret = false;
  518. if (!File.Exists(_UserCfgPath))
  519. return false;
  520. IniHelper iniHelper = new IniHelper(_UserCfgPath);
  521. string sValue = "";
  522. //int iValue = 0;
  523. //double dValue = 0;
  524. bool bValue = false;
  525. string section = "User";
  526. ret = iniHelper.ReadString(section, "UserCode", out sValue);
  527. _LoginUser.Code = sValue.Trim();
  528. ret = iniHelper.ReadString(section, "UserPw", out sValue);
  529. //_LoginUser.Password = PasswordUnprotect(sValue.Trim());
  530. _LoginUser.Password = sValue.Trim();
  531. ret = iniHelper.ReadBool(section, "IsRememberUserCode", out bValue);
  532. _IsRememberUserCode = bValue;
  533. ret = iniHelper.ReadBool(section, "IsRememberUserPw", out bValue);
  534. _IsRememberUserPw = bValue;
  535. return ret;
  536. }
  537. public bool SetUserCfg()
  538. {
  539. bool ret = false;
  540. IniHelper iniHelper = new IniHelper(_UserCfgPath);
  541. string section = "User";
  542. ret = iniHelper.WriteString(section, "UserCode", _LoginUser.Code);
  543. //ret = iniHelper.WriteString(section, "UserPw", PasswordProtect(_LoginUser.Password));
  544. ret = iniHelper.WriteString(section, "UserPw", _LoginUser.Password);
  545. ret = iniHelper.WriteBool(section, "IsRememberUserCode", _IsRememberUserCode);
  546. ret = iniHelper.WriteBool(section, "IsRememberUserPw", _IsRememberUserPw);
  547. return ret;
  548. }
  549. public bool RightControl(UserRightEnum rightEnum)
  550. {
  551. //if (_LoginUser.RoleInfo.Code.IndexOf("admin") > 0)
  552. if (_LoginUser.RoleInfo.Code == "admin")
  553. return true;
  554. switch (rightEnum)
  555. {
  556. case UserRightEnum.Step:
  557. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Step") != null;
  558. case UserRightEnum.Product:
  559. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Product") != null;
  560. case UserRightEnum.Order:
  561. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Order") != null;
  562. case UserRightEnum.Statistics:
  563. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Statistics") != null;
  564. case UserRightEnum.Role:
  565. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Role") != null;
  566. case UserRightEnum.User:
  567. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "User") != null;
  568. case UserRightEnum.Calibration:
  569. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Calibration") != null;
  570. case UserRightEnum.SysSetting:
  571. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "SysSetting") != null;
  572. case UserRightEnum.ParamsSetting:
  573. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "ParamsSetting") != null;
  574. case UserRightEnum.Manual:
  575. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Manual") != null;
  576. case UserRightEnum.Debug:
  577. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Debug") != null;
  578. case UserRightEnum.Operation1:
  579. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Operation1") != null;
  580. case UserRightEnum.Operation2:
  581. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Operation2") != null;
  582. case UserRightEnum.Operation3:
  583. return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Operation3") != null;
  584. default:
  585. return false;
  586. }
  587. }
  588. /// <summary>
  589. /// 用户登入 含界面
  590. /// </summary>
  591. /// <returns></returns>
  592. public bool UserLoginDialog()
  593. {
  594. UserLoginFrm frm = new UserLoginFrm(this);
  595. DialogResult dret = frm.ShowDialog();
  596. if (dret != DialogResult.OK)
  597. {
  598. return false;
  599. }
  600. _IsLogin = true;
  601. return true;
  602. }
  603. /// <summary>
  604. /// 用户管理 含界面
  605. /// </summary>
  606. public void UserManagerDialog()
  607. {
  608. if (RightControl(UserRightEnum.User))
  609. {
  610. UserListFrm frm = new UserListFrm(this);
  611. DialogResult dret = frm.ShowDialog();
  612. }
  613. else
  614. MessageBox.Show("权限不足!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  615. }
  616. /// <summary>
  617. /// 用户权限管理 含界面
  618. /// </summary>
  619. public void RightManageDialog()
  620. {
  621. if (RightControl(UserRightEnum.Role))
  622. {
  623. RightMgrFrm frm = new RightMgrFrm(this._LoginUser);
  624. DialogResult dret = frm.ShowDialog();
  625. }
  626. else
  627. MessageBox.Show("权限不足!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  628. }
  629. #region 加解密
  630. //MaiMu
  631. private string PW_Entroty_str = "MaiMu";
  632. private string PasswordProtect(string pw)
  633. {
  634. if (string.IsNullOrEmpty(pw))
  635. pw = "IsNullOrEmpty";
  636. byte[] decBytes = System.Text.Encoding.UTF8.GetBytes(pw);
  637. byte[] PW_Entroty = System.Text.Encoding.UTF8.GetBytes(PW_Entroty_str);
  638. DataProtectionScope scope = DataProtectionScope.CurrentUser;
  639. byte[] encrypted = ProtectedData.Protect(decBytes, PW_Entroty, scope);
  640. string codepw = System.Text.Encoding.UTF8.GetString(encrypted);
  641. Console.WriteLine("\nEncrypted string = {0}", codepw);
  642. return codepw;
  643. }
  644. private string PasswordUnprotect(string Unpw)
  645. {
  646. byte[] encrypted = System.Text.Encoding.UTF8.GetBytes(Unpw);
  647. byte[] PW_Entroty = System.Text.Encoding.UTF8.GetBytes(PW_Entroty_str);
  648. DataProtectionScope scope = DataProtectionScope.CurrentUser;
  649. byte[] decrypted = ProtectedData.Unprotect(encrypted, PW_Entroty, scope);
  650. string codepw = System.Text.Encoding.UTF8.GetString(decrypted);
  651. Console.WriteLine("\nDecrypted data using CurrentUser scope = {0}", codepw);
  652. if (codepw == "IsNullOrEmpty")
  653. return "";
  654. return codepw;
  655. }
  656. #endregion
  657. }
  658. #endregion
  659. }