using iWareCommon.Common.Entity; using iWareCommon.Common.EnumType; using iWareCommon.Common.Service; using iWareCommon.Utils; using iWareDataCore.ORM; using iWareDataCore.Properties; using iWareDataCore.RBAC.Dao; using iWareDataCore.RBAC.Entity; using iWareDataCore.RBAC.EnumType; using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Linq; using System.Text; using System.Threading.Tasks; namespace iWareDataCore.RBAC.Service { public class UserService : CommonService { private static object Lock = new object(); private UserService() : base(UserDao.GetInstance()) { } private static UserService Instance = null; /// /// 获取单例的方法 /// /// 用户服务的单例实体 public static UserService GetInstance() { if (Instance == null) { lock (Lock) { if (Instance == null) { Instance = new UserService(); } } } return Instance; } /// /// 批量修改用户状态 /// /// 需要修改的用户id列表 /// 状态:1为启用,0为锁定 /// 异常错误消息 /// 修改的用户数量 public int ChangeStatus(List ids, int status, out string msg) { msg = ""; using (var dbModel = new DbModelCore()) { try { var ones = dbModel.RBACUsers.Where(x => ids.Contains(x.id)).ToList(); foreach (var one in ones) { one.status = status; } dbModel.SaveChanges(); return ones.Count; } catch (Exception ex) { msg = ex.Message; LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "ChangeStatus", ex.Message); return -1; } } } /// /// 用户自己修改用户密码 /// /// 用户Id /// 原密码 /// 新密码 /// 异常错误消息 /// 修改用户的Id,发生错误是返回-1 public int ChangePassword(int id, string oldPassword, string newPassword, out string msg) { msg = ""; using (var dbModel = new DbModelCore()) { try { var oPass = MD5Helper.ParseMd5(oldPassword); var users = dbModel.RBACUsers.Where(x => x.id == id && x.password == oPass).ToList(); if (users.Count <= 0) { msg = "您输入的原始密码错误!"; return -1; } users[0].password = MD5Helper.ParseMd5(newPassword); dbModel.SaveChanges(); return id; } catch (Exception ex) { msg = ex.Message; LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "ChangePassword", ex.Message); return -1; } } } /// /// 将密码重置为111111 /// /// 用户Id /// 异常错误消息 /// 修改用户的Id,发生错误是返回-1 public int ResetPassword(int id, out string msg) { msg = ""; using (var dbModel = new DbModelCore()) { try { var users = dbModel.RBACUsers.Where(x => x.id == id).ToList(); if (users.Count <= 0) { msg = "未找到指定用户!"; return -1; } users[0].password = MD5Helper.ParseMd5(Resources.InitPassword); dbModel.SaveChanges(); return id; } catch (Exception ex) { msg = ex.Message; LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "ResetPassword", ex.Message); return -1; } } } public override List QueryByParam(QueryParam param, out string msg) { msg = ""; using (var dbModel = new DbModelCore()) { var users = UserDao.GetInstance().QueryByParam(param, dbModel); var roles = RoleDao.GetInstance().QueryByParam(new QueryParam(), dbModel); //以角色Id为键,角色实体为值的字典 var roleDictionary = new Dictionary(); foreach (var role in roles) { roleDictionary.Add(role.Id, role); } //以用户id为键,角色id列表为值的字典 var userIdRoleIdsDictionary = new Dictionary>(); foreach (var user in users) { userIdRoleIdsDictionary.Add(user.Id, new List()); } var roleUsers = RoleUserDao.GetInstance().QueryByParam(new QueryParam(), dbModel); foreach (var one in roleUsers) { if (userIdRoleIdsDictionary.ContainsKey(one.UserId)) { userIdRoleIdsDictionary[one.UserId].Add(one.RoleId); } } foreach (var user in users) { foreach (var roleId in userIdRoleIdsDictionary[user.Id]) { user.Roles.Add(roleDictionary[roleId]); user.DisplayRoleNames += roleDictionary[roleId].RoleName + ","; } if (user.DisplayRoleNames.EndsWith(",")) { user.DisplayRoleNames = user.DisplayRoleNames.Substring(0, user.DisplayRoleNames.Length - 1); } } return users; } } public override List QueryByParam(QueryParam param, out string msg, out int totalNum, out int currentPage) { msg = ""; totalNum = 0; currentPage = 1; using (var dbModel = new DbModelCore()) { var users = UserDao.GetInstance().QueryByParam(param, dbModel, out totalNum, out currentPage); var roles = RoleDao.GetInstance().QueryByParam(new QueryParam(), dbModel); //以角色Id为键,角色实体为值的字典 var roleDictionary = new Dictionary(); foreach (var role in roles) { roleDictionary.Add(role.Id, role); } //以用户id为键,角色id列表为值的字典 var userIdRoleIdsDictionary = new Dictionary>(); foreach (var user in users) { userIdRoleIdsDictionary.Add(user.Id, new List()); } var roleUsers = RoleUserDao.GetInstance().QueryByParam(new QueryParam(), dbModel); foreach (var one in roleUsers) { if (userIdRoleIdsDictionary.ContainsKey(one.UserId)) { userIdRoleIdsDictionary[one.UserId].Add(one.RoleId); } } foreach (var user in users) { foreach (var roleId in userIdRoleIdsDictionary[user.Id]) { user.Roles.Add(roleDictionary[roleId]); user.DisplayRoleNames += roleDictionary[roleId].RoleName + ","; } if (user.DisplayRoleNames.EndsWith(",")) { user.DisplayRoleNames = user.DisplayRoleNames.Substring(0, user.DisplayRoleNames.Length - 1); } } return users; } } public override int Delete(int id, out string msg) { Delete(new List { id }, out msg); return string.IsNullOrEmpty(msg) ? id : -1; } public override int Delete(List ids, out string msg) { msg = ""; using (var dbModel = new DbModelCore()) { try { var roleUsers = dbModel.RBACRoleUsers.Where(x => ids.Contains(x.userid)).ToList(); roleUsers.ForEach(x => dbModel.RBACRoleUsers.Remove(x)); var ones = dbModel.RBACUsers.Where(x => ids.Contains(x.id)).ToList(); ones.ForEach(x => x.label = (int)ELabelStatus.已删除); dbModel.SaveChanges(); return ones.Count; } catch (Exception ex) { msg = ex.Message; LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "DeleteBatch", ex.Message); return 0; } } } public override int Save(UserEntity user, out string msg) { msg = ""; using (var dbModel = new DbModelCore()) { try { var one = user.ToOrm(); if (string.IsNullOrEmpty(one.password)) { one.password = MD5Helper.ParseMd5(Resources.InitPassword); } else { one.password = MD5Helper.ParseMd5(one.password); } if (user.Roles != null) { foreach (var role in user.Roles) { one.RBACRoleUsers.Add(new RBACRoleUser { roleid = role.Id }); } } dbModel.RBACUsers.Add(one); dbModel.SaveChanges(); return one.id; } catch (DbEntityValidationException ex) { var errs = ex.EntityValidationErrors.SelectMany(validationResult => validationResult.ValidationErrors).Select(m => m.ErrorMessage); msg = string.Join(", ", errs); LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Save", msg); return -1; } catch (Exception ex) { msg = ex.HResult == (int)EDbError.记录已存在 ? EDbError.记录已存在.ToString() : ex.Message; LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Save", msg); return -1; } } } public override int Update(UserEntity user, out string msg) { msg = ""; using (var dbModel = new DbModelCore()) { try { var one = dbModel.RBACUsers.First(x => x.id == user.Id); EntityPropHelper.CopyProp(user, one, UserEntity.GetColumnMap()); var ones = dbModel.RBACRoleUsers.Where(x => x.userid == user.Id).ToList(); foreach (var ur in ones) { dbModel.RBACRoleUsers.Remove(ur); } if (user.Roles != null) { foreach (var role in user.Roles) { one.RBACRoleUsers.Add(new RBACRoleUser { roleid = role.Id }); } } dbModel.SaveChanges(); return one.id; } catch (DbEntityValidationException ex) { var errs = ex.EntityValidationErrors.SelectMany(validationResult => validationResult.ValidationErrors).Select(m => m.ErrorMessage); msg = string.Join(", ", errs); LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Save", msg); return -1; } catch (Exception ex) { msg = ex.Message; LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Update", ex.Message); return -1; } } } /// /// 用户登录验证 /// /// 用户名 /// 密码 /// 异常错误信息 /// 登录成功后的用户信息,登录失败时返回null public UserEntity Login(string username, string password, out string msg) { msg = ""; if (string.IsNullOrEmpty(username)) { msg = "用户名不能为空"; return null; } if (string.IsNullOrEmpty(password)) { msg = "密码不能为空"; return null; } using (var dbModel = new DbModelCore()) { try { var pass = MD5Helper.ParseMd5(password); var users = dbModel.RBACUsers.Where(x => x.username == username && x.password == pass && x.status == (int)EStatus.启用 && x.label == (int)ELabelStatus.未删除).ToList(); if (users.Count <= 0) { msg = "用户名或密码错误!"; return null; } var user = new UserEntity(users[0]); //拼装用户角色 var roleUsers = dbModel.RBACRoleUsers.Where(x => x.userid == user.Id).ToList(); var roleIds = new List(); foreach (var one in roleUsers) { roleIds.Add(one.roleid); } var roles = dbModel.RBACRoles.Where(x => roleIds.Contains(x.id)).ToList(); foreach (var role in roles) { user.Roles.Add(new RoleEntity(role)); } //拼装用户菜单 var roleContents = dbModel.RBACRoleContents.Where(x => roleIds.Contains(x.roleid)).ToList(); var contentIds = new List(); var valueDictionary = new Dictionary(); foreach (var roleContent in roleContents) { if (!contentIds.Contains(roleContent.contentid)) { contentIds.Add(roleContent.contentid); valueDictionary.Add(roleContent.contentid, roleContent.value); } else { if (valueDictionary[roleContent.contentid] < roleContent.value) { valueDictionary[roleContent.contentid] = roleContent.value; } } } var contents = dbModel.RBACContents.Where(x => contentIds.Contains(x.id)).OrderBy(x => x.contentindex).ToList(); var planContents = new List(); foreach (var content in contents) { planContents.Add(new ContentValueEntity(content, valueDictionary[content.id])); } var childrenDictionary = TreeHelper.GetChildrenDictionary(planContents); var userContents = childrenDictionary.ContainsKey(-1) ? childrenDictionary[-1] : new List(); foreach (var content in userContents) { if (((int)EContentType.用于BS端的菜单).Equals(content.Type)) { user.Contents.Add(content); } else if (((int)EContentType.用于CS端的菜单).Equals(content.Type)) { user.CsContents.Add(content); } } if (user.Roles.Count > 0) { for (var i = 0; i < user.Roles.Count; i++) { user.DisplayRoleNames += user.Roles[i].RoleName + ","; } if (user.DisplayRoleNames.EndsWith(",")) { user.DisplayRoleNames = user.DisplayRoleNames.Substring(0, user.DisplayRoleNames.Length - 1); } } return user; } catch (Exception ex) { msg = ex.Message; LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Login", ex.Message); return null; } } } /// /// 用户登录验证 /// /// 用户名 /// 密码 /// 异常错误信息 /// 登录成功后的用户信息,登录失败时返回null public UserEntity Login(string username, string password, string cellName, out string msg) { msg = ""; if (string.IsNullOrEmpty(username)) { msg = "用户名不能为空"; return null; } if (string.IsNullOrEmpty(password)) { msg = "密码不能为空"; return null; } using (var dbModel = new DbModelCore()) { try { var pass = MD5Helper.ParseMd5(password); var users = dbModel.RBACUsers.Where(x => x.username == username && x.password == pass && x.status == (int)EStatus.启用 && x.label == (int)ELabelStatus.未删除).ToList(); if (users.Count <= 0) { msg = "用户名或密码错误!"; return null; } var user = new UserEntity(users[0]); var roleIds = new List(); var roles = dbModel.RBACRoles.Where(x => x.rolename == cellName).ToList(); foreach (var role in roles) { roleIds.Add(role.id); user.Roles.Add(new RoleEntity(role)); } //拼装用户菜单 var roleContents = dbModel.RBACRoleContents.Where(x => roleIds.Contains(x.roleid)).ToList(); var contentIds = new List(); var valueDictionary = new Dictionary(); foreach (var roleContent in roleContents) { if (!contentIds.Contains(roleContent.contentid)) { contentIds.Add(roleContent.contentid); valueDictionary.Add(roleContent.contentid, roleContent.value); } else { if (valueDictionary[roleContent.contentid] < roleContent.value) { valueDictionary[roleContent.contentid] = roleContent.value; } } } var contents = dbModel.RBACContents.Where(x => contentIds.Contains(x.id)).OrderBy(x => x.contentindex).ToList(); var planContents = new List(); foreach (var content in contents) { planContents.Add(new ContentValueEntity(content, valueDictionary[content.id])); } var childrenDictionary = TreeHelper.GetChildrenDictionary(planContents); var userContents = childrenDictionary.ContainsKey(-1) ? childrenDictionary[-1] : new List(); foreach (var content in userContents) { if (((int)EContentType.用于BS端的菜单).Equals(content.Type)) { user.Contents.Add(content); } else if (((int)EContentType.用于CS端的菜单).Equals(content.Type)) { user.CsContents.Add(content); } } if (user.Roles.Count > 0) { for (var i = 0; i < user.Roles.Count; i++) { user.DisplayRoleNames += user.Roles[i].RoleName + ","; } if (user.DisplayRoleNames.EndsWith(",")) { user.DisplayRoleNames = user.DisplayRoleNames.Substring(0, user.DisplayRoleNames.Length - 1); } } return user; } catch (Exception ex) { msg = ex.Message; LogTextHelper.WriteLog(Resources.LogDir, this.ToString(), "Login", ex.Message); return null; } } } } }