123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- 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);
- OpResult<bool> error = null;
- if (UserStorage.BasicUserDbo == null)
- {
- error = OpResult<bool>.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?", "").Log();
- }
- else if (UserRoles.Any() && !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);
- }
- }
- }
- }
|