using Autofac; using GreenTree.Nachtragsmanagement.Core; using GreenTree.Nachtragsmanagement.Core.Authentication; using GreenTree.Nachtragsmanagement.Services.User; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace GreenTree.Nachtragsmanagement.Web.Framework.Authorization { public class RoleAuthorizeAttribute : AuthorizeAttribute { #region Fields private readonly IAuthenticationService _authenticationService; private readonly IUserHelper _userHelper; private readonly string[] _allowedFunctions; #endregion /// /// Initializes a new instance of the RoleAuthorizeAttribute class /// /// The functions needed. public RoleAuthorizeAttribute(params string[] functions) { _allowedFunctions = functions; _authenticationService = Singleton.Instance.Resolve(); _userHelper = Singleton.Instance.Resolve(); } protected override bool AuthorizeCore(HttpContextBase httpContext) { var user = _userHelper.FromCookies(); if (user == null) return false; foreach (var role in user.Roles) { foreach (var function in role.Functions) { var allowed = _allowedFunctions.Contains(function.Description); if (allowed) return true; } } return false; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectResult("~/login"); } } }