public async Task <IActionResult> ApplyCustomProfile([FromBody] ApplyCustomProfileRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            IEnumerable <FundingStreamPermission> fundingStreamPermissions = await _authorizationHelper.GetUserFundingStreamPermissions(User);

            if (fundingStreamPermissions.All(
                    x => x.FundingStreamId == request.FundingStreamId && x.CanApplyCustomProfilePattern == false))
            {
                return(new ForbidResult());
            }

            NoValidatedContentApiResponse result = await _publishingApiClient.ApplyCustomProfilePattern(request);

            if (result.StatusCode == HttpStatusCode.BadRequest)
            {
                return(BadRequest(result.ModelState));
            }

            if (result.StatusCode == HttpStatusCode.InternalServerError)
            {
                return(new InternalServerErrorResult($"Unable to apply custom profile. An error has occurred.'"));
            }

            return(StatusCode((int)result.StatusCode));
        }
Exemplo n.º 2
0
        public async Task GetFundingStreams_GivenTwoFundingStreamsReturned_ReturnsOneFundingStreamWhenSecurityTrimmed()
        {
            //Arrange
            IPoliciesApiClient policiesApiClient = CreatePoliciesApiClient();

            policiesApiClient
            .GetFundingStreams()
            .Returns(new ApiResponse <IEnumerable <FundingStream> >(HttpStatusCode.OK, GetFundingStreams()));

            IAuthorizationHelper authorizationHelper = CreateAuthorizationHelper();

            authorizationHelper
            .GetUserFundingStreamPermissions(Arg.Any <ClaimsPrincipal>(), "DSG")
            .Returns(new FundingStreamPermission {
                CanCreateSpecification = false
            });
            authorizationHelper
            .GetUserFundingStreamPermissions(Arg.Any <ClaimsPrincipal>(), "PSG")
            .Returns(new FundingStreamPermission {
                CanCreateSpecification = true
            });
            authorizationHelper
            .GetUserFundingStreamPermissions(Arg.Any <ClaimsPrincipal>(), "Missing")
            .Returns((FundingStreamPermission)null);

            PolicyController policyController = CreateController(policiesApiClient, authorizationHelper);

            //Act
            IActionResult result = await policyController.GetFundingStreams(true);

            //Assert
            result
            .Should()
            .BeAssignableTo <OkObjectResult>();

            IEnumerable <FundingStream> fundingStreams = (result as OkObjectResult).Value as IEnumerable <FundingStream>;

            fundingStreams
            .Should()
            .HaveCount(1);

            fundingStreams
            .First()
            .Id
            .Should()
            .Be("PSG");
        }
Exemplo n.º 3
0
        public async Task <IActionResult> ValidateDataset([FromBody] ValidateDatasetModel vm)
        {
            Guard.ArgumentNotNull(vm, nameof(vm));

            FundingStreamPermission permissions = await _authorizationHelper.GetUserFundingStreamPermissions(User, vm.FundingStreamId);

            if (permissions?.CanUploadDataSourceFiles != true)
            {
                _logger.Error($"User [{User?.Identity?.Name}] has insufficient permissions to upload a dataset file for {vm.FundingStreamId}");
                return(Forbid(new AuthenticationProperties()));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ValidatedApiResponse <DatasetValidationStatusModel> apiResponse = await _datasetApiClient.ValidateDataset(
                new GetDatasetBlobModel
            {
                DatasetId            = vm.DatasetId,
                Version              = vm.Version,
                Filename             = vm.Filename,
                Description          = vm.Description,
                Comment              = vm.Comment,
                FundingStreamId      = vm.FundingStreamId,
                MergeExistingVersion = vm.MergeExistingVersion
            });

            if (apiResponse == null)
            {
                _logger.Warning("Validate Dataset API response was null");
                return(new InternalServerErrorResult("Validate Dataset API response was null"));
            }

            if (!apiResponse.StatusCode.IsSuccess())
            {
                _logger.Warning("Failed to validate dataset with status code: {statusCode}", apiResponse.StatusCode);

                if (apiResponse.IsBadRequest(out BadRequestObjectResult badRequest))
                {
                    return(badRequest);
                }

                return(new InternalServerErrorResult(
                           "Validate Dataset API response failed with status code: {statusCode}" + apiResponse.StatusCode));
            }

            DatasetValidationStatusViewModel
                result = _mapper.Map <DatasetValidationStatusViewModel>(apiResponse.Content);

            return(new OkObjectResult(result));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> CreateDraftTemplate([FromBody] TemplateCreateModel createModel)
        {
            Guard.ArgumentNotNull(createModel, nameof(createModel));

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            FundingStreamPermission permissions = await _authorizationHelper.GetUserFundingStreamPermissions(User, createModel.FundingStreamId);

            if (!permissions.CanCreateTemplates)
            {
                _logger.Error($"User [{User?.Identity?.Name}] has insufficient permissions to create a {createModel.FundingStreamId} template");
                return(Forbid(new AuthenticationProperties()));
            }

            ValidatedApiResponse <string> result = await _client.CreateDraftTemplate(new TemplateCreateCommand
            {
                Description     = createModel.Description,
                FundingStreamId = createModel.FundingStreamId,
                FundingPeriodId = createModel.FundingPeriodId,
                SchemaVersion   = "1.1"
            });

            switch (result.StatusCode)
            {
            case HttpStatusCode.Created:
                return(Created($"api/templates/build/{result.Content}", result.Content));

            case HttpStatusCode.BadRequest:
                return(BadRequest(result.ModelState));

            default:
                return(StatusCode((int)result.StatusCode));
            }
        }
Exemplo n.º 5
0
        public async Task EditCalculationStatus_GivenUserDoesNotHaveCanApproveAnyCalculationPermission_Returns403()
        {
            //Arrange
            string specificationId = "abc123";
            string calculationId   = "5";

            PublishStatusEditModel model = new PublishStatusEditModel()
            {
                PublishStatus = PublishStatus.Approved
            };

            ValidatedApiResponse <Calculation> response = new ValidatedApiResponse <Calculation>(HttpStatusCode.OK, new Calculation()
            {
                FundingStreamId = "fs1", SpecificationId = specificationId
            });

            ICalculationsApiClient calcsClient = Substitute.For <ICalculationsApiClient>();

            calcsClient
            .GetCalculationById(Arg.Is(calculationId))
            .Returns(response);

            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper.DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanEditCalculations))
            .Returns(true);

            authorizationHelper.GetUserFundingStreamPermissions(Arg.Any <ClaimsPrincipal>(), Arg.Any <string>())
            .Returns(Task.FromResult(new Common.ApiClient.Users.Models.FundingStreamPermission()));


            CalculationController controller = CreateCalculationController(calcsClient, mapper, authorizationHelper, resultsApiClient);

            // Act
            IActionResult result = await controller.ApproveCalculation(specificationId, calculationId, model);

            // Assert
            result.Should().BeOfType <ForbidResult>();

            await authorizationHelper
            .Received(1)
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanApproveAnyCalculations));

            await authorizationHelper
            .Received(1)
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanApproveCalculations));
        }
        public async Task <IActionResult> CreateSpecification([FromBody] CreateSpecificationViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            var fundingStreamIds = new List <string> {
                viewModel.FundingStreamId
            };

            IEnumerable <FundingStreamPermission> fundingStreamPermissions = await _authorizationHelper.GetUserFundingStreamPermissions(User);

            bool hasPermissionsOnAllTheseStreams = fundingStreamIds
                                                   .All(fundingStreamId => fundingStreamPermissions
                                                        .Any(x =>
                                                             x.FundingStreamId == fundingStreamId && x.CanCreateSpecification));

            if (!hasPermissionsOnAllTheseStreams)
            {
                return(new ForbidResult());
            }

            CreateSpecificationModel specification = new CreateSpecificationModel
            {
                Description         = viewModel.Description,
                Name                = viewModel.Name,
                FundingPeriodId     = viewModel.FundingPeriodId,
                FundingStreamIds    = fundingStreamIds,
                ProviderVersionId   = viewModel.ProviderVersionId,
                AssignedTemplateIds = viewModel.AssignedTemplateIds,
                ProviderSnapshotId  = viewModel.ProviderSnapshotId
            };

            ValidatedApiResponse <SpecificationSummary> result = await _specificationsApiClient.CreateSpecification(specification);

            if (result.IsBadRequest(out BadRequestObjectResult badRequest))
            {
                return(badRequest);
            }

            if (result.StatusCode.IsSuccess())
            {
                return(new OkObjectResult(result.Content));
            }

            return(new InternalServerErrorResult($"Unable to create specification - result '{result.StatusCode}'"));
        }
Exemplo n.º 7
0
        public async Task EditCalculationStatus_GivenRequestContainsACalculationInADifferentSpecification_ReturnsError()
        {
            //Arrange
            string specificationId = "abc123";
            string calculationId   = "5";

            PublishStatusEditModel model = new PublishStatusEditModel()
            {
                PublishStatus = PublishStatus.Approved
            };

            ValidatedApiResponse <Calculation> response = new ValidatedApiResponse <Calculation>(HttpStatusCode.OK, new Calculation()
            {
                FundingStreamId = "fs1", SpecificationId = "anotherSpec"
            });

            ICalculationsApiClient calcsClient = Substitute.For <ICalculationsApiClient>();

            calcsClient
            .GetCalculationById(Arg.Is(calculationId))
            .Returns(response);

            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            IAuthorizationHelper authorizationHelper = Substitute.For <IAuthorizationHelper>();

            authorizationHelper.DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Is(specificationId), Arg.Is(SpecificationActionTypes.CanEditCalculations))
            .Returns(true);

            authorizationHelper.GetUserFundingStreamPermissions(Arg.Any <ClaimsPrincipal>(), Arg.Any <string>())
            .Returns(Task.FromResult(new Common.ApiClient.Users.Models.FundingStreamPermission()));


            CalculationController controller = CreateCalculationController(calcsClient, mapper, authorizationHelper, resultsApiClient);

            // Act
            IActionResult result = await controller.ApproveCalculation(specificationId, calculationId, model);

            // Assert
            result
            .Should()
            .BeOfType <PreconditionFailedResult>()
            .Which
            .Value
            .Should()
            .Be("The calculation requested is not contained within the specification requested");
        }
        public async Task <IActionResult> GetFundingStreams(bool securityTrimmed)
        {
            ApiResponse <IEnumerable <FundingStream> > response = await _policiesApiClient.GetFundingStreams();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                IEnumerable <FundingStream> fundingStreams = response.Content.OrderBy(x => x.Name);

                if (securityTrimmed)
                {
                    IEnumerable <Task <FundingStream> > tasks = fundingStreams.Select(async(_) =>
                    {
                        FundingStreamPermission permission = await _authorizationHelper.GetUserFundingStreamPermissions(User, _.Id);
                        return(permission != null ? (permission.CanCreateSpecification ? _ : null) : null);
                    });

                    fundingStreams = await Task.WhenAll(tasks);
                }

                return(Ok(fundingStreams.Where(_ => _ != null)));
            }

            throw new InvalidOperationException($"An error occurred while retrieving code context. Status code={response.StatusCode}");
        }
Exemplo n.º 9
0
 private void SetupFundingStreamPermissions(params FundingStreamPermission[] fundingStreamPermissions)
 {
     _authorizationHelper.GetUserFundingStreamPermissions(Arg.Any <ClaimsPrincipal>())
     .Returns(fundingStreamPermissions);
 }
        public async Task <IActionResult> GetAllFundingStreamPermissions()
        {
            var permissions = await _authorizationHelper.GetUserFundingStreamPermissions(User);

            return(Ok(permissions));
        }