You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AuthFilter.cs 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.Http;
  5. using System.Web.Http;
  6. using System.Web.Http.Controllers;
  7. using System.Web.Http.Filters;
  8. using iiie.Logs.DataAccess;
  9. using iiie.Logs.DBO;
  10. namespace iiie.Authentication.Business
  11. {
  12. /// <summary>
  13. /// Filter for controllers methods
  14. /// </summary>
  15. public class AuthFilter : ActionFilterAttribute
  16. {
  17. /// <summary>
  18. /// Authorized roles to access this method
  19. /// </summary>
  20. public IEnumerable<int> UserRoles { get; set; }
  21. /// <summary>
  22. /// Constructor
  23. /// </summary>
  24. /// <param name="roles">The authorized roles</param>
  25. public AuthFilter(params int[] roles)
  26. {
  27. UserRoles = roles.ToList();
  28. }
  29. public override void OnActionExecuting(HttpActionContext actionContext)
  30. {
  31. base.OnActionExecuting(actionContext);
  32. OpResult<bool> error = null;
  33. if (UserStorage.BasicUserDbo == null)
  34. {
  35. error = OpResult<bool>.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?", "").Log();
  36. }
  37. else if (UserRoles.Any() && !UserRoles.Contains(UserStorage.BasicUserDbo.Role))
  38. {
  39. error = OpResult<bool>.Error(ResultStatus.PermissionError, string.Format("User has role {0}, but only {1} are allowed",
  40. UserStorage.BasicUserDbo.Role, string.Join(",", UserRoles.Select(x => x.ToString()))), "Permission denied").Log();
  41. }
  42. if (error != null)
  43. {
  44. actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, error.PublicDetails);
  45. }
  46. }
  47. }
  48. }