RoleAuthorizeAttribute.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using Autofac;
  2. using GreenTree.Nachtragsmanagement.Core;
  3. using GreenTree.Nachtragsmanagement.Core.Authentication;
  4. using GreenTree.Nachtragsmanagement.Services.User;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Web;
  11. using System.Web.Mvc;
  12. namespace GreenTree.Nachtragsmanagement.Web.Framework.Authorization
  13. {
  14. public class RoleAuthorizeAttribute : AuthorizeAttribute
  15. {
  16. #region Fields
  17. private readonly IAuthenticationService _authenticationService;
  18. private readonly IUserHelper _userHelper;
  19. private readonly string[] _allowedFunctions;
  20. #endregion
  21. /// <summary>
  22. /// Initializes a new instance of the RoleAuthorizeAttribute class
  23. /// </summary>
  24. /// <param name="functions">The functions needed.</param>
  25. public RoleAuthorizeAttribute(params string[] functions)
  26. {
  27. _allowedFunctions = functions;
  28. _authenticationService = Singleton<IContainer>.Instance.Resolve<IAuthenticationService>();
  29. _userHelper = Singleton<IContainer>.Instance.Resolve<IUserHelper>();
  30. }
  31. protected override bool AuthorizeCore(HttpContextBase httpContext)
  32. {
  33. var user = _userHelper.FromCookies();
  34. if (user == null)
  35. return false;
  36. foreach (var role in user.Roles)
  37. {
  38. foreach (var function in role.Functions)
  39. {
  40. var allowed = _allowedFunctions.Contains(function.Description);
  41. if (allowed)
  42. return true;
  43. }
  44. }
  45. return false;
  46. }
  47. protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
  48. {
  49. filterContext.Result = new RedirectResult("~/login");
  50. }
  51. }
  52. }