using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Filters; using System.Data; using System.Runtime.CompilerServices; using YLErp.Web.App.Auth; namespace YLErp.Web { [Authorize(policy: "yc_identity")] public class BaseController : Controller { protected const string xlsxMimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; YLContext _yldb; ClientDBContext _clientdb; protected YLContext yldb { get { return _yldb ?? (_yldb = new YLContext()); } } protected ClientDBContext clientDB { get { return _clientdb ?? (_clientdb = DbContextFactory.GetClientDbContext(CurUser)); } } #region----用户信息---- /// /// 当前系统用户ID /// protected int UserId => CurUser.UserId; /// /// 当前系统用户名 /// protected string UserName => CurUser.UserName; UserInfo _curUser; protected UserInfo CurUser { get { if (User.Identity.IsAuthenticated) { if (_curUser != null) { return _curUser; } _curUser = Server.CacheProvider.Get("loginUser^" + HttpContext.User.GetUserId()) as UserInfo; if (_curUser != null) { _curUser.UserFrom = OptUserFrom.WebUI; return _curUser; } } return new UserInfo { UserName = "系统", UserFrom = OptUserFrom.WebUI }; } } /// /// 用户关联的簿记账户ID列表 /// protected List GetUserAssetunitIds() => CurUser.GetAssetUnitIds(); /// /// 是否有权限查看所有交易 /// protected bool ShowAllTrades { get { return CurUser.交易管理_查看所有交易; } } #endregion #region----JSON数据返回---- /// /// 返回jqgrid认识的数据 /// protected JsonResult JsonForJqGrid(IPagedList pagedList, string msg = null) where T : class { if (pagedList is null) { return Json(new SearchListResult { Msg = msg, page = 1 }); } return Json(new SearchListResult { Msg = msg, rows = pagedList.Items, total = pagedList.TotalPages(), page = pagedList.PageIndex, records = pagedList.TotalCount }); } /// /// 返回成功的消息 /// protected JsonResult JsonSuccessMessage(string message) { return Json(new Result() { success = true, msg = message }); } /// /// 返回成功的消息数据 /// protected JsonResult JsonSuccessData(object data) { return Json(new Result() { success = true, obj = data }); } /// /// 返回成功的消息 /// protected JsonResult JsonSuccess(string message = null, object data = null) { return Json(new Result() { success = true, msg = message, obj = data }); } protected JsonResult JsonError(string message = null, object data = null) { return Json(new Result() { success = false, msg = message, obj = data }); } #endregion #region----视图数据返回---- protected ActionResult NoRightPage() { return new ContentResult { Content = "您无权访问此页面。", ContentType = "text/plain; charset=utf-8" }; } protected ViewResult ShowError(ShowErrorModel model) { if (model is null) { throw new ArgumentNullException(nameof(model)); } return View("ShowError", model); } protected ViewResult ShowError(string errMsg, string title = null) { return View("ShowError", new ShowErrorModel { ErrorMsg = errMsg, Title = title }); } #endregion #region---底层重写---- protected override void Dispose(bool disposing) { _yldb?.Dispose(); _clientdb?.Dispose(); base.Dispose(disposing); } public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); if (context.Controller is Controllers.HomeController) { return; } var hasAllowAnonymous = ValidateAllowAnonymous(context); if (hasAllowAnonymous) { return; } var hasRight = false; var isAjaxRequest = Request.Headers["X-Requested-With"] == "XMLHttpRequest"; var typedHeaders = Request.GetTypedHeaders(); if (CurUser.UserId > 0 && (!isAjaxRequest || typedHeaders.Referer != null)) { var custAttrs = context.ActionDescriptor.EndpointMetadata.OfType().ToArray(); if (custAttrs.Any()) { hasRight = custAttrs.Any(n => n.HasRight(CurUser)); } else if (PS.Config.ErpElement.StrictAuthorize) { if (MyAuthorizeHelper.CanIgnore(context.Controller.GetType())) { hasRight = true; } else if (typedHeaders.Referer != null) { hasRight = MyAuthorizeHelper.HasRight(CurUser, isAjaxRequest, Request.Path, typedHeaders.Referer.AbsolutePath); } else { hasRight = true; //这里是没有权限设定的页面 } } else { hasRight = true; } } if (!hasRight) //未授权处理 { if (isAjaxRequest) { context.Result = new JsonResult(new Result { success = false, msg = "没有权限" }); } else { context.Result = NoRightPage(); } } else { //拦截会导致安全隐患的上传文件类型 if (Request.HasFormContentType && Request.Form.Files.Count > 0) { context.Result = ValidUploadFiles(Request.Form.Files, isAjaxRequest); if (context.Result != null) { return; } } if (!isAjaxRequest && Request.Method == "GET") { //已授权设置当前菜单 var curpass = Request.Path; foreach (var p in AppHelper.Menus) { var subMenu = p.SubItems.FirstOrDefault(sm => sm.Url == curpass); if (subMenu != null) { ViewBag.Menu = $"{p.Name}-{subMenu.Name}"; break; } } } } } private ActionResult ValidUploadFiles(IFormFileCollection files, bool isAjaxRequest) { string[] accepts = null; var str = PS.Config.ErpElement.UploadFileAccepts.TrimToNull(); if (!string.IsNullOrEmpty(str)) { accepts = str.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries) .Where(n => !string.IsNullOrWhiteSpace(n)).Select(n => n.Trim()).ToArray(); if (!accepts.Any()) { accepts = null; } } var disableSet = new HashSet(StringComparer.OrdinalIgnoreCase); for (var i = 0; i < files.Count; i++) { var fname = files[i].FileName; if (fname.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) { disableSet.Add(".aspx"); } else if (accepts != null && !accepts.Any(n => fname.EndsWith(n, StringComparison.OrdinalIgnoreCase))) { disableSet.Add(System.IO.Path.GetExtension(fname)); } } if (disableSet.Any()) { var fextStr = string.Join(",", disableSet); var message = $"禁止上传{fextStr}类型的文件"; if (isAjaxRequest) { return new JsonResult(new Result { success = false, msg = message }); } return new ContentResult { Content = message, ContentType = "text/plain" }; } return null; } /// /// 验证是否无需登录 /// /// /// private bool ValidateAllowAnonymous(ActionExecutingContext context) { if (context.ActionDescriptor!=null) { var custAttrs = context.ActionDescriptor.EndpointMetadata.OfType().ToArray(); if (custAttrs.Any()) { return true; } } return false; } #endregion [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static int DecryptInt(string enid) { return DataProtectHelper.DecryptInt(enid); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static long DecryptLong(string enid) { return DataProtectHelper.DecryptLong(enid); } } }