RoleAuthorizeAttribute.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. private readonly bool _showNotAuthorized;
  21. #endregion
  22. /// <summary>
  23. /// Initializes a new instance of the RoleAuthorizeAttribute class
  24. /// </summary>
  25. /// <param name="showNotAuthorized">Determines if a NotAuthorized message or a login redirection is made.</param>
  26. /// <param name="functions">The functions needed.</param>
  27. public RoleAuthorizeAttribute(bool showNotAuthorized, params string[] functions)
  28. {
  29. _showNotAuthorized = showNotAuthorized;
  30. _allowedFunctions = functions;
  31. _authenticationService = Singleton<IContainer>.Instance.Resolve<IAuthenticationService>();
  32. _userHelper = Singleton<IContainer>.Instance.Resolve<IUserHelper>();
  33. }
  34. protected override bool AuthorizeCore(HttpContextBase httpContext)
  35. {
  36. var user = _userHelper.FromCookies();
  37. if (user == null)
  38. return false;
  39. if (!_allowedFunctions.Any())
  40. return true;
  41. foreach (var role in user.Roles)
  42. {
  43. foreach (var function in role.Functions)
  44. {
  45. var allowed = _allowedFunctions.Contains(function.Description);
  46. if (allowed)
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
  53. {
  54. if (!_showNotAuthorized)
  55. filterContext.Result = new RedirectResult("~/login");
  56. else
  57. filterContext.Result = new RedirectResult("~/global/notauthorized");
  58. }
  59. }
  60. }