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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Web.Http;
  4. using System.Web.Http.Controllers;
  5. using iiie.Logs.DataAccess;
  6. using iiie.Logs.DBO;
  7. namespace iiie.Authentication.Business
  8. {
  9. /// <summary>
  10. /// Filter for controllers methods
  11. /// </summary>
  12. public class AuthFilter : AuthorizeAttribute
  13. {
  14. /// <summary>
  15. /// Authorized roles to access this method
  16. /// </summary>
  17. public IEnumerable<int> UserRoles { get; set; }
  18. /// <summary>
  19. /// Constructor
  20. /// </summary>
  21. /// <param name="roles">The authorized roles</param>
  22. public AuthFilter(params int[] roles)
  23. {
  24. UserRoles = roles.ToList();
  25. }
  26. /// <summary>
  27. /// Check if user can access this method
  28. /// </summary>
  29. /// <param name="context">HTTP request context</param>
  30. /// <returns>True if user can access, false otherwise</returns>
  31. protected override bool IsAuthorized(HttpActionContext context)
  32. {
  33. if (!UserRoles.Any())
  34. return true;
  35. if (UserStorage.BasicUserDbo == null)
  36. {
  37. OpResult<bool>.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?").Log();
  38. return false;
  39. }
  40. if (!UserRoles.Contains(UserStorage.BasicUserDbo.Role))
  41. {
  42. OpResult<bool>.Error(ResultStatus.PermissionError, string.Format("User has role {0}, but only {1} are allowed",
  43. UserStorage.BasicUserDbo.Role, string.Join(",", UserRoles.Select(x => x.ToString())))).Log();
  44. return false;
  45. }
  46. return true;
  47. }
  48. }
  49. }