12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
- using System.Web.Http.Controllers;
- using iiie.Logs.DataAccess;
- using iiie.Logs.DBO;
-
- namespace iiie.Authentication.Business
- {
- /// <summary>
- /// Filter for controllers methods
- /// </summary>
- public class AuthFilter : AuthorizeAttribute
- {
- /// <summary>
- /// Authorized roles to access this method
- /// </summary>
- public IEnumerable<int> UserRoles { get; set; }
-
- /// <summary>
- /// Constructor
- /// </summary>
- /// <param name="roles">The authorized roles</param>
- public AuthFilter(params int[] roles)
- {
- UserRoles = roles.ToList();
- }
-
- /// <summary>
- /// Check if user can access this method
- /// </summary>
- /// <param name="context">HTTP request context</param>
- /// <returns>True if user can access, false otherwise</returns>
- protected override bool IsAuthorized(HttpActionContext context)
- {
- if (!UserRoles.Any())
- return true;
- if (UserStorage.BasicUserDbo == null)
- {
- OpResult<bool>.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?").Log();
- return false;
- }
- if (!UserRoles.Contains(UserStorage.BasicUserDbo.Role))
- {
- OpResult<bool>.Error(ResultStatus.PermissionError, string.Format("User has role {0}, but only {1} are allowed",
- UserStorage.BasicUserDbo.Role, string.Join(",", UserRoles.Select(x => x.ToString())))).Log();
- return false;
- }
- return true;
- }
- }
- }
|