using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Web.Mvc; using System.Web.Script.Serialization; using System.Xml.Serialization; using DSWeb.SoftMng.BLL; using DSWeb.SoftMng.DBUtility; using DSWeb.SoftMng.Model; using DSWeb.SoftMng.Filter; using DSWeb.Areas.CommMng.Models; using DSWeb.TruckMng.Helper.Repository; using HcUtility.Comm; using DSWeb.EntityDA; using DSWeb.Models; using Newtonsoft.Json; using DSWeb.Areas.CommMng.DAL; using DSWeb.Areas.SysMng.DAL.SysUser; namespace DSWeb.SoftMng.Controllers { public class AuthController : Controller { private readonly sys_secCompanyServerBLL _bll = new sys_secCompanyServerBLL(); private readonly sys_secModuleServerBLL _mbll = new sys_secModuleServerBLL(); private readonly info_clientServerBLL _cbll = new info_clientServerBLL(); private readonly sys_moduleServerBLL _ibll = new sys_moduleServerBLL(); #region View /// <summary> /// 首页 /// </summary> /// <returns></returns> //[ModuleAuthFilter(Name = "secRegist")]//过滤器 public ActionResult Index() { if (Session["CODENAME"] == null) Response.Redirect("/login.aspx"); ViewData["CODENAME"] = Session["CODENAME"]; return View(); } /// <summary> /// 角色权限 /// </summary> /// <returns></returns> public ActionResult RoleAuth() { if (Session["CODENAME"] == null) Response.Redirect("/login.aspx"); ViewData["CODENAME"] = Session["CODENAME"]; return View(); } /// <summary> /// 角色权限范围 /// </summary> /// <returns></returns> public ActionResult RoleAuthRange() { if (Session["CODENAME"] == null) Response.Redirect("/login.aspx"); ViewData["CODENAME"] = Session["CODENAME"]; return View(); } /// <summary> /// 用户角色 /// </summary> /// <returns></returns> public ActionResult UserRole() { if (Session["CODENAME"] == null) Response.Redirect("/login.aspx"); ViewData["CODENAME"] = Session["CODENAME"]; return View(); } #endregion #region Handler /// <summary> /// 获取列表 /// </summary> /// <param name="startIndex">开始索引</param> /// <param name="limit">分页大小</param> /// <param name="search">搜索框的值</param> /// <param name="sortName">排序字段</param> /// <param name="sortOrder">排序方式</param> /// <returns></returns> [SqlKeyWordsFilter(Type = "Action")]//sql 防注入过滤器 public JsonResult GetList(int startIndex, int limit, string search, string sortName, string sortOrder,string companyId, string opUser, string question,string beginRegCount_1, string beginRegCount_2, string beginDate_1, string beginDate_2) { StringBuilder where = new StringBuilder(); where.Append("1=1"); if (!(String.IsNullOrEmpty(opUser) || String.IsNullOrWhiteSpace(opUser))) { //search=Common.Common.string_Encrypt(search, "Dw9pVb9r"); where.Append(string.Format(" And OperUser like '%{0}%'", opUser)); } if (!(String.IsNullOrEmpty(beginDate_1) || String.IsNullOrWhiteSpace(beginDate_1))) { //search=Common.Common.string_Encrypt(search, "Dw9pVb9r"); where.Append(string.Format(" And OperTime>='{0}'", beginDate_1)); } if (!(String.IsNullOrEmpty(beginDate_2) || String.IsNullOrWhiteSpace(beginDate_2))) { //search=Common.Common.string_Encrypt(search, "Dw9pVb9r"); where.Append(string.Format(" And OperTime<='{0}'", beginDate_2)); } var list = _bll.GetModelList(0, 2000, where.ToString(), String.Format("{0} {1}", sortName, sortOrder)); var result = from p in list select new { p.GID, CecrietStr = new JavaScriptSerializer().Deserialize<CecrietStr>(Common.Common.string_Decrypt(p.CompanySecretKey, "Dw9pVb9r")), p.OperUser, p.OperTime }; if (!(String.IsNullOrEmpty(search) || String.IsNullOrWhiteSpace(search))) { result = result.Where(p=>p.CecrietStr.Name.Contains(search)); } if (!(String.IsNullOrEmpty(beginRegCount_1) || String.IsNullOrWhiteSpace(beginRegCount_1))) { result = result.Where(p => p.CecrietStr.Times>=Convert.ToInt32(beginRegCount_1)); } if (!(String.IsNullOrEmpty(beginRegCount_2) || String.IsNullOrWhiteSpace(beginRegCount_2))) { result = result.Where(p => p.CecrietStr.Times <= Convert.ToInt32(beginRegCount_2)); } if (!(String.IsNullOrEmpty(question) || String.IsNullOrWhiteSpace(question))) { result = result.Where(p => p.CecrietStr.ModHistory!=null&&p.CecrietStr.ModHistory.Contains(question)); } var count = result.Count();//总数 result = result.Skip(startIndex).Take(limit); return Json(new { total = count, rows = result }); } /// <summary> /// 详细列表 /// </summary> /// <returns></returns> public JsonResult GetDetailList(string parentId, string companyId, bool isroot) { StringBuilder where = new StringBuilder(); if (isroot) where.Append("(PARENTID='0' or PARENTID='1') and TYPE<>1 "); else where.Append(string.Format("PARENTID='{0}'", parentId)); var list = _ibll.GetModelList(where.ToString()); var result = from p in list select new { p.GID, Name = p.DESCRIPTION, Code = p.NAME, Data = GetsecModel(p.GID, companyId), p.PARENTID, HasChild = _ibll.GetRecordCount(string.Format("PARENTID='{0}'", p.GID)) > 0 }; return Json(new { total = list.Count, rows = result }); } public object GetsecModel(string gid, string companyid) { var model = _mbll.GetModelList("IdenSecretkey='" + Common.Common.string_Encrypt(gid, "2cP46Gox") + "' AND PID='" + companyid + "'").FirstOrDefault(); if (model != null) return Json(new { SecModel = model, SecrietStr = new JavaScriptSerializer().Deserialize<SecrietStr>(Common.Common.string_Decrypt(model.ModuleSecretkey, "2cP46Gox")) }).Data; return Json(new { SecModel = new sys_secModule(), SecrietStr = new SecrietStr() { Id = null, Name = null, Times = null, Enabled = null } }).Data; } /// <summary> /// 保存 /// </summary> /// <param name="model"></param> /// <returns></returns> public JsonResult Save(Model.sys_secCompany model) { bool result; //加密算法{公司主键,公司名称,允许在线人数,是否启用} CecrietStr smodel = new CecrietStr(); Regex reg = new Regex(@"(?<=Key:')[\w-]+(?=')"); smodel.Id = reg.Match(Request["Name"]).Value; reg = new Regex(@"(?<=Value:').+(?=')"); smodel.Name = reg.Match(Request["Name"]).Value; smodel.Times = Convert.ToInt32(Request["Times"]); smodel.Enabled = Request["Enabled"] != "0"; smodel.MenuControl = Request["MenuControl"] != "0"; if (String.IsNullOrEmpty(model.GID)) { var toEncrypt = new JavaScriptSerializer().Serialize(smodel); var secretKey = Common.Common.string_Encrypt(toEncrypt, "Dw9pVb9r"); model.GID = Guid.NewGuid().ToString(); model.CompanySecretKey = secretKey; model.OperUser = Session["SHOWNAME"].ToString(); model.OperTime = DateTime.Now; result = _bll.Add(model) > 0; } //新增 else { //获取原数据 var oldModel = _bll.GetModel(model.GID); smodel.ModHistory = new JavaScriptSerializer().Deserialize<CecrietStr>(Common.Common.string_Decrypt(oldModel.CompanySecretKey, "Dw9pVb9r")).ModHistory; var toEncrypt = new JavaScriptSerializer().Serialize(smodel); var secretKey = Common.Common.string_Encrypt(toEncrypt, "Dw9pVb9r"); //类反射 Type type = typeof(Model.sys_secCompany); PropertyInfo[] piArr = type.GetProperties(); foreach (var pi in piArr) { if (Array.IndexOf(Request.Params.AllKeys, pi.Name) < 0) pi.SetValue(model, pi.GetValue(oldModel, null), null); } model.CompanySecretKey = secretKey; model.OperUser = Session["SHOWNAME"].ToString(); model.OperTime = DateTime.Now; result = _bll.Update(model) > 0; //try //{ // var operUser = Session["SHOWNAME"].ToString(); // var list = _ibll.GetModelList("MODTYPE=0");//获取配置下的模块 // foreach (var item in list) // { // SecrietStr pmodel = new SecrietStr(); // pmodel.Id = item.GID; // pmodel.Name = item.DESCRIPTION; // pmodel.Times = smodel.Times; // pmodel.Enabled =true; // toEncrypt = new JavaScriptSerializer().Serialize(pmodel); // secretKey = Common.Common.string_Encrypt(toEncrypt, "2cP46Gox"); // sys_secModule detailmodel = new sys_secModule(); // detailmodel.GID = Guid.NewGuid().ToString(); // detailmodel.ModuleSecretkey = secretKey; // detailmodel.OperUser = operUser; // detailmodel.OperTime = DateTime.Now; // detailmodel.IdenSecretkey = Common.Common.string_Encrypt(pmodel.Id, "2cP46Gox"); // detailmodel.PID = model.GID; // var ymodel = _mbll.GetModelList("IdenSecretkey='" + // Common.Common.string_Encrypt(pmodel.Id, "2cP46Gox") + "' AND PID='" + // model.GID + "'").FirstOrDefault(); // if (ymodel != null) // { // detailmodel.GID = ymodel.GID; // _mbll.Update(detailmodel); // } // else // _mbll.Add(detailmodel); // } //} //catch (Exception e) //{ // result = false; //} } //修改 return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 保存从实例 /// </summary> /// <param name="model"></param> /// <returns></returns> public JsonResult SaveDetail(Model.sys_secModule model) { bool result; //加密算法{模块主键,模块名称,允许使用人数,是否启用} SecrietStr smodel = new SecrietStr(); smodel.Id = Request["SecId"]; smodel.Name = Request["Name"]; smodel.Times = Convert.ToInt32(Request["Times"]); smodel.Enabled = Request["Enabled"] != "0"; var toEncrypt = new JavaScriptSerializer().Serialize(smodel); var secretKey = Common.Common.string_Encrypt(toEncrypt, "2cP46Gox"); if (String.IsNullOrEmpty(model.GID)) { model.GID = Guid.NewGuid().ToString(); model.ModuleSecretkey = secretKey; model.OperUser = Session["SHOWNAME"].ToString(); model.OperTime = DateTime.Now; model.IdenSecretkey = Common.Common.string_Encrypt(smodel.Id, "2cP46Gox"); result = _mbll.Add(model) > 0; } //新增 else { //获取原数据 var oldModel = _mbll.GetModel(model.GID); //类反射 Type type = typeof(Model.sys_secModule); PropertyInfo[] piArr = type.GetProperties(); foreach (var pi in piArr) { if (Array.IndexOf(Request.Params.AllKeys, pi.Name) < 0) pi.SetValue(model, pi.GetValue(oldModel, null), null); } model.ModuleSecretkey = secretKey; model.IdenSecretkey = Common.Common.string_Encrypt(smodel.Id, "2cP46Gox"); model.OperUser = Session["SHOWNAME"].ToString(); model.OperTime = DateTime.Now; result = _mbll.Update(model) > 0; } //修改 return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> public JsonResult Delete(string ids) { bool result = _bll.DeleteListWhere(string.Format("GID in({0})", ids)) > 0; return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> public JsonResult DeleteDetail(string ids) { bool result = _mbll.DeleteListWhere(string.Format("GID in({0})", ids)) > 0; return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 懒加载公司信息 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="query"></param> /// <returns></returns> public JsonResult GetCompanyList(int pageIndex, int pageSize, string query) { StringBuilder where = new StringBuilder(); if (!String.IsNullOrEmpty(query)) where.Append(string.Format("SHORTNAME LIKE '%{0}%' OR CODENAME LIKE '%{0}%' OR DESCRIPTION LIKE '%{0}%'", query)); var list = _cbll.GetModelList(pageIndex, pageSize, where.ToString(), "SHORTNAME collate Chinese_PRC_CS_AS_KS_WS"); var total = _cbll.GetRecordCount(where.ToString()); var result = from p in list select new { id = "{Key:'" + p.GID + "', Value:'" + p.SHORTNAME + "'}", text = p.SHORTNAME }; return Json(new { data = result, total }, JsonRequestBehavior.AllowGet); } /// <summary> /// 获取角色权限范围列表 /// </summary> /// <returns></returns> public JsonResult GetAuthRangeList(string roleid, string sortOrder, string sortName, string search) { user_authority_infoBLL ibll = new user_authority_infoBLL(); StringBuilder where = new StringBuilder(); where.Append("ISDELETE=0"); if (!(String.IsNullOrEmpty(search) || String.IsNullOrWhiteSpace(search))) where.Append(string.Format(" And DESCRIPTION like '%{0}%'", search)); var list = ibll.GetModelList(0,9999,where.ToString(), String.Format("{0} {1}", sortName, sortOrder)); //var list = ibll.GetModelList(string.Format(where + " ORDER BY {0} {1}", sortName, sortOrder)); var result = from p in list select new { AUTHORITYID = p.GID, NAME = p.DESCRIPTION, VISIBLERANGE = 4, OPERATERANGE = 4 }; if (!string.IsNullOrEmpty(roleid)) { user_authority_rangeBLL rbll = new user_authority_rangeBLL(); var list1 = rbll.GetModelList("USERID='" + roleid + "'"); var update = from p in list1 select new { p.GID, p.AUTHORITYID, p.VISIBLERANGE, p.OPERATERANGE, VISIBLERELATION = GetRelation(p.VISIBLERANGE, p.AUTHORITYID, roleid,"vs"), OPERATERELATION = GetRelation(p.OPERATERANGE, p.AUTHORITYID, roleid,"op") }; return Json(new { result, update }); } return Json(new { result, update = new ArrayList() }); } private string GetRelation(int? type, string authority, string roleid,string rangtype) { var israngstr = " and OPERATERANGE=1 "; if (rangtype =="vs") israngstr = " and VISIBLERANGE=1 "; JavaScriptSerializer json = new JavaScriptSerializer(); user_authority_range_companyBLL rcbll = new user_authority_range_companyBLL(); user_authority_range_opBLL robll = new user_authority_range_opBLL(); var obj = new Object(); if (type == 5) { obj = from q in rcbll.GetModelList("USERID='" + roleid + "' AND AUTHORITYID='" + authority + "'"+ israngstr) select new { id = q.COMPANYID, name = "comp" }; } if (type == 6) { obj = from q in robll.GetModelList("USERID='" + roleid + "' AND AUTHORITYID='" + authority + "'"+ israngstr) select new { id = q.OPID, name = "user" }; } return json.Serialize(obj); } /// <summary> /// 获取角色下的权限 /// </summary> /// <param name="pid"></param> /// <returns></returns> public JsonResult GetRoleModuleList(string pid) { sys_moduleBLL bll = new sys_moduleBLL(); StringBuilder where = new StringBuilder(); var list = bll.GetModelList("GID IN (SELECT AuthorityID FROM sys_roleauth WHERE PID='" + pid + "' AND TYPE=1)"); var result = from p in list select new { id = p.GID, name = p.DESCRIPTION, pId = p.PARENTID }; return Json(result); } /// <summary> /// 批量配置模块 /// </summary> /// <param name="companyid"></param> /// <param name="modtype"></param> /// <param name="enabled"></param> /// <returns></returns> public JsonResult SetMod(string companyid, int modtype, bool enabled) { var result = true; try { var cmodel = _bll.GetModel(companyid); CecrietStr cModel = new JavaScriptSerializer().Deserialize<CecrietStr>( Common.Common.string_Decrypt(cmodel.CompanySecretKey, "Dw9pVb9r")); var operUser = Session["SHOWNAME"].ToString(); var list = _ibll.GetModelList("MODTYPE=" + modtype);//获取配置下的模块 foreach (var item in list) { SecrietStr pmodel = new SecrietStr(); pmodel.Id = item.GID; pmodel.Name = item.DESCRIPTION; pmodel.Times = cModel.Times; pmodel.Enabled = enabled; var toEncrypt = new JavaScriptSerializer().Serialize(pmodel); var secretKey = Common.Common.string_Encrypt(toEncrypt, "2cP46Gox"); sys_secModule model = new sys_secModule(); model.GID = Guid.NewGuid().ToString(); model.ModuleSecretkey = secretKey; model.OperUser = operUser; model.OperTime = DateTime.Now; model.IdenSecretkey = Common.Common.string_Encrypt(pmodel.Id, "2cP46Gox"); model.PID = companyid; var ymodel = _mbll.GetModelList("IdenSecretkey='" + Common.Common.string_Encrypt(pmodel.Id, "2cP46Gox") + "' AND PID='" + companyid + "'").FirstOrDefault(); if (ymodel != null) { model.GID = ymodel.GID; _mbll.Update(model); } else _mbll.Add(model); } //设置模块历史 var hisList = cModel.ModHistory; List<string> modHis = new List<string>(); if (!string.IsNullOrEmpty(hisList)) modHis = hisList.Split(',').ToList(); if (enabled) { if (!modHis.Contains(modtype.ToString())) modHis.Add(modtype.ToString()); } else modHis.Remove(modtype.ToString()); cModel.ModHistory = modHis.Count > 0 ? string.Join(",", modHis) : ""; var cecretKey = new JavaScriptSerializer().Serialize(cModel); cmodel.CompanySecretKey = Common.Common.string_Encrypt(cecretKey, "Dw9pVb9r"); _bll.Update(cmodel); } catch (Exception e) { result = false; } return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 获取导出sql /// </summary> /// <param name="ids"></param> /// <returns></returns> public JsonResult GetSql(string ids) { var list = _bll.GetModelList(string.Format("GID in({0})", ids)); return Json(list); } /// <summary> /// 懒加载权限信息 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="query"></param> /// <returns></returns> public JsonResult GetAuthList(int pageIndex, int pageSize, string query) { sys_moduleBLL ibll = new sys_moduleBLL(); StringBuilder where = new StringBuilder(); if (!String.IsNullOrEmpty(query)) where.Append(string.Format("NAME LIKE '%{0}%' OR DESCRIPTION LIKE '%{0}%'", query)); var list = ibll.GetModelList(pageIndex, pageSize, where.ToString(), "DESCRIPTION collate Chinese_PRC_CS_AS_KS_WS"); var total = ibll.GetRecordCount(where.ToString()); var result = from p in list select new { id = p.GID, text = p.DESCRIPTION }; return Json(new { data = result, total }, JsonRequestBehavior.AllowGet); } /// <summary> /// 获取角色列表 /// </summary> /// <param name="startIndex"></param> /// <param name="limit"></param> /// <param name="search"></param> /// <param name="sortName"></param> /// <param name="sortOrder"></param> /// <returns></returns> public JsonResult GetRoleList(int startIndex, int limit, string search, string sortName, string sortOrder) { sys_roleauthBLL mbll = new sys_roleauthBLL(); StringBuilder where = new StringBuilder(); where.Append("Type=0"); if (!(String.IsNullOrEmpty(search) || String.IsNullOrWhiteSpace(search))) where.Append(string.Format(" And Name like '%{0}%'", search)); var list = mbll.GetModelList(startIndex, limit, where.ToString(), String.Format("{0} {1}", sortName, sortOrder)); var count = mbll.GetRecordCount(where.ToString());//总数 return Json(new { total = count, rows = list }); } /// <summary> /// 保存角色 /// </summary> /// <param name="model"></param> /// <returns></returns> public JsonResult SaveRole(sys_roleauth model) { bool result; sys_roleauthBLL mbll = new sys_roleauthBLL(); if (String.IsNullOrEmpty(model.GID)) { model.GID = Guid.NewGuid().ToString(); result = mbll.Add(model) > 0; } //新增 else { //获取原数据 var oldModel = mbll.GetModel(model.GID); //类反射 Type type = typeof(Model.sys_roleauth); PropertyInfo[] piArr = type.GetProperties(); foreach (var pi in piArr) { if (Array.IndexOf(Request.Params.AllKeys, pi.Name) < 0) pi.SetValue(model, pi.GetValue(oldModel, null), null); } result = mbll.Update(model) > 0; } //修改 return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 删除角色 /// </summary> /// <param name="ids"></param> /// <returns></returns> public JsonResult RoleAuthDelete(string ids) { sys_roleauthBLL mbll = new sys_roleauthBLL(); user_authority_rangeBLL rbll = new user_authority_rangeBLL(); user_authority_range_companyBLL rcbll = new user_authority_range_companyBLL(); user_authority_range_opBLL robll = new user_authority_range_opBLL(); bool result = mbll.DeleteListWhere(string.Format("GID in({0})", ids)) > 0; user_roleBLL ubll = new user_roleBLL(); //删除关系表数据 bool result1 = ubll.DeleteListWhere(string.Format("ROLEID in({0})", ids)) > 0; //删除权限范围角色权限关系数据 bool result2 = rbll.DeleteListWhere(string.Format("USERID in({0})", ids)) > 0; //删除公司关联表数据 bool result3 = rcbll.DeleteListWhere(string.Format("USERID in({0})", ids)) > 0; //删除人员关联表数据 bool result4 = robll.DeleteListWhere(string.Format("USERID in({0})", ids)) > 0; return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 复制新建角色 /// </summary> /// <param name="ids"></param> /// <param name="newname"></param> /// <returns></returns> public JsonResult CopyRole(sys_roleauth model) { sys_roleauthBLL mbll = new sys_roleauthBLL(); user_authority_rangeBLL rbll = new user_authority_rangeBLL(); user_authority_range_companyBLL rcbll = new user_authority_range_companyBLL(); user_authority_range_opBLL robll = new user_authority_range_opBLL(); bool result = false; var role = mbll.GetModel(model.GID); ; role.GID = Guid.NewGuid().ToString(); role.Name = model.Name; //return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); //复制新增一条角色信息 result=mbll.Add(role)>0; var oldroleid = model.GID; if (result) { var rolelist = mbll.GetModelList(string.Format("PID= '{0}' ", oldroleid)); foreach (var item in rolelist) { item.GID = Guid.NewGuid().ToString(); item.PID = role.GID; result = mbll.Add(item) > 0; if (!result) break; } } if (result) { //复制增加 权限范围角色权限关系数据 var authority_rangelist = rbll.GetModelList(string.Format("USERID in('{0}')", oldroleid)); foreach (var item in authority_rangelist) { item.GID = Guid.NewGuid().ToString(); item.USERID = role.GID; result=rbll.Add(item)> 0; if (!result) break; } } //公司关联表数据 if (result) { var user_authority_range_companylist = rcbll.GetModelList(string.Format("USERID in('{0}')", oldroleid)); foreach (var item in user_authority_range_companylist) { item.GID = Guid.NewGuid().ToString(); item.USERID = role.GID; result = rcbll.Add(item)>0; if (!result) break; } } //人员关联表数据 if (result) { var user_authority_range_oplist = robll.GetModelList(string.Format("USERID in('{0}')", oldroleid)); foreach (var item in user_authority_range_oplist) { item.GID = Guid.NewGuid().ToString(); item.USERID = role.GID; result = robll.Add(item)>0; if (!result) break; } } return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 删除权限 /// </summary> /// <param name="ids"></param> /// <returns></returns> public JsonResult RoleAuthDelete2(string roleid, string ids) { var module = new Modules.ModuleGridSource(); user_roleBLL ubll = new user_roleBLL(); sys_roleauthBLL mbll = new sys_roleauthBLL(); bool result = mbll.DeleteListWhere(string.Format("PID ='{0}' AND AuthorityID IN({1})", roleid, ids)) > 0; //所有拥有此角色的人员删除该权限 var list = ubll.GetModelList("ROLEID='" + roleid + "'"); string[] delItems = ids.Split(','); foreach (var item in delItems) { foreach (var p in list) module.RemoveUserModule(p.USERID, item.Replace("\'", "")); } return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } /// <summary> /// 获取人员树型 /// </summary> /// <returns></returns> public JsonResult GetUsertreeView() { StringBuilder userBuilder = new StringBuilder(); IList<CompanyEntity> companyEntities = new List<CompanyEntity>(); CompanyDA companyDA = new CompanyDA(); companyEntities = companyDA.GetAllCompany(); if (companyEntities.Count > 0) { userBuilder.Append("["); for (int k = 0; k < companyEntities.Count; k++) { if (k == 0) { userBuilder.Append("{id:\"" + companyEntities[k].GID + "\","); } else { userBuilder.Append(",{id:\"" + companyEntities[k].GID + "\","); } userBuilder.Append("name:\"" + companyEntities[k].NAME + "\",nocheck:false"); IList<SysDeptEntity> sysDeptEntities = new List<SysDeptEntity>(); sysDeptEntities = new SysDeptDA().GetDepartmentByCompanyID(companyEntities[k].GID); if (sysDeptEntities.Count > 0) { userBuilder.Append(",childred:["); for (int j = 0; j < sysDeptEntities.Count; j++) { userBuilder.Append("{id:\"" + sysDeptEntities[j].GID + "\","); userBuilder.Append("name:\"" + sysDeptEntities[j].DEPTNAME + "\",nocheck:false"); IList<UserEntity> userEntities = new List<UserEntity>(); userEntities = new UserDA().GetUserByCompanyAndDept(companyEntities[k].GID, sysDeptEntities[j].DEPTNAME); if (userEntities.Count > 0) { userBuilder.Append(",childred:["); for (int i = 0; i < userEntities.Count; i++) { userBuilder.Append("{id:\"" + userEntities[i].Gid + "\","); userBuilder.Append("name:\"" + userEntities[i].ShowName + "\""); if (i == userEntities.Count - 1) { userBuilder.Append("}"); } else { userBuilder.Append("},"); } } userBuilder.Append("]"); } if (j == sysDeptEntities.Count - 1) { userBuilder.Append("}"); } else { userBuilder.Append("},"); } } userBuilder.Append("]"); } userBuilder.Append("}"); } userBuilder.Append("]"); } return Json(userBuilder.ToString()); } /// <summary> /// 设置角色 /// </summary> /// <param name="userid"></param> /// <param name="roleid"></param> /// <param name="type"></param> /// <returns></returns> public JsonResult SetRole(string userid, string roleid, int type) { sys_roleauthBLL mbll = new sys_roleauthBLL(); var authlist = mbll.GetModelList("Type=1 And PID ='" + roleid + "'"); var module = new Modules.ModuleGridSource(); string msg = ""; try { foreach (var item in authlist) { if (type == 0) { var m = module.RemoveUserModule(userid, item.AuthorityID); if (m != "1") msg += m + "<br/>"; } else { var m = module.AddUserModule(userid, item.AuthorityID); if (m != "1") msg += m + "<br/>"; } } //绑定用户角色表 //dosomething return Json(msg); } catch (Exception se) { return Json(se.Message); } } /// <summary> /// 设置权限范围 /// </summary> /// <param name="userid"></param> /// <param name="roleid"></param> /// <param name="type"></param> /// <param name="view"></param> /// <param name="opera"></param> /// <param name="view_check"></param> /// <param name="opera_check"></param> /// <returns></returns> public void SetRange(string userid, string roleid, int type) { sys_roleauthBLL mbll = new sys_roleauthBLL(); user_authority_rangeBLL arbll = new user_authority_rangeBLL(); user_authority_range_companyBLL rcbll = new user_authority_range_companyBLL(); user_authority_range_opBLL robll = new user_authority_range_opBLL(); arbll.DeleteListWhere("USERID='" + userid + "' "); //删除之前的配置(公司) rcbll.DeleteListWhere("USERID='" + userid + "' "); //删除之前的配置(人员) robll.DeleteListWhere("USERID='" + userid + "' "); user_roleBLL ubll = new user_roleBLL(); var listrole = ubll.GetModelList("USERID='" + userid + "'"); foreach (var role in listrole) { var list = arbll.GetModelList("USERID='" + role.ROLEID + "'"); foreach (var item in list) { SetAuthRange(userid, item.AUTHORITYID, item.VISIBLERANGE, item.OPERATERANGE, role.ROLEID); } } //if (type == 0) //移除角色 //{ // //删除权限范围 type=0 // arbll.DeleteListWhere("USERID='" + userid + "' AND AUTHORITYID in (SELECT AUTHORITYID FROM user_authority_range WHERE USERID='" + roleid + "')"); // //删除之前的配置(公司) // rcbll.DeleteListWhere("USERID='" + userid + "' AND AUTHORITYID in (SELECT AUTHORITYID FROM user_authority_range WHERE USERID='" + roleid + "')"); // //删除之前的配置(人员) // robll.DeleteListWhere("USERID='" + userid + "' AND AUTHORITYID in (SELECT AUTHORITYID FROM user_authority_range WHERE USERID='" + roleid + "')"); // user_roleBLL ubll = new user_roleBLL(); // var listrole = ubll.GetModelList("USERID='" + userid + "'"); // foreach (var role in listrole) // { // var list = arbll.GetModelList("USERID='" + role.ROLEID + "'"); // foreach (var item in list) // { // SetAuthRange(userid, item.AUTHORITYID, item.VISIBLERANGE, item.OPERATERANGE, roleid); // } // } //} //if (type == 1)//添加角色 //{ // //增加权限范围 // var list = arbll.GetModelList("USERID='" + roleid + "'"); // foreach (var item in list) // { // SetAuthRange(userid, item.AUTHORITYID, item.VISIBLERANGE, item.OPERATERANGE, roleid); // } //} } /// <summary> /// 设置单独权限的范围 /// </summary> private void SetAuthRange(string userid, string authority, int? view, int? opera, string roleid) { user_authority_rangeBLL arbll = new user_authority_rangeBLL(); var model = arbll.GetModelList("USERID='" + userid + "' AND AUTHORITYID='" + authority + "'").FirstOrDefault(); if (model != null) { if (model.VISIBLERANGE == 5 || view == 5) model.VISIBLERANGE = 5; else if (model.VISIBLERANGE == 6 || view == 6) model.VISIBLERANGE = 6; else if (model.VISIBLERANGE >= view) model.VISIBLERANGE = view; if (model.OPERATERANGE == 5 || opera == 5) model.OPERATERANGE = 5; else if (model.OPERATERANGE == 6 || opera == 6) model.OPERATERANGE = 6; else if (model.OPERATERANGE >= opera) model.OPERATERANGE = opera; model.MODIFIEDTIME = DateTime.Now; model.MODIFIEDUSER = Session["USERID"].ToString(); arbll.Update(model); } else { model = new user_authority_range(); model.GID = Guid.NewGuid().ToString(); model.USERID = userid; model.AUTHORITYID = authority; model.VISIBLERANGE = view; model.OPERATERANGE = opera; model.CREATEUSER = Session["USERID"].ToString(); model.CREATETIME = DateTime.Now; arbll.Add(model); } var data_view = GetRelation(model.VISIBLERANGE, model.AUTHORITYID, roleid,"vs"); var data_opera = GetRelation(model.OPERATERANGE, model.AUTHORITYID, roleid,"op"); SetCompUser(model.VISIBLERANGE, model.OPERATERANGE, model.AUTHORITYID, model.USERID, data_view, data_opera); } public void SetCompanyRange(string authorityid, string userid, int type, string list) { //var israngstr = " and OPERATERANGE=1 "; //if (type == 0) israngstr = " and VISIBLERANGE=1 "; user_authority_range_companyBLL rcbll = new user_authority_range_companyBLL(); var plist = new JavaScriptSerializer().Deserialize<List<modeuleClass>>(list); foreach (var p in plist) { var umodel = rcbll.GetModelList("USERID='" + userid + "' AND AUTHORITYID='" + authorityid + "' AND COMPANYID='" + p.id + "'").FirstOrDefault(); if (umodel != null) { if (type == 0) umodel.VISIBLERANGE = 1; else umodel.OPERATERANGE = 1; umodel.MODIFIEDTIME = DateTime.Now; umodel.MODIFIEDUSER = Session["USERID"].ToString(); rcbll.Update(umodel); } else { umodel = new user_authority_range_company(); umodel.GID = Guid.NewGuid().ToString(); umodel.USERID = userid; umodel.AUTHORITYID = authorityid; umodel.COMPANYID = p.id; if (type == 0) { umodel.VISIBLERANGE = 1; umodel.OPERATERANGE = 0; } else { umodel.VISIBLERANGE = 0; umodel.OPERATERANGE = 1; } umodel.CREATETIME = DateTime.Now; umodel.CREATEUSER = Session["USERID"].ToString(); rcbll.Add(umodel); } } } /// <summary> /// 保存角色权限配置 /// </summary> /// type:0 - 角色权限 1:角色权限范围 /// <returns></returns> public void SetUserRange(string authorityid, string userid, int type, string list) { //var sqlstr = " update user_authority_range_op set OPERATERANGE=0 where USERID = '" + userid + "' AND AUTHORITYID = '" + authorityid + "'"; //if (type == 0) sqlstr = " update user_authority_range_op set VISIBLERANGE=0 where USERID = '" + userid + "' AND AUTHORITYID = '" + authorityid + "'"; //var _r = BasicDataRefDAL.ExecSql(sqlstr); user_authority_range_opBLL robll = new user_authority_range_opBLL(); var omodellist = robll.GetModelList("USERID='" + userid + "' AND AUTHORITYID='" + authorityid + "'"); var qlist = new JavaScriptSerializer().Deserialize<List<modeuleClass>>(list); foreach (var p in qlist) { var omodel = omodellist.Find(t => t.OPID == p.id); if (omodel != null) { if (type == 0) omodel.VISIBLERANGE = 1; else omodel.OPERATERANGE = 1; omodel.MODIFIEDTIME = DateTime.Now; omodel.MODIFIEDUSER = Session["USERID"].ToString(); robll.Update(omodel); } else { omodel = new user_authority_range_op(); omodel.GID = Guid.NewGuid().ToString(); omodel.USERID = userid; omodel.AUTHORITYID = authorityid; omodel.OPID = p.id; if (type == 0) { omodel.VISIBLERANGE = 1; omodel.OPERATERANGE = 0; } else { omodel.VISIBLERANGE = 0; omodel.OPERATERANGE = 1; } omodel.CREATETIME = DateTime.Now; omodel.CREATEUSER = Session["USERID"].ToString(); robll.Add(omodel); } } } /// <summary> /// 角色添加权限 /// </summary> /// <param name="roleid"></param> /// <param name="modulelist"></param> /// <returns></returns> public JsonResult SaveRoleAuth(string roleid, string modulelist) { var module = new Modules.ModuleGridSource(); sys_roleauthBLL mbll = new sys_roleauthBLL(); user_roleBLL ubll = new user_roleBLL(); try { var data = new JavaScriptSerializer().Deserialize<List<modeuleClass>>(modulelist); var list = ubll.GetModelList("ROLEID='" + roleid + "'"); //20200225 首先检查拥有该角色的所有人 能否获得该权限范围 var useridlist = ""; foreach (var user in list) { if (useridlist != "") useridlist += ","; useridlist += user.GID; } var checkresult = SysUserDAL.CheckOPRange(data, useridlist); if (!checkresult.Success) { return Json(new { success = false, msg = checkresult.Message }); } foreach (var item in data) { sys_roleauth model = new sys_roleauth(); model.GID = Guid.NewGuid().ToString(); model.AuthorityID = item.id;//模块id model.Name = item.name; model.PID = roleid; model.Type = 1;//一般权限 mbll.Add(model); //所有拥有此角色的人员添加该权限 foreach (var p in list) module.AddUserModule(p.USERID, item.id); } return Json(new { success = true }); } catch (Exception se) { return Json(new { success = false, msg = se.Message }); } } //获取全部角色 public JsonResult GetRoleView() { sys_roleauthBLL mbll = new sys_roleauthBLL(); StringBuilder where = new StringBuilder(); where.Append("Type=0"); var list = mbll.GetModelList(where.ToString()); var result = from p in list select new { id = p.GID, name = p.Name }; return Json(result); } /// <summary> /// 获取人员对应的角色 /// </summary> /// <param name="userid"></param> /// <returns></returns> public JsonResult GetUserRoleChecked(string userid) { sys_roleauthBLL mbll = new sys_roleauthBLL(); StringBuilder where = new StringBuilder(); where.Append(string.Format("Type=0 and GID in (SELECT ROLEID FROM USER_ROLE WHERE USERID ='{0}')", userid)); var list = mbll.GetModelList(where.ToString()); var result = from p in list select new { id = p.GID, name = p.Name }; return Json(result); } /// <summary> /// 保存用户角色 /// </summary> /// <param name="userid"></param> /// <param name="rolelist"></param> /// <returns></returns> public JsonResult SaveUserRole(string userid, string rolelist, int type) { user_roleBLL ubll = new user_roleBLL(); try { var data = new JavaScriptSerializer().Deserialize<List<modeuleClass>>(rolelist); foreach (var item in data) { user_role model = new user_role(); model.GID = Guid.NewGuid().ToString(); model.ROLEID = item.id; model.USERID = userid; switch (type) { case 1://添加角色 ubll.Add(model); //加权限 SetRole(userid, item.id, 1); ////修改权限范围 //SetRange(userid, item.id, 1); break; case 0://移除角色 ubll.DeleteListWhere(string.Format("USERID='{0}' AND ROLEID='{1}'", userid, item.id)); ////移除权限 SetRole(userid, item.id, 0); ////恢复默认权限范围 //SetRange(userid, item.id, 0); break; } } SetRange(userid,"", 1); return Json(new { success = true }); } catch (Exception se) { return Json(new { success = false, msg = se.Message }); } } /// <summary> /// 获取公司列表 /// </summary> /// <returns></returns> public JsonResult GetCompanyList1() { companyBLL cbll = new companyBLL(); var result = from p in cbll.GetModelList("") select new { id = p.GID, name = p.NAME }; return Json(result); } /// <summary> /// 保存权限范围 /// </summary> /// <returns></returns> public JsonResult SaveAuthByRole(user_authority_range model) { user_authority_rangeBLL rbll = new user_authority_rangeBLL(); bool result; if (String.IsNullOrEmpty(model.GID)) { model.GID = Guid.NewGuid().ToString(); model.CREATEUSER = Session["SHOWNAME"].ToString(); model.CREATETIME = DateTime.Now; result = rbll.Add(model) > 0; } //新增 else { //获取原数据 var oldModel = rbll.GetModel(model.GID); //类反射 Type type = typeof(Model.user_authority_range); PropertyInfo[] piArr = type.GetProperties(); foreach (var pi in piArr) { if (Array.IndexOf(Request.Params.AllKeys, pi.Name) < 0) pi.SetValue(model, pi.GetValue(oldModel, null), null); } model.MODIFIEDUSER = Session["SHOWNAME"].ToString(); model.MODIFIEDTIME = DateTime.Now; result = rbll.Update(model) > 0; } //修改 //设置角色对应的权限范围 var data_view = Request["VISIBLERELATION"]; var data_opera = Request["OPERATERELATION"]; SetCompUser(model.VISIBLERANGE, model.OPERATERANGE, model.AUTHORITYID, model.USERID, data_view, data_opera); //获取该角色下的人员并修改权限范围 user_roleBLL bll = new user_roleBLL(); var list = bll.GetModelList("ROLEID='" + model.USERID + "'"); foreach (var item in list) SetAuthRange(item.USERID, model.AUTHORITYID, model.VISIBLERANGE, model.OPERATERANGE, model.USERID); return Json(new { success = result, message = result ? "操作成功" : "操作失败" }); } private void SetCompUser(int? view, int? opera, string authority, string userid, string data_view, string data_opera) { //可视范围(保存人员) if (view == 5) SetCompanyRange(authority, userid, 0, data_view); if (view == 6) SetUserRange(authority, userid, 0, data_view); //操作范围(保存人员) if (opera == 5) SetCompanyRange(authority, userid, 1, data_opera); if (opera == 6) SetUserRange(authority, userid, 1, data_opera); } /// <summary> /// 保存权限范围 /// </summary> /// <returns></returns> public JsonResult SaveAuthByRoleMulti(string jsonStr) { var jsonObj = JsonConvert.DeserializeObject<List<user_authority_range_multi_set>>(jsonStr); user_authority_rangeBLL rbll = new user_authority_rangeBLL(); bool result; foreach (var model in jsonObj) { if (String.IsNullOrEmpty(model.GID)) { model.GID = Guid.NewGuid().ToString(); model.CREATEUSER = Session["SHOWNAME"].ToString(); model.CREATETIME = DateTime.Now; result = rbll.Add(model) > 0; } //新增 else { //获取原数据 var oldModel = rbll.GetModel(model.GID); ////类反射 //Type type = typeof(Model.user_authority_range); //PropertyInfo[] piArr = type.GetProperties(); //foreach (var pi in piArr) //{ // if (Array.IndexOf(Request.Params.AllKeys, pi.Name) < 0) // pi.SetValue(model, pi.GetValue(oldModel, null), null); //} model.CREATETIME = oldModel.CREATETIME; model.CREATEUSER = oldModel.CREATEUSER; model.MODIFIEDUSER = Session["SHOWNAME"].ToString(); model.MODIFIEDTIME = DateTime.Now; result = rbll.Update(model) > 0; } //修改 //设置角色对应的权限范围 var data_view = model.VISIBLERELATION; var data_opera = model.OPERATERELATION; SetCompUser(model.VISIBLERANGE, model.OPERATERANGE, model.AUTHORITYID, model.USERID, data_view, data_opera); //获取该角色下的人员并修改权限范围 user_roleBLL bll = new user_roleBLL(); var list = bll.GetModelList("ROLEID='" + model.USERID + "'"); foreach (var item in list) SetAuthRange(item.USERID, model.AUTHORITYID, model.VISIBLERANGE, model.OPERATERANGE, model.USERID); } return Json(new { success = true, message = "操作成功" }); } #endregion public bool SetRoleAuthRange() { var result = true; return result; } public ContentResult CopyAuth(string FromUSERID, string ToUSERIDLIST) { DBResult result = new DBResult(); if (string.IsNullOrWhiteSpace(FromUSERID) || string.IsNullOrWhiteSpace(ToUSERIDLIST)) { var jsonRespose1 = new MvcShipping.Helper.JsonResponse { Success = false, Message = "请正确选择权限来源用户和目标用户", Data = "" }; return new ContentResult() { Content = MvcShipping.Helper.JsonConvert.Serialize(jsonRespose1) }; } var useridlist = ToUSERIDLIST.Split(','); //20200221 首先获取来源用户的所有模块ID列表 var useractionbll = new user_actionBLL(); var useractionlist = useractionbll.GetModelList(" userid='"+ FromUSERID + "' and exists(select 1 from [action] where gid=ACTIONID)"); var checkcando = new DBResult(true, "", null); //逐个权限进行判断 看这次能否添加得上 foreach (var module in useractionlist) { checkcando = SysUserDAL.CheckOPRangeByActionID(module.ACTIONID, ToUSERIDLIST); if (!checkcando.Success) { result.SetErrorInfo(checkcando.Message); } } //如不能 则返回所有引起错误的信息 if (!string.IsNullOrWhiteSpace(result.Message) && !result.Success) { var jsonRespose1 = new MvcShipping.Helper.JsonResponse { Success = false, Message = result.Message, Data = "" }; return new ContentResult() { Content = MvcShipping.Helper.JsonConvert.Serialize(jsonRespose1) }; } //对权限进行设置 StringBuilder sqlstrbase = new StringBuilder(); sqlstrbase.Append("declare @USERID varchar(50) "); sqlstrbase.Append("declare @CREATEUSER varchar(50) "); sqlstrbase.Append("declare @FROMUSER varchar(50) "); sqlstrbase.Append("set @USERID='{0}' "); sqlstrbase.Append("set @CREATEUSER='{1}' "); sqlstrbase.Append("set @FROMUSER = '{2}' "); sqlstrbase.Append("delete from user_action where USERID=@USERID "); sqlstrbase.Append("insert into user_action (GID,ACTIONID,USERID,CREATEUSER,CREATETIME,MODIFIEDUSER,MODIFIEDTIME) "); sqlstrbase.Append("select newid(),actionid,@USERID,@CREATEUSER,getdate(),@CREATEUSER,getdate() from user_action where userid = @FROMUSER "); sqlstrbase.Append("delete from user_authority_range where USERID=@USERID "); sqlstrbase.Append("insert into user_authority_range (GID,USERID,AUTHORITYID,VISIBLERANGE,OPERATERANGE,CREATEUSER,CREATETIME,MODIFIEDUSER,MODIFIEDTIME) "); sqlstrbase.Append("select newid(),@USERID,AUTHORITYID,VISIBLERANGE,OPERATERANGE,@CREATEUSER,getdate(),@CREATEUSER,getdate() from user_authority_range where userid = @FROMUSER "); sqlstrbase.Append("delete from user_authority_range_op where USERID=@USERID "); sqlstrbase.Append("insert into user_authority_range_op (GID,USERID,AUTHORITYID,OPID,OPNAME,VISIBLERANGE,OPERATERANGE,CREATEUSER,CREATETIME,MODIFIEDUSER,MODIFIEDTIME) "); sqlstrbase.Append("select newid(),@USERID,AUTHORITYID,OPID,OPNAME,VISIBLERANGE,OPERATERANGE,@CREATEUSER,getdate(),@CREATEUSER,getdate() from user_authority_range_op where userid = @FROMUSER "); sqlstrbase.Append("delete from user_authority_range_company where USERID=@USERID "); sqlstrbase.Append("insert into user_authority_range_company (GID,USERID,AUTHORITYID,COMPANYID,VISIBLERANGE,OPERATERANGE,CREATEUSER,CREATETIME,MODIFIEDUSER,MODIFIEDTIME) "); sqlstrbase.Append("select newid(),@USERID,AUTHORITYID,COMPANYID,VISIBLERANGE,OPERATERANGE,@CREATEUSER,getdate(),@CREATEUSER,getdate() from user_authority_range_company where userid = @FROMUSER "); foreach (var userid in useridlist) { string sqlstr = string.Format(sqlstrbase.ToString(), userid,Session["USERID"].ToString(), FromUSERID); var _r = BasicDataRefDAL.ExecSql(sqlstr); if (_r == -1) { var jsonRespose2 = new MvcShipping.Helper.JsonResponse { Success = true, Message = "设置错误,请联系管理员!", Data = "" }; return new ContentResult() { Content = MvcShipping.Helper.JsonConvert.Serialize(jsonRespose2) }; } } var jsonRespose = new MvcShipping.Helper.JsonResponse { Success = true, Message = "设置完成", Data = "" }; return new ContentResult() { Content = MvcShipping.Helper.JsonConvert.Serialize(jsonRespose) }; } } public class modeuleClass { public string id { get; set; } public string name { get; set; } } }