using MaiMuControl.Device.IOCardDev;
using MaiMuControl.SysStatusMgr.UserMgr;
using MySql.Data.MySqlClient;
using SqlSugar;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ToolKits.Ini;
namespace GeBoShi.UI.User
{
#region 基础表
///
/// 基础表格
///
public class BaseTable
{
[SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
public int Id { get; set; }
public string ModifyUserCode { get; set; }
[SugarColumn(UpdateServerTime = true, InsertServerTime = true)]
public DateTime ModifyTime { get; set; }
[SugarColumn(IsOnlyIgnoreUpdate = true)]
public string CreateUserCode { get; set; }
//insert时使用DB时间填充,不更新
[SugarColumn(InsertServerTime = true, IsOnlyIgnoreUpdate = true)]
public DateTime CreateTime { get; set; } = DateTime.Now;//程序中需要用
}
#endregion
#region 权限集,权限,对应关系
[SugarIndex("index_{table}_code", nameof(Right.Code), OrderByType.Asc, isUnique: true)]
public class Right : BaseTable
{
public Right() { }
public Right(string code, string name, string groupName = "默认")
{
Code = code;
Name = name;
GroupName = groupName;
CreateUserCode = "admin";
ModifyUserCode = "admin";
}
public bool check { get; set; }
public string GroupName { get; set; }//分组名
[SugarColumn(Length = 16)]
public string Code { get; set; }
public string Name { get; set; }
//用于根据权限查所有角色时用
//[Navigate(typeof(RoleRightMap), nameof(RoleRightMap.RightId), nameof(RoleRightMap.RoleId))]//注意顺序
//public List RoleList { get; set; }
}
public class RoleRightMap : BaseTable
{
public int RoleId { get; set; }
public int RightId { get; set; }
///
/// 0-无权 1-查看 2-修改
///
public int Level { get; set; }
}
[SugarIndex("index_{table}_code", nameof(Role.Code), OrderByType.Asc, isUnique: true)]
public class Role : BaseTable
{
[SugarColumn(Length = 16)]
public string Code { get; set; }
public string Name { get; set; }
[Navigate(typeof(RoleRightMap), nameof(RoleRightMap.RoleId), nameof(RoleRightMap.RightId))]//注意顺序
public List RightList { get; set; }
}
#endregion
#region 用户表
[SugarIndex("index_{table}_code", nameof(User.Code), OrderByType.Asc, isUnique: true)]
public class User : BaseTable
{
[SugarColumn(Length = 16)]
public string Code { get; set; }
public string Name { get; set; }
[SugarColumn(IsNullable = true)]
public string Password { get; set; }
public int RoleId { get; set; }
[Navigate(NavigateType.ManyToOne, nameof(RoleId))]
public Role RoleInfo { get; set; }
public bool State { get; set; } = true;
///
/// 是否自动登出
///
public bool AutoLogOut { get; set; } = false;
///
/// 自动登出时间 5分钟
///
public int LogOutTimeMinutes { get; set; } = 5;
[SugarColumn(IsNullable = true)]
public string Note { get; set; }
}
#endregion
#region 初始化用户数据库
public class ConteolUserDB
{
public static string GetSqlDBCode()
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "SystemDefault.ini");
if (File.Exists(path))
{
string sValue;
IniHelper iniHelper = new IniHelper(path);
iniHelper.ReadString("SystemDefault", "MySqlCode", out sValue);
return sValue.Replace("\0", "");
}
else
{
// write default value
IniHelper iniHelper = new IniHelper(path);
iniHelper.WriteString("SystemDefault", "MySqlCode", "Maimu888");
return "Maimu888";
}
}
//server=localhost;Database=ProductionDB;Uid=root;Pwd=123456; AllowLoadLocalInfile=true
///
/// 用户数据库,链接地址
///
public static string ConnectionString { get; private set ; }
///
/// 设置需要联机的数据库IP
///
///
public static void SetServerIP(string addrIP)
{
//server = localhost; Database = ProductionDB; Uid = root; Pwd = 123456; AllowLoadLocalInfile = true
ConnectionString = "server = " + addrIP + "; Database = UserDB; Uid = root; Pwd = " + GetSqlDBCode() + "; AllowLoadLocalInfile = true;";
//ConnectionString = "server=127.0.0.1;port=3306;database=UserDB;uid=testUser;pwd=123456;";
//ConnectionString = "server = localhost; Database = UserDB; Uid = root; Pwd = 123456; AllowLoadLocalInfile = true";
}
///
/// 初始化用户数据表
///
///
///
public static void initDB( bool dropTable = false)
{
ConnectionConfig connectionConfig = new ConnectionConfig()
{
ConnectionString = ConnectionString,
DbType = SqlSugar.DbType.MySql,
IsAutoCloseConnection = true
};
//创建数据库对象
using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
{
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响
};
//create db
db.DbMaintenance.CreateDatabase();
//db.DbMaintenance.TruncateTable();//删除记录
//===建表
if (dropTable && db.DbMaintenance.IsAnyTable("Right", false)) db.DbMaintenance.DropTable("Right");
if (dropTable && db.DbMaintenance.IsAnyTable("Role", false)) db.DbMaintenance.DropTable("Role");
if (dropTable && db.DbMaintenance.IsAnyTable("RoleRightMap", false)) db.DbMaintenance.DropTable("RoleRightMap");
if (dropTable && db.DbMaintenance.IsAnyTable("User", false)) db.DbMaintenance.DropTable("User");
//===添加与更新表
db.CodeFirst.InitTables();
db.CodeFirst.InitTables();
db.CodeFirst.InitTables();
db.CodeFirst.InitTables();
//更新新列数据
//db.Ado.ExecuteCommand("update Step set Tag=0 where Tag is null");
//try
//{
// db.Ado.ExecuteCommand("ALTER TABLE Product DROP COLUMN HoleCountId");
//}
//catch { }
//try {
// db.Ado.ExecuteCommand("ALTER TABLE Product DROP COLUMN HoleCount");
//}
//catch { }
//===初始数据 注意*********会清空这些表数据
//User
db.DbMaintenance.TruncateTable();
db.DbMaintenance.TruncateTable();
if (db.Queryable().Count() < 1)
{
//db.Insertable(new Models.User() { Code = "admin", Name = "管理员", RoleId = id }).ExecuteCommand();
db.InsertNav(new User()
{
Code = "admin",
Name = "管理员",
//Password = GetMD5(""),
Password = "",
RoleInfo = new Role() { Code = "admin", Name = "管理员", ModifyUserCode = "admin", CreateUserCode = "admin" },//多表添加
CreateUserCode = "admin",
ModifyUserCode = "admin",
}).Include(x => x.RoleInfo)
.ExecuteCommand();
}
//===权限
db.DbMaintenance.TruncateTable();
db.DbMaintenance.TruncateTable();
if (db.Queryable().Where(m => m.Code == "Step").Count() < 1) db.Insertable(new Right("Step", "流程管理")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Product").Count() < 1) db.Insertable(new Right("Product", "产品管理")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Order").Count() < 1) db.Insertable(new Right("Order", "报表查询")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Statistics").Count() < 1) db.Insertable(new Right("Statistics", "统计分析")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Role").Count() < 1) db.Insertable(new Right("Role", "角色管理")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "User").Count() < 1) db.Insertable(new Right("User", "用户管理")).ExecuteCommand();
//if (db.Queryable().Where(m => m.Code == "Right").Count() < 1) db.Insertable(new Models.Right("Right", "权限管理")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Calibration").Count() < 1) db.Insertable(new Right("Calibration", "标定设置")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "SysSetting").Count() < 1) db.Insertable(new Right("SysSetting", "系统设置")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "ParamsSetting").Count() < 1) db.Insertable(new Right("ParamsSetting", "参数设置")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Manual").Count() < 1) db.Insertable(new Right("Manual", "手动操作")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Debug").Count() < 1) db.Insertable(new Right("Debug", "设备调试")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Operation1").Count() < 1) db.Insertable(new Right("Operation1", "特色操作1")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Operation2").Count() < 1) db.Insertable(new Right("Operation2", "特色操作2")).ExecuteCommand();
if (db.Queryable().Where(m => m.Code == "Operation3").Count() < 1) db.Insertable(new Right("Operation3", "特色操作3")).ExecuteCommand();
//==触发器
//string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
//string sqlPath = rootPath + "\\ConfigFiles\\SqlPath\\";
//if (Directory.Exists(sqlPath))
//{
// int count;
// string triggerName = "trigger_order_update";
// if (File.Exists(sqlPath + triggerName + ".sql"))
// {
// count = db.Ado.GetInt($"SELECT count(*) FROM information_schema.TRIGGERS where TRIGGER_NAME = '{triggerName}'");
// if (count > 0)
// db.Ado.ExecuteCommand($"drop trigger {triggerName}");
// db.Ado.ExecuteCommand(File.ReadAllText(sqlPath + triggerName + ".sql"));
// }
//}
//==清理垃圾数据
//db.Ado.ExecuteCommand($"delete from `Order` where ProductId not in (select id from product)");
}
}
///
/// 备份DB (还原:mysql -uroot -p < d:\dbName.sql)
///
///
public static void BackupDataBase(string outFilePath)
{
using (var conn = new MySqlConnection(ConnectionString))
{
using (var cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
// 设置数据库连接
cmd.Connection = conn;
cmd.Connection.Open();
// 导出数据库到文件
mb.ExportToFile(outFilePath);
conn.Close();
}
}
}
}
private static string GetMD5(string str)
{
byte[] data = Encoding.UTF8.GetBytes(str);
data = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
string ret = "";
for (int i = 0; i < data.Length; i++)
{
ret += data[i].ToString("x1").PadLeft(2, '0');//ToString("x1"):转换为16进制
}
return ret.ToUpper();
}
//private static string Jiami(string code)
//{
// DataProtectionScope scope = DataProtectionScope.CurrentUser;
// byte[] encrypted = ProtectedData.Protect(original, null, scope);
//}
}
#endregion
#region 数据库操作
public class UserRepository : SimpleClient where T : class, new()
{
public UserRepository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
{
if (context == null)
{
base.Context = new SqlSugarClient(new ConnectionConfig()
{
DbType = SqlSugar.DbType.MySql,
//InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
ConnectionString = ConteolUserDB.ConnectionString
});
base.Context.Aop.OnLogExecuting = (s, p) =>
{
Console.WriteLine(s);
};
}
}
///
/// 扩展方法,自带方法不能满足的时候可以添加新方法
///
///
public List CommQuery(string json)
{
T t = Context.Utilities.DeserializeObject(json);
var list = base.Context.Queryable().WhereClass(t).ToList();
return list;
}
}
public class RoleService : UserRepository
{
public List GetListNav()
{
return base.AsSugarClient().Queryable()
.Includes(m => m.RightList)
.Where(m => m.Code != "admin")
.ToList();
}
public bool DelNav(Role model)
{
return base.AsSugarClient().DeleteNav(model)
.Include(a => a.RightList)
.ExecuteCommand();
}
public bool UpdateNav(Role model)
{
return base.AsSugarClient().UpdateNav(model)
.Include(a => a.RightList)//.ThenInclude(z1 => z1.RoomList) //插入2层 Root->ShoolA->RoomList
.ExecuteCommand();
}
//获取所有子
public List GetRightItems()
{
var db = base.Change();//切换仓仓(新功能)
var list = db.GetList();
return list;
}
//public List GetRightItems1()
//{
// var db = base.Change();//切换仓仓(新功能)
// base.AsSugarClient().ThenMapper(list, map =>
// {
// });
//}
//分页
//public List GetOrderPage(Expression> where, int pagesize, int pageindex)
//{
// return base.GetPageList(where, new SqlSugar.PageModel() { PageIndex = pageindex, PageSize = pagesize }); //使用自已的仓储方法
//}
//调用仓储扩展方法
public List GetOrderByJson(string Json)
{
return base.CommQuery(Json);
}
}
public class UserService : UserRepository
{
public List GetListNav()
{
return base.AsSugarClient().Queryable()
.Includes(m => m.RoleInfo, info => info.RightList)
.ToList();
}
public User GetModel(string userCode, string userPw)
{
//return base.GetFirst(t=>t.Code.Equals(userCode) && SqlFunc.IsNull(t.Password,"") .Equals(userPw));
return base.AsSugarClient().Queryable()
.Includes(m => m.RoleInfo, info => info.RightList)
.Where(t => t.Code.Equals(userCode) && SqlFunc.IsNull(t.Password, "").Equals(userPw))
.First();
}
public bool ModifyPw(int userId, string newPW)
{
//更新一个字段
var result = base.AsSugarClient().Updateable().SetColumns("Password", newPW).Where("id=" + userId).ExecuteCommand();
//更新多个字段
//var result = base.AsSugarClient().Updateable().SetColumns(p => new User { Password = newPW, Name = Name }).Where("id=" + userId).ExecuteCommand();
return result > 0;
}
//获取所有子
public List GetRoleItems()
{
var db = base.Change();//切换仓仓(新功能)
return db.GetList();
}
//分页
//public List GetOrderPage(Expression> where, int pagesize, int pageindex)
//{
// return base.GetPageList(where, new SqlSugar.PageModel() { PageIndex = pageindex, PageSize = pagesize }); //使用自已的仓储方法
//}
//调用仓储扩展方法
public List GetOrderByJson(string Json)
{
return base.CommQuery(Json);
}
}
#endregion
public enum UserRightEnum
{
[Description("Step")]
Step = 0,
[Description("Product")]
Product = 1,
[Description("Order")]
Order = 2,
[Description("Statistics")]
Statistics = 3,
[Description("Role")]
Role = 4,
[Description("User")]
User = 5,
[Description("Calibration")]
Calibration = 6,
[Description("SysSetting")]
SysSetting = 7,
[Description("ParamsSetting")]
ParamsSetting = 8,
[Description("Manual")]
Manual = 9,
[Description("Debug")]
Debug = 10,
[Description("Operation1")]
Operation1 = 11,
[Description("Operation2")]
Operation2 = 12,
[Description("Operation3")]
Operation3 = 13,
}
#region 用户管理
public class UserMgr
{
#region #权限集
#endregion
private User _LoginUser;
///
/// 获取当前登入用户
///
public User LoginUser { get { return _LoginUser; } }
private bool _IsLogin;
///
/// 是否登入
///
public bool IsLogin { get { return _IsLogin; } }
private string _MySqlIP;
private bool _IsRememberUserCode;
public bool IsRememberUserCode { get { return _IsRememberUserCode; } }
private bool _IsRememberUserPw;
public bool IsRememberUserPw { get { return _IsRememberUserPw; } }
private string _UserCfgPath;
public UserMgr(string MySqlIP)
{
ConteolUserDB.SetServerIP(MySqlIP);
_MySqlIP = MySqlIP;
_LoginUser = new User();
_UserCfgPath = Application.StartupPath + "\\ConfigFiles\\Login.ini";
if(!File.Exists(Application.StartupPath + "\\ConfigFiles"))
{
DirectoryInfo directoryInfo = new DirectoryInfo(Application.StartupPath + "\\ConfigFiles");
directoryInfo.Create();
}
}
public bool InitialUserMgrDB(bool dropTable = true)
{
bool ret = false;
//List RightList = new List();
try
{
//初始化用户数据库
ConteolUserDB.initDB(dropTable);
ret = true;
}
catch (Exception ex)
{
MessageBox.Show("错误信息:" + ex.Message, "报警", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
}
return ret;
}
public string CheckUser(string UserName, string Password)
{
string ret = "";
//查询数据库,比对账号密码
try
{
UserService service = new UserService();
var model = service.GetModel(UserName, Password);
if (model == null)
{
ret = "帐号或密码错误!";
return ret;
}
if (UserName != "admin" && !model.State)
{
ret = "帐号已停用!";
return ret;
}
if (string.IsNullOrWhiteSpace(model.Password))
model.Password = "";
_LoginUser = model;
}
catch (Exception ex)
{
MessageBox.Show("错误信息:" + ex.Message , "报警", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
ret = "数据库异常!";
}
return ret;
}
public void SetRememberUser(bool code, bool pw)
{
_IsRememberUserCode = code;
_IsRememberUserPw = pw;
}
public bool GetUserCfg()
{
bool ret = false;
if (!File.Exists(_UserCfgPath))
return false;
IniHelper iniHelper = new IniHelper(_UserCfgPath);
string sValue = "";
//int iValue = 0;
//double dValue = 0;
bool bValue = false;
string section = "User";
ret = iniHelper.ReadString(section, "UserCode", out sValue);
_LoginUser.Code = sValue.Trim();
ret = iniHelper.ReadString(section, "UserPw", out sValue);
//_LoginUser.Password = PasswordUnprotect(sValue.Trim());
_LoginUser.Password = sValue.Trim();
ret = iniHelper.ReadBool(section, "IsRememberUserCode", out bValue);
_IsRememberUserCode = bValue;
ret = iniHelper.ReadBool(section, "IsRememberUserPw", out bValue);
_IsRememberUserPw = bValue;
return ret;
}
public bool SetUserCfg()
{
bool ret = false;
IniHelper iniHelper = new IniHelper(_UserCfgPath);
string section = "User";
ret = iniHelper.WriteString(section, "UserCode", _LoginUser.Code);
//ret = iniHelper.WriteString(section, "UserPw", PasswordProtect(_LoginUser.Password));
ret = iniHelper.WriteString(section, "UserPw", _LoginUser.Password);
ret = iniHelper.WriteBool(section, "IsRememberUserCode", _IsRememberUserCode);
ret = iniHelper.WriteBool(section, "IsRememberUserPw", _IsRememberUserPw);
return ret;
}
public bool RightControl(UserRightEnum rightEnum)
{
//if (_LoginUser.RoleInfo.Code.IndexOf("admin") > 0)
if (_LoginUser.RoleInfo.Code == "admin")
return true;
switch (rightEnum)
{
case UserRightEnum.Step:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Step") != null;
case UserRightEnum.Product:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Product") != null;
case UserRightEnum.Order:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Order") != null;
case UserRightEnum.Statistics:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Statistics") != null;
case UserRightEnum.Role:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Role") != null;
case UserRightEnum.User:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "User") != null;
case UserRightEnum.Calibration:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Calibration") != null;
case UserRightEnum.SysSetting:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "SysSetting") != null;
case UserRightEnum.ParamsSetting:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "ParamsSetting") != null;
case UserRightEnum.Manual:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Manual") != null;
case UserRightEnum.Debug:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Debug") != null;
case UserRightEnum.Operation1:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Operation1") != null;
case UserRightEnum.Operation2:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Operation2") != null;
case UserRightEnum.Operation3:
return _LoginUser.RoleInfo.RightList.FirstOrDefault(m => m.Code == "Operation3") != null;
default:
return false;
}
}
///
/// 用户登入 含界面
///
///
public bool UserLoginDialog()
{
UserLoginFrm frm = new UserLoginFrm(this);
DialogResult dret = frm.ShowDialog();
if (dret != DialogResult.OK)
{
return false;
}
_IsLogin = true;
return true;
}
///
/// 用户管理 含界面
///
public void UserManagerDialog()
{
if (RightControl(UserRightEnum.User))
{
UserListFrm frm = new UserListFrm(this);
DialogResult dret = frm.ShowDialog();
}
else
MessageBox.Show("权限不足!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
///
/// 用户权限管理 含界面
///
public void RightManageDialog()
{
if (RightControl(UserRightEnum.Role))
{
RightMgrFrm frm = new RightMgrFrm(this._LoginUser);
DialogResult dret = frm.ShowDialog();
}
else
MessageBox.Show("权限不足!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#region 加解密
//MaiMu
private string PW_Entroty_str = "MaiMu";
private string PasswordProtect(string pw)
{
if (string.IsNullOrEmpty(pw))
pw = "IsNullOrEmpty";
byte[] decBytes = System.Text.Encoding.UTF8.GetBytes(pw);
byte[] PW_Entroty = System.Text.Encoding.UTF8.GetBytes(PW_Entroty_str);
DataProtectionScope scope = DataProtectionScope.CurrentUser;
byte[] encrypted = ProtectedData.Protect(decBytes, PW_Entroty, scope);
string codepw = System.Text.Encoding.UTF8.GetString(encrypted);
Console.WriteLine("\nEncrypted string = {0}", codepw);
return codepw;
}
private string PasswordUnprotect(string Unpw)
{
byte[] encrypted = System.Text.Encoding.UTF8.GetBytes(Unpw);
byte[] PW_Entroty = System.Text.Encoding.UTF8.GetBytes(PW_Entroty_str);
DataProtectionScope scope = DataProtectionScope.CurrentUser;
byte[] decrypted = ProtectedData.Unprotect(encrypted, PW_Entroty, scope);
string codepw = System.Text.Encoding.UTF8.GetString(decrypted);
Console.WriteLine("\nDecrypted data using CurrentUser scope = {0}", codepw);
if (codepw == "IsNullOrEmpty")
return "";
return codepw;
}
#endregion
}
#endregion
}