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.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. if (!UserRoles.Any())
  33. return;
  34. OpResult<bool> error = null;
  35. if (UserStorage.BasicUserDbo == null)
  36. {
  37. error = OpResult<bool>.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?", "").Log();
  38. }
  39. else if (!UserRoles.Contains(UserStorage.BasicUserDbo.Role))
  40. {
  41. error = OpResult<bool>.Error(ResultStatus.PermissionError, string.Format("User has role {0}, but only {1} are allowed",
  42. UserStorage.BasicUserDbo.Role, string.Join(",", UserRoles.Select(x => x.ToString()))), "Permission denied").Log();
  43. }
  44. if (error != null)
  45. {
  46. actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, error.PublicDetails);
  47. }
  48. }
  49. }
  50. }