using System; using System.Linq; using System.Web.Mvc; namespace WX.CRM.WebHelper { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthorizeToolBar : AuthorizeAttribute { private const string IS_AUTHORIZED = "isAuthorized"; public string RedirectUrl = "~/Base/Account/UnAuthorized"; private string _rightId; private int _toolBarId; private string[] m_roles; private MenuLogHelper menuLogHelper; public AuthorizeToolBar() { this.m_roles = UserRightsHelper.getUserRights(); if (menuLogHelper == null) menuLogHelper = new MenuLogHelper(); } public AuthorizeToolBar(string rightId, int toolBarId) { this._rightId = rightId; this._toolBarId = toolBarId; if (menuLogHelper == null) menuLogHelper = new MenuLogHelper(); } protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { this.m_roles = UserRightsHelper.getUserRights(); bool isAuthorized = this.isAuthorizeCore(httpContext); httpContext.Items.Add(IS_AUTHORIZED, isAuthorized); return isAuthorized; } private bool isAuthorizeCore(System.Web.HttpContextBase httpContext) { bool IsAuthenticated = httpContext.User.Identity.IsAuthenticated; if (!IsAuthenticated) { return false; } if (!string.IsNullOrEmpty(this._rightId) && this._toolBarId > 0 && !this.IsRoleToolBar(this._rightId, this._toolBarId)) { return false; } return true; } private bool IsRoleToolBar(string role, int toobar) { int outInt = 0; if ((role != null) && (this.m_roles != null)) { string[] rolesRights = this.m_roles.Where(p => p.Contains(role)).ToArray(); for (int i = 0; i < rolesRights.Length; i++) { if ((rolesRights[i] != null) && (rolesRights[i].Length > 4) && (string.Compare(rolesRights[i], 0, role, 0, 4, StringComparison.OrdinalIgnoreCase) == 0) && int.TryParse(rolesRights[i].Substring(4), out outInt) && (outInt & toobar) > 0) { return true; } } } return false; } public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); var isAuthorized = filterContext.HttpContext.Items[IS_AUTHORIZED] != null ? Convert.ToBoolean(filterContext.HttpContext.Items[IS_AUTHORIZED]) : false; if (!isAuthorized && filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.RequestContext.HttpContext.Response.Redirect(RedirectUrl + "?type=button"); } //记录方法埋点 menuLogHelper.AddMenuLog(); } public string RightId { get { return (this._rightId ?? string.Empty); } set { this._rightId = value; } } public int TooBarId { get { return this._toolBarId; } set { this._toolBarId = value; } } } }