using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using iiie.Logs.DataAccess;
using iiie.Logs.DBO;
namespace iiie.Authentication.Business
{
///
/// Filter for controllers methods
///
public class AuthFilter : ActionFilterAttribute
{
///
/// Authorized roles to access this method
///
public IEnumerable UserRoles { get; set; }
///
/// Constructor
///
/// The authorized roles
public AuthFilter(params int[] roles)
{
UserRoles = roles.ToList();
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
if (!UserRoles.Any())
return;
OpResult error = null;
if (UserStorage.BasicUserDbo == null)
{
error = OpResult.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?", "").Log();
}
else if (!UserRoles.Contains(UserStorage.BasicUserDbo.Role))
{
error = 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()))), "Permission denied").Log();
}
if (error != null)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, error.PublicDetails);
}
}
}
}