1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- 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
- {
- /// <summary>
- /// Filter for controllers methods
- /// </summary>
- public class AuthFilter : ActionFilterAttribute
- {
- /// <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();
- }
-
- public override void OnActionExecuting(HttpActionContext actionContext)
- {
- base.OnActionExecuting(actionContext);
- if (!UserRoles.Any())
- return;
- OpResult<bool> error = null;
- if (UserStorage.BasicUserDbo == null)
- {
- error = OpResult<bool>.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?", "").Log();
- }
- else if (!UserRoles.Contains(UserStorage.BasicUserDbo.Role))
- {
- error = 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()))), "Permission denied").Log();
- }
- if (error != null)
- {
- actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, error.PublicDetails);
- }
- }
- }
- }
|