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
{
///
/// Filter for controllers methods
///
public class AuthFilter : AuthorizeAttribute
{
///
/// Authorized roles to access this method
///
public IEnumerable UserRoles { get; set; }
///
/// Constructor
///
/// The authorized roles
public AuthFilter(params int[] roles)
{
UserRoles = roles.ToList();
}
///
/// Check if user can access this method
///
/// HTTP request context
/// True if user can access, false otherwise
protected override bool IsAuthorized(HttpActionContext context)
{
if (!UserRoles.Any())
return true;
if (UserStorage.BasicUserDbo == null)
{
OpResult.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?").Log();
return false;
}
if (!UserRoles.Contains(UserStorage.BasicUserDbo.Role))
{
OpResult.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;
}
}
}