public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpRequest request = HttpContext.Current.Request; // TODO: DI // TODO: Caching string permissionsDbPath = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "PermissionsDB.xml"); var permissionsRepo = new PermissionsXmlRepository(permissionsDbPath); var rolesCsvProvider = new RolesCsvCookieProvider(request); var permissionsService = new PermissionsService(permissionsRepo, rolesCsvProvider); string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; bool canAccessUrl = controllerName == "Error" || permissionsService.HasUrlPermission(request.RawUrl, request.HttpMethod); bool canAccessMethod = RequiredTask == null || permissionsService.HasTaskPermission(RequiredTask); Debug.WriteLine($"AuthFilter canAccessUrl: {canAccessUrl}, canAccessMethod: {canAccessMethod}"); if (!canAccessUrl || !canAccessMethod) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "controller", "Error" }, { "action", "PermissionErrorAjax" } }); } else { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "controller", "Error" }, { "action", "PermissionError" } }); } } base.OnActionExecuting(filterContext); }
public void HasUrlPermission_ShouldReturnFalseForUrlNotAllowedByRoles() { var repoMock = new Mock<IPermissionsRepository>(); repoMock.Setup(x => x.GetAllRoles()).Returns( new List<Role> { new Role() { Name = "SNAIL" } }); repoMock.Setup(x => x.GetAllTasks()).Returns( new List<Task> { new Task() { Name = "CAN_LIVE", Url = "Snail/KeepAlive", Method = "GET" }, }); repoMock.Setup(x => x.GetAllGrants()).Returns( new List<Grant> { new Grant() { RoleName = "SNAIL", TaskName = "CAN_LIVE" } }); var providerMock = new Mock<IRolesCsvProvider>(); providerMock.Setup(x => x.GetRolesCsv()).Returns("LAMP"); var service = new PermissionsService(repoMock.Object, providerMock.Object); bool isGranted = service.HasUrlPermission("Zoo/Snail/KeepAlive", "GET"); isGranted.Should().BeFalse(); }