| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- 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;
- private readonly bool _showNotAuthorized;
- #endregion
- /// <summary>
- /// Initializes a new instance of the RoleAuthorizeAttribute class
- /// </summary>
- /// <param name="showNotAuthorized">Determines if a NotAuthorized message or a login redirection is made.</param>
- /// <param name="functions">The functions needed.</param>
- public RoleAuthorizeAttribute(bool showNotAuthorized, params string[] functions)
- {
- _showNotAuthorized = showNotAuthorized;
- _allowedFunctions = functions;
- _authenticationService = Singleton<IContainer>.Instance.Resolve<IAuthenticationService>();
- _userHelper = Singleton<IContainer>.Instance.Resolve<IUserHelper>();
- }
- protected override bool AuthorizeCore(HttpContextBase httpContext)
- {
- var user = _userHelper.FromCookies();
- if (user == null)
- return false;
- if (!_allowedFunctions.Any())
- return true;
- 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)
- {
- if (!_showNotAuthorized)
- filterContext.Result = new RedirectResult("~/login");
- else
- filterContext.Result = new RedirectResult("~/global/notauthorized");
- }
- }
- }
|