public void ReturnsBadRequestOnInvalidModelStateWithOtherThanGetRequest()
        {
            // Arrange
            var filter        = new ValidatorActionFilter();
            var filterContext = ActionExecutingContextProvider.GetActionExecutingContext("POST");

            filterContext.ModelState.AddModelError("Error", "An error has occured!");

            // Act
            filter.OnActionExecuting(filterContext);

            // Assert
            filterContext.HttpContext.Response.StatusCode.ShouldBe((int)HttpStatusCode.BadRequest);
        }
        public void ReturnsBadRequestOnInvalidModelStateWithGetRequest()
        {
            // Arrange
            var filter        = new ValidatorActionFilter();
            var filterContext = ActionExecutingContextProvider.GetActionExecutingContext("GET");

            filterContext.ModelState.AddModelError("Error", "An error has occured!");

            // Act
            filter.OnActionExecuting(filterContext);

            // Assert
            filterContext.Result.ShouldBeOfType <BadRequestResult>();
        }
        public void ResultContainsErrorMessagesInModelState()
        {
            // Arrange
            var filter        = new ValidatorActionFilter();
            var filterContext = ActionExecutingContextProvider.GetActionExecutingContext("POST");
            Dictionary <string, CustomModelStateEntry> errorsToExpect = ArrangeExpectedErrors(filterContext);

            // Act
            filter.OnActionExecuting(filterContext);

            // Assert
            var contentResult = filterContext.Result as ContentResult;

            contentResult.ShouldNotBeNull();
            contentResult.ContentType.ShouldBe("application/json");
            AssertThatReturnedErrorsMatchExpected(errorsToExpect, contentResult);
        }
        public void ReturnsUnauthorizedResultIfUserDoesntHavePermission()
        {
            // Arrange
            var db = GetInMemoryDb();

            var serviceFilter = new DynamicallyAuthorizeServiceFilter(db);
            var filterContext = ActionExecutingContextProvider.GetActionExecutingContext("GET");

            filterContext.HttpContext.User               = A.Fake <ClaimsPrincipal>();
            filterContext.RouteData.Values["action"]     = "This";
            filterContext.RouteData.Values["controller"] = "DoesntReallyMatterButItsNeeded";

            // Act
            serviceFilter.OnActionExecuting(filterContext);

            // Assert
            filterContext.Result.ShouldBeOfType <UnauthorizedResult>();
        }
        public void RedirectsIfUnauthorized()
        {
            // Arrange
            var attribute = new JsonAuthorizeAttribute();

            var filterContext = ActionExecutingContextProvider.GetActionExecutingContext("GET");

            var urlHelper = A.Fake <IUrlHelper>();

            A.CallTo(() => urlHelper
                     .Action(new UrlActionContext()))
            .WithAnyArguments()
            .Returns("Login/Account/");

            var controller = A.Fake <Controller>();

            controller.Url = urlHelper;

            A.CallTo(() => filterContext.Controller).Returns(controller);

            var user = A.Fake <ClaimsPrincipal>();

            A.CallTo(() => user.Identity.IsAuthenticated).Returns(false);

            // Act
            attribute.OnActionExecuting(filterContext);

            // Assert
            filterContext.Result.ShouldBeOfType <ContentResult>();

            var result = filterContext.Result as ContentResult;

            result.ContentType.ShouldBe("application/json");

            HelperRedirectResult deserializedContent = JsonConvert.DeserializeObject <HelperRedirectResult>(result.Content);

            deserializedContent.Redirect.ShouldBe("Login/Account/");
        }
        public void AdminUserIsLetThrough()
        {
            // Arrange
            var db            = GetInMemoryDb();
            var serviceFilter = new DynamicallyAuthorizeServiceFilter(db);
            var filterContext = ActionExecutingContextProvider.GetActionExecutingContext("GET");

            var user = A.Fake <ClaimsPrincipal>();

            A.CallTo(() => user.IsInRole(OnlineStore.Infrastructure.Constants.Roles.ADMIN_ROLE)).Returns(true);

            filterContext.HttpContext.User = user;

            // Act
            serviceFilter.OnActionExecuting(filterContext);

            // Assert
            A.CallToSet(() => filterContext.Result)
            .To(() => A <IActionResult>
                .That
                .IsInstanceOf(typeof(UnauthorizedResult)))
            .MustNotHaveHappened();
        }
        public async Task RollbacksTransactionOnError()
        {
            // Arrange
            var db = A.Fake <ApplicationDbContext>(opts => opts.WithArgumentsForConstructor(() =>
                                                                                            new ApplicationDbContext(new Microsoft.EntityFrameworkCore.DbContextOptions <ApplicationDbContext>())));

            A.CallTo(() => db.BeginTransaction()).DoesNothing();

            var filter = new DbContextTransactionFilter(db);

            var filterContext           = ActionExecutingContextProvider.GetActionExecutingContext("POST");
            var actionExecutionDelegate = A.Fake <ActionExecutionDelegate>();

            A.CallTo(() => actionExecutionDelegate.Invoke()).Throws <InvalidOperationException>();

            // Act
            try { await filter.OnActionExecutionAsync(filterContext, actionExecutionDelegate); } catch { }

            // Assert
            A.CallTo(() => db.BeginTransaction()).MustHaveHappened();
            A.CallTo(() => db.CommitTransactionAsync()).MustNotHaveHappened();
            A.CallTo(() => db.RollbackTransaction()).MustHaveHappened();
        }
        public async Task RegularUserWithPermissionIsLetThrough()
        {
            // Arrange
            var    db                 = GetInMemoryDb();
            string actionToTestOn     = "TestAction";
            string controllerToTestOn = "TestController";
            var    role               = await AddSampleRoleToDatabase(db, actionToTestOn, controllerToTestOn);

            var filterContext = SetupFilterContextWithUser();
            var serviceFilter = new DynamicallyAuthorizeServiceFilter(db);

            // Act
            serviceFilter.OnActionExecuting(filterContext);

            // Assert
            A.CallToSet(() => filterContext.Result)
            .To(() => A <IActionResult>
                .That.IsInstanceOf(typeof(UnauthorizedResult)))
            .MustNotHaveHappened();

            ActionExecutingContext SetupFilterContextWithUser()
            {
                var context = ActionExecutingContextProvider.GetActionExecutingContext("GET");

                context.RouteData.Values["action"]     = actionToTestOn;
                context.RouteData.Values["controller"] = controllerToTestOn;

                var user = A.Fake <ClaimsPrincipal>();

                A.CallTo(() => user.IsInRole(role.Name)).Returns(true);

                context.HttpContext.User = user;

                return(context);
            }
        }
        public async Task CommitsTransaction()
        {
            // Arrange
            var db = A.Fake <ApplicationDbContext>(opts => opts.WithArgumentsForConstructor(() =>
                                                                                            new ApplicationDbContext(new Microsoft.EntityFrameworkCore.DbContextOptions <ApplicationDbContext>())));

            A.CallTo(() => db.BeginTransaction()).DoesNothing();
            A.CallTo(() => db.CommitTransactionAsync()).Returns(Task.FromResult(0));

            var filter = new DbContextTransactionFilter(db);

            var filterContext = ActionExecutingContextProvider.GetActionExecutingContext("POST");

            var actionExecutionDelegate = A.Fake <ActionExecutionDelegate>();

            A.CallTo(() => actionExecutionDelegate.Invoke()).Returns(Task.FromResult <ActionExecutedContext>(null));

            // Act
            await filter.OnActionExecutionAsync(filterContext, actionExecutionDelegate);

            // Assert
            A.CallTo(() => db.BeginTransaction()).MustHaveHappened();
            A.CallTo(() => db.CommitTransactionAsync()).MustHaveHappened();
        }