BaseController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using log4net.Ext;
  7. using Ant.Service.Common;
  8. using System.Collections;
  9. using Ant.Service.Common.Enums;
  10. using Central.Control.Domain;
  11. using MES.Production.Service.IService;
  12. using MES.Production.Service;
  13. namespace ChangFa.Machinery.WebPage.Controllers
  14. {
  15. /// <summary>
  16. /// 控制器基类,主要做登录用户、权限认证、日志记录等工作
  17. /// add 作者: 季健国 QQ:181589805 by 2016-05-30
  18. /// </summary>
  19. public class BaseController : Controller
  20. {
  21. #region 公用变量
  22. /// <summary>
  23. /// 查询关键词
  24. /// </summary>
  25. public string keywords { get; set; }
  26. /// <summary>
  27. /// 视图传递的分页页码
  28. /// </summary>
  29. public int page { get; set; }
  30. /// <summary>
  31. /// 视图传递的分页条数
  32. /// </summary>
  33. public int pagesize { get; set; }
  34. /// <summary>
  35. /// 用户容器,公用
  36. /// </summary>
  37. public IUserManage UserManage = Spring.Context.Support.ContextRegistry.GetContext().GetObject("MES.Production.Service.User") as IUserManage;
  38. /// <summary>
  39. /// 系统ID,很重要
  40. /// </summary>
  41. public string siteId = System.Configuration.ConfigurationManager.AppSettings["siteid"].ToString();
  42. #endregion
  43. #region 用户对象
  44. /// <summary>
  45. /// 获取当前用户对象
  46. /// </summary>
  47. public Account CurrentUser
  48. {
  49. get
  50. {
  51. if (SessionHelper.GetSession("CurrentUser") != null)
  52. {
  53. return SessionHelper.GetSession("CurrentUser") as Account;
  54. }
  55. var account = UserManage.GetAccountByCookie();
  56. SessionHelper.SetSession("CurrentUser", account);
  57. return account;
  58. }
  59. }
  60. #endregion
  61. /// <summary>
  62. /// 登录验证
  63. /// </summary>
  64. protected override void OnActionExecuting(ActionExecutingContext filterContext)
  65. {
  66. #region 登录用户验证
  67. //1、判断Session对象是否存在
  68. if (filterContext.HttpContext.Session == null)
  69. {
  70. filterContext.HttpContext.Response.Write(
  71. " <script type='text/javascript'> alert('~登录已过期,请重新登录');window.top.location='/'; </script>");
  72. filterContext.RequestContext.HttpContext.Response.End();
  73. filterContext.Result = new EmptyResult();
  74. return;
  75. }
  76. //2、登录验证
  77. if (this.CurrentUser == null)
  78. {
  79. filterContext.HttpContext.Response.Write(
  80. " <script type='text/javascript'> alert('登录已过期,请重新登录'); window.top.location='/';</script>");
  81. filterContext.RequestContext.HttpContext.Response.End();
  82. filterContext.Result = new EmptyResult();
  83. return;
  84. }
  85. #endregion
  86. #region 公共Get变量
  87. //分页页码
  88. object p = filterContext.HttpContext.Request["page"];
  89. if (p == null || p.ToString() == "") { page = 1; } else { page = int.Parse(p.ToString()); }
  90. //搜索关键词
  91. string search = filterContext.HttpContext.Request.QueryString["Search"];
  92. if (!string.IsNullOrEmpty(search)) { keywords = search; }
  93. //显示分页条数
  94. string size = filterContext.HttpContext.Request.QueryString["example_length"];
  95. if (!string.IsNullOrEmpty(size) && System.Text.RegularExpressions.Regex.IsMatch(size.ToString(), @"^\d+$")) { pagesize = int.Parse(size.ToString()); } else { pagesize = 10; }
  96. #endregion
  97. base.OnActionExecuting(filterContext);
  98. }
  99. #region log4net日志
  100. /// <summary>
  101. /// 统一日志变量
  102. /// </summary>
  103. protected static IExtLog _log = ExtLogManager.GetLogger("dblog");
  104. /// <summary>
  105. /// 操作日志
  106. /// </summary>
  107. public void WriteLog(enumOperator action, string message, enumLog4net logLevel)
  108. {
  109. switch (logLevel)
  110. {
  111. case enumLog4net.INFO:
  112. _log.Info(Utils.GetIP(), this.CurrentUser.Name, Request.Url.ToString(), action.ToString(), message);
  113. break;
  114. case enumLog4net.WARN:
  115. _log.Warn(Utils.GetIP(), this.CurrentUser.Name, Request.Url.ToString(), action.ToString(), message);
  116. break;
  117. default:
  118. _log.Error(Utils.GetIP(), this.CurrentUser.Name, Request.Url.ToString(), action.ToString(), message);
  119. break;
  120. }
  121. }
  122. /// <summary>
  123. /// 异常日志
  124. /// </summary>
  125. public void WriteLog(enumOperator action, string message, Exception e)
  126. {
  127. _log.Fatal(Utils.GetIP(), this.CurrentUser.Name, Request.Url.ToString(), action.ToString(), message, e);
  128. }
  129. #endregion
  130. #region 输出消息
  131. /// <summary>
  132. /// 输出JSON消息
  133. /// </summary>
  134. /// <param name="obj">泛型对象</param>
  135. public void PrintMessage(object obj)
  136. {
  137. System.Web.HttpContext Context = System.Web.HttpContext.Current;
  138. Context.Response.Charset = "UTF-8"; //设置字符集类型
  139. Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
  140. Context.Response.Write(JsonConverter.Serialize(obj));
  141. System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
  142. }
  143. /// <summary>
  144. /// 输出纯字符串消息
  145. /// </summary>
  146. /// <param name="str">字符串</param>
  147. public void PrintMessage(string str)
  148. {
  149. System.Web.HttpContext Context = System.Web.HttpContext.Current;
  150. Context.Response.Charset = "UTF-8"; //设置字符集类型
  151. Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
  152. Context.Response.Write(str);
  153. System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
  154. }
  155. #endregion
  156. }
  157. /// <summary>
  158. /// 模块权限验证功能
  159. /// 规则:1、根据模块别名验证对应模块
  160. /// 2、根据模块操作Action 验证是否可操作按钮
  161. /// add 作者: 季健国 QQ:181589805 by 2016-05-30
  162. /// </summary>
  163. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
  164. public class UserAuthorizeAttribute : AuthorizeAttribute
  165. {
  166. #region 字段和属性
  167. /// <summary>
  168. /// 模块别名,可配置更改
  169. /// </summary>
  170. public string ModuleAlias { get; set; }
  171. /// <summary>
  172. /// 权限动作
  173. /// </summary>
  174. public string OperaAction { get; set; }
  175. /// <summary>
  176. /// 权限访问控制器参数
  177. /// </summary>
  178. private string Sign { get; set; }
  179. /// <summary>
  180. /// 基类实例化
  181. /// </summary>
  182. public BaseController baseController = new BaseController();
  183. #endregion
  184. #region 权限认证
  185. /// <summary>
  186. /// 权限认证
  187. /// </summary>
  188. public override void OnAuthorization(AuthorizationContext filterContext)
  189. {
  190. //1、判断模块是否对应
  191. if (string.IsNullOrEmpty(ModuleAlias))
  192. {
  193. filterContext.HttpContext.Response.Write(" <script type='text/javascript'>alert('^登录已过期,请重新登录!'); </script>");
  194. filterContext.RequestContext.HttpContext.Response.End();
  195. filterContext.Result = new EmptyResult();
  196. return;
  197. }
  198. //2、判断用户是否存在
  199. if (baseController.CurrentUser == null)
  200. {
  201. filterContext.HttpContext.Response.Write(" <script type='text/javascript'> alert('^没有当前操作权限!');window.top.location='/'; </script>");
  202. filterContext.RequestContext.HttpContext.Response.End();
  203. filterContext.Result = new EmptyResult();
  204. return;
  205. }
  206. //对比变量,用于权限认证
  207. var alias = ModuleAlias;
  208. #region 配置Sign调取控制器标识
  209. Sign = filterContext.RequestContext.HttpContext.Request.QueryString["sign"];
  210. if (!string.IsNullOrEmpty(Sign))
  211. {
  212. if (("," + ModuleAlias.ToLower()).Contains("," + Sign.ToLower()))
  213. {
  214. alias = Sign;
  215. filterContext.Controller.ViewData["Sign"] = Sign;
  216. }
  217. }
  218. #endregion
  219. //3、调用下面的方法,验证是否有访问此页面的权限,查看加操作
  220. var moduleId = baseController.CurrentUser.Modules.Where(p => p.ALIAS.ToLower() == alias.ToLower()).Select(p => p.ID).FirstOrDefault();
  221. bool _blAllowed = this.IsAllowed(baseController.CurrentUser, moduleId, OperaAction);
  222. if (!_blAllowed)
  223. {
  224. filterContext.HttpContext.Response.Write(" <script type='text/javascript'> alert('^没有当前操作权限!');</script>");
  225. filterContext.RequestContext.HttpContext.Response.End();
  226. filterContext.Result = new EmptyResult();
  227. return;
  228. }
  229. //4、有权限访问页面,将此页面的权限集合传给页面
  230. filterContext.Controller.ViewData["PermissionList"] = GetPermissByJson(baseController.CurrentUser, moduleId);
  231. }
  232. /// <summary>
  233. /// 获取操作权限Json字符串,供视图JS判断使用
  234. /// </summary>
  235. string GetPermissByJson(Account account, int moduleId)
  236. {
  237. //操作权限
  238. var _varPerListThisModule = account.Permissions.Where(p => p.MODULEID == moduleId).Select(R => new { R.PERVALUE }).ToList();
  239. return JsonConverter.Serialize(_varPerListThisModule);
  240. }
  241. /// <summary>
  242. /// 功能描述:判断用户是否有此模块的操作权限
  243. /// </summary>
  244. bool IsAllowed(Account user, int moduleId, string action)
  245. {
  246. //判断入口
  247. if (user == null || user.Id <= 0 || moduleId == 0 || string.IsNullOrEmpty(action)) return false;
  248. //验证权限
  249. var permission = user.Permissions.Where(p => p.MODULEID == moduleId);
  250. action = action.Trim(',');
  251. if (action.IndexOf(',') > 0)
  252. {
  253. permission = permission.Where(p => action.ToLower().Contains(p.PERVALUE.ToLower()));
  254. }
  255. else
  256. {
  257. permission = permission.Where(p => p.PERVALUE.ToLower() == action.ToLower());
  258. }
  259. return permission.Any();
  260. }
  261. #endregion
  262. }
  263. /// <summary>
  264. /// 模块去重,非常重要
  265. /// add 作者: 季健国 QQ:181589805 by 2016-08-03
  266. /// </summary>
  267. public class ModuleDistinct : IEqualityComparer<SYS_MODULE>
  268. {
  269. public bool Equals(SYS_MODULE x, SYS_MODULE y)
  270. {
  271. return x.ID == y.ID;
  272. }
  273. public int GetHashCode(SYS_MODULE obj)
  274. {
  275. return obj.ToString().GetHashCode();
  276. }
  277. }
  278. }