public async Task GivenAFhirMediator_WhenHardDeletingWithSufficientPermissions_ThenItWillBeHardDeleted()
        {
            _authorizationService.CheckAccess(Arg.Any <DataActions>(), Arg.Any <CancellationToken>()).Returns(DataActions.Delete | DataActions.HardDelete);

            ResourceKey resourceKey = new ResourceKey <Observation>("id1");

            ResourceKey resultKey = (await _mediator.DeleteResourceAsync(resourceKey, true)).ResourceKey;

            await _fhirDataStore.Received(1).HardDeleteAsync(resourceKey, Arg.Any <CancellationToken>());

            Assert.NotNull(resultKey);
            Assert.Equal(resourceKey.Id, resultKey.Id);
            Assert.Null(resultKey.VersionId);
        }
Exemple #2
0
        /// <summary>
        /// Confirm the request
        /// </summary>
        /// <param name="requestId">Request's id</param>
        public void Confirm(int requestId)
        {
            _authService.CheckAccess(AuthOperations.TournamentRequests.Confirm);
            var tournamentRequest = Get(requestId);

            if (tournamentRequest == null)
            {
                throw new MissingEntityException(ServiceResources.ExceptionMessages.TournamentRequestNotFound, requestId);
            }

            _tournamentRepository.AddTeamToTournament(tournamentRequest.TeamId, tournamentRequest.GroupId);
            _tournamentRepository.UnitOfWork.Commit();
            NotifyUser(_userService.GetUser(Get(requestId).UserId).Email);
            _tournamentRequestRepository.Remove(requestId);
            _tournamentRequestRepository.UnitOfWork.Commit();
        }
        public async Task <CreateReindexResponse> Handle(CreateReindexRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Reindex, cancellationToken) != DataActions.Reindex)
            {
                throw new UnauthorizedFhirActionException();
            }

            (var activeReindexJobs, var reindexJobId) = await _fhirOperationDataStore.CheckActiveReindexJobsAsync(cancellationToken);

            if (activeReindexJobs)
            {
                throw new JobConflictException(string.Format(Resources.OnlyOneResourceJobAllowed, reindexJobId));
            }

            // We need to pull in latest search parameter updates from the data store before creating a reindex job.
            // There could be a potential delay of <see cref="ReindexJobConfiguration.JobPollingFrequency"/> before
            // search parameter updates on one instance propagates to other instances. If we store the reindex
            // job with the old hash value in _searchParameterDefinitionManager.SearchParameterHashMap, then we will
            // not detect the resources that need to be reindexed.
            await _searchParameterOperations.GetAndApplySearchParameterUpdates(cancellationToken);

            var jobRecord = new ReindexJobRecord(
                _searchParameterDefinitionManager.SearchParameterHashMap,
                request.MaximumConcurrency ?? _reindexJobConfiguration.DefaultMaximumThreadsPerReindexJob,
                request.MaximumResourcesPerQuery ?? _reindexJobConfiguration.MaximumNumberOfResourcesPerQuery,
                request.QueryDelayIntervalInMilliseconds ?? _reindexJobConfiguration.QueryDelayIntervalInMilliseconds,
                request.TargetDataStoreUsagePercentage);
            var outcome = await _fhirOperationDataStore.CreateReindexJobAsync(jobRecord, cancellationToken);

            return(new CreateReindexResponse(outcome));
        }
        public ResourceHandlerTests()
        {
            _fhirDataStore       = Substitute.For <IFhirDataStore>();
            _conformanceProvider = Substitute.For <ConformanceProviderBase>();
            _searchService       = Substitute.For <ISearchService>();

            // TODO: FhirRepository instantiate ResourceDeserializer class directly
            // which will try to deserialize the raw resource. We should mock it as well.
            _rawResourceFactory     = Substitute.For <RawResourceFactory>(new FhirJsonSerializer());
            _resourceWrapperFactory = Substitute.For <IResourceWrapperFactory>();
            _resourceWrapperFactory
            .Create(Arg.Any <ResourceElement>(), Arg.Any <bool>(), Arg.Any <bool>())
            .Returns(x => CreateResourceWrapper(x.ArgAt <ResourceElement>(0), x.ArgAt <bool>(1)));

            _conformanceStatement = CapabilityStatementMock.GetMockedCapabilityStatement();
            CapabilityStatementMock.SetupMockResource(_conformanceStatement, ResourceType.Observation, null);
            var observationResource = _conformanceStatement.Rest.First().Resource.Find(x => x.Type == ResourceType.Observation);

            observationResource.ReadHistory       = false;
            observationResource.UpdateCreate      = true;
            observationResource.ConditionalCreate = true;
            observationResource.ConditionalUpdate = true;
            observationResource.Versioning        = CapabilityStatement.ResourceVersionPolicy.Versioned;

            CapabilityStatementMock.SetupMockResource(_conformanceStatement, ResourceType.Patient, null);
            var patientResource = _conformanceStatement.Rest.First().Resource.Find(x => x.Type == ResourceType.Patient);

            patientResource.ReadHistory       = true;
            patientResource.UpdateCreate      = true;
            patientResource.ConditionalCreate = true;
            patientResource.ConditionalUpdate = true;
            patientResource.Versioning        = CapabilityStatement.ResourceVersionPolicy.VersionedUpdate;

            _conformanceProvider.GetCapabilityStatementOnStartup().Returns(_conformanceStatement.ToTypedElement().ToResourceElement());
            var lazyConformanceProvider = new Lazy <IConformanceProvider>(() => _conformanceProvider);

            var collection = new ServiceCollection();

            // an auth service that allows all.
            _authorizationService = Substitute.For <IAuthorizationService <DataActions> >();
            _authorizationService.CheckAccess(Arg.Any <DataActions>(), Arg.Any <CancellationToken>()).Returns(ci => ci.Arg <DataActions>());

            var referenceResolver = new ResourceReferenceResolver(_searchService, new TestQueryStringParser());

            _resourceIdProvider = new ResourceIdProvider();
            collection.Add(x => _mediator).Singleton().AsSelf();
            collection.Add(x => new CreateResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, referenceResolver, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces();
            collection.Add(x => new UpsertResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService, ModelInfoProvider.Instance)).Singleton().AsSelf().AsImplementedInterfaces();
            collection.Add(x => new ConditionalCreateResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _searchService, x.GetService <IMediator>(), _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces();
            collection.Add(x => new ConditionalUpsertResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _searchService, x.GetService <IMediator>(), _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces();
            collection.Add(x => new GetResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces();
            collection.Add(x => new DeleteResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces();

            ServiceProvider provider = collection.BuildServiceProvider();

            _mediator = new Mediator(type => provider.GetService(type));

            _deserializer = new ResourceDeserializer(
                (FhirResourceFormat.Json, new Func <string, string, DateTimeOffset, ResourceElement>((str, version, lastUpdated) => _fhirJsonParser.Parse(str).ToResourceElement())));
        }
Exemple #5
0
        public async Task <EverythingOperationResponse> Handle(EverythingOperationRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Read, cancellationToken) != DataActions.Read)
            {
                throw new UnauthorizedFhirActionException();
            }

            if (!string.Equals(request.EverythingOperationType, ResourceType.Patient.ToString(), StringComparison.Ordinal))
            {
                throw new RequestNotValidException(string.Format(Core.Resources.ResourceNotSupported, request.EverythingOperationType));
            }

            SearchResult searchResult = await _patientEverythingService.SearchAsync(
                request.ResourceId,
                request.Start,
                request.End,
                request.Since,
                request.ResourceTypes,
                request.ContinuationToken,
                cancellationToken);

            ResourceElement bundle = request.UnsupportedParameters != null && request.UnsupportedParameters.Any()
                ? _bundleFactory.CreateSearchBundle(new SearchResult(searchResult.Results, searchResult.ContinuationToken, searchResult.SortOrder, request.UnsupportedParameters))
                : _bundleFactory.CreateSearchBundle(searchResult);

            return(new EverythingOperationResponse(bundle));
        }
        public async Task GivenUserDoesNotHavePermissionForReindex_WhenHandle_ThenUnauthorizedExceptionIsThrown()
        {
            _authorizationService.CheckAccess(Arg.Is(DataActions.Reindex), Arg.Any <CancellationToken>()).Returns(DataActions.None);
            var request = GetReindexRequest(HttpGetName);

            await Assert.ThrowsAsync <UnauthorizedFhirActionException>(() => _reindexHandler.Handle(request, _cancellationToken));
        }
        public async Task <CancelImportResponse> Handle(CancelImportRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Import, cancellationToken) != DataActions.Import)
            {
                throw new UnauthorizedFhirActionException();
            }

            try
            {
                TaskInfo taskInfo = await _taskManager.CancelTaskAsync(request.TaskId, cancellationToken);

                if (taskInfo.Status == TaskManagement.TaskStatus.Completed)
                {
                    throw new OperationFailedException(Resources.ImportOperationCompleted, HttpStatusCode.Conflict);
                }
                else
                {
                    return(new CancelImportResponse(HttpStatusCode.Accepted));
                }
            }
            catch (TaskNotExistException)
            {
                throw new ResourceNotFoundException(string.Format(Resources.ImportTaskNotFound, request.TaskId));
            }
        }
Exemple #8
0
 private void SetPermissionForHandler(string context = "ContextA", RequestHandlerType?handlerType = null)
 {
     _authorizationService
     .CheckAccess(
         new Permission(context, (handlerType ?? _requestHandlerType).ToString()))
     .Returns(true);
 }
Exemple #9
0
 private void SetPermissionForHandler()
 {
     _authorizationService
     .CheckAccess(
         new Permission(nameof(IDomainFrameworkTestFixture), _handlerType.ToString()))
     .Returns(true);
 }
        public async Task <CreateReindexResponse> Handle(CreateReindexRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Reindex, cancellationToken) != DataActions.Reindex)
            {
                throw new UnauthorizedFhirActionException();
            }

            (var activeReindexJobs, var reindexJobId) = await _fhirOperationDataStore.CheckActiveReindexJobsAsync(cancellationToken);

            if (activeReindexJobs)
            {
                throw new JobConflictException(string.Format(Resources.OnlyOneResourceJobAllowed, reindexJobId));
            }

            var jobRecord = new ReindexJobRecord(
                _searchParameterDefinitionManager.SearchParameterHashMap,
                request.MaximumConcurrency ?? _reindexJobConfiguration.DefaultMaximumThreadsPerReindexJob,
                request.MaximumResourcesPerQuery ?? _reindexJobConfiguration.MaximumNumberOfResourcesPerQuery,
                request.QueryDelayIntervalInMilliseconds ?? _reindexJobConfiguration.QueryDelayIntervalInMilliseconds,
                request.TargetDataStoreUsagePercentage);
            var outcome = await _fhirOperationDataStore.CreateReindexJobAsync(jobRecord, cancellationToken);

            return(new CreateReindexResponse(outcome));
        }
Exemple #11
0
        public async Task <CancelReindexResponse> Handle(CancelReindexRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Reindex, cancellationToken) != DataActions.Reindex)
            {
                throw new UnauthorizedFhirActionException();
            }

            return(await _retryPolicy.ExecuteAsync(async() =>
            {
                ReindexJobWrapper outcome = await _fhirOperationDataStore.GetReindexJobByIdAsync(request.JobId, cancellationToken);

                // If the job is already completed for any reason, return conflict status.
                if (outcome.JobRecord.Status.IsFinished())
                {
                    throw new RequestNotValidException(
                        string.Format(Resources.ReindexJobInCompletedState, outcome.JobRecord.Id, outcome.JobRecord.Status));
                }

                // Try to cancel the job.
                outcome.JobRecord.Status = OperationStatus.Canceled;
                outcome.JobRecord.CanceledTime = Clock.UtcNow;

                await _fhirOperationDataStore.UpdateReindexJobAsync(outcome.JobRecord, outcome.ETag, cancellationToken);

                return new CancelReindexResponse(HttpStatusCode.Conflict, outcome);
            }));
        }
Exemple #12
0
        public async Task <CreateExportResponse> Handle(CreateExportRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Export, cancellationToken) != DataActions.Export)
            {
                throw new UnauthorizedFhirActionException();
            }

            IReadOnlyCollection <KeyValuePair <string, string> > requestorClaims = _claimsExtractor.Extract()?
                                                                                   .OrderBy(claim => claim.Key, StringComparer.Ordinal).ToList();

            // Compute the hash of the job.
            var hashObject = new
            {
                request.RequestUri,
                RequestorClaims = requestorClaims,
            };

            string hash = JsonConvert.SerializeObject(hashObject).ComputeHash();

            string storageAccountConnectionHash = string.IsNullOrEmpty(_exportJobConfiguration.StorageAccountConnection) ?
                                                  string.Empty :
                                                  StringExtensions.ComputeHash(_exportJobConfiguration.StorageAccountConnection);

            // Check to see if a matching job exists or not. If a matching job exists, we will return that instead.
            // Otherwise, we will create a new export job. This will be a best effort since the likelihood of this happen should be small.
            ExportJobOutcome outcome = await _fhirOperationDataStore.GetExportJobByHashAsync(hash, cancellationToken);

            var filters = ParseFilter(request.Filters);

            ExportJobFormatConfiguration formatConfiguration = ParseFormat(request.FormatName, request.ContainerName != null);

            if (outcome == null)
            {
                var jobRecord = new ExportJobRecord(
                    request.RequestUri,
                    request.RequestType,
                    formatConfiguration.Format,
                    request.ResourceType,
                    filters,
                    hash,
                    _exportJobConfiguration.RollingFileSizeInMB,
                    requestorClaims,
                    request.Since,
                    request.GroupId,
                    storageAccountConnectionHash,
                    _exportJobConfiguration.StorageAccountUri,
                    request.AnonymizationConfigurationLocation,
                    request.AnonymizationConfigurationFileETag,
                    _exportJobConfiguration.MaximumNumberOfResourcesPerQuery,
                    _exportJobConfiguration.NumberOfPagesPerCommit,
                    request.ContainerName);

                outcome = await _fhirOperationDataStore.CreateExportJobAsync(jobRecord, cancellationToken);
            }

            return(new CreateExportResponse(outcome.JobRecord.Id));
        }
Exemple #13
0
        public static bool CheckAccess(this IAuthorizationService authorizationService, IPrincipal principal, Operation operation, Resource resource)
        {
            var claimsPrincipal = principal.AsClaimsPrincipal();
            var resources       = new Collection <Claim>(new Claim[] { resource }.ToList());
            var operations      = new Collection <Claim>(new Claim[] { operation }.ToList());

            var authorizationContext = new AuthorizationContext(claimsPrincipal, resources, operations);

            return(authorizationService.CheckAccess(authorizationContext));
        }
Exemple #14
0
        public void DeleteClassify(int clsId)
        {
            _authorizationService.CheckAccess(Permissions.ResourceAdmin, OrchardService.WorkContext.CurrentUser, null);
            var cls = GetClsById(clsId);

            if (cls == null)
            {
                return;
            }
            _resClassifyRepository.Delete(cls);
        }
        public async Task <ConvertDataResponse> Handle(ConvertDataRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request);

            if (await _authorizationService.CheckAccess(DataActions.ConvertData, cancellationToken) != DataActions.ConvertData)
            {
                throw new UnauthorizedFhirActionException();
            }

            return(await _convertDataEngine.Process(request, cancellationToken));
        }
Exemple #16
0
        public void DeleteTag(int tagId)
        {
            _authorizationService.CheckAccess(Permissions.ManageTags, _orchardServices.WorkContext.CurrentUser, null);

            var tag = GetTag(tagId);

            if (tag == null)
            {
                return;
            }

            // Delete associations to content items
            foreach (var tagContentItem in _contentTagRepository.Fetch(x => x.TagRecord == tag))
            {
                _contentTagRepository.Delete(tagContentItem);
            }

            // Delete tag entity
            _tagRepository.Delete(tag);
        }
Exemple #17
0
        /// <summary>
        /// Create a new team.
        /// </summary>
        /// <param name="teamToCreate">A Team to create.</param>
        public Team Create(CreateTeamDto teamToCreate)
        {
            _authService.CheckAccess(AuthOperations.Teams.Create);

            if (teamToCreate.Captain == null)
            {
                throw new EntityInvariantViolationException("Captain can not be null");
            }

            ThrowExceptionIfTeamWithSuchNameExists(teamToCreate.Name);

            var captain = GetPlayerById(teamToCreate.Captain.Id);

            if (captain == null)
            {
                throw new MissingEntityException(ServiceResources.ExceptionMessages.PlayerNotFound, teamToCreate.Captain.Id);
            }

            // Check if captain in teamToCreate is captain of another team
            var existTeam = GetTeamLedByCaptain(captain.Id);

            VerifyExistingTeamOrThrow(existTeam);

            return(_teamRepository.Add(teamToCreate));
        }
Exemple #18
0
        public bool CreateTerm(OptionItemPart termPart)
        {
            if (GetTermByName(termPart.OptionSetId, termPart.Name) == null)
            {
                _authorizationService.CheckAccess(Permissions.CreateTerm, _services.WorkContext.CurrentUser, null);

                termPart.As <ICommonPart>().Container = GetOptionSet(termPart.OptionSetId).ContentItem;
                _contentManager.Create(termPart);
                return(true);
            }
            _notifier.Warning(T("The term {0} already exists in this taxonomy", termPart.Name));
            return(false);
        }
Exemple #19
0
        public async Task <MemberMatchResponse> Handle(MemberMatchRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Read, cancellationToken) != DataActions.Read)
            {
                throw new UnauthorizedFhirActionException();
            }

            ResourceElement patient = await _memberMatchService.FindMatch(request.Coverage, request.Patient, cancellationToken);

            return(new MemberMatchResponse(patient));
        }
Exemple #20
0
        /// <summary>
        /// Confirm request by id
        /// </summary>
        /// <param name="requestId">The id of request to Confirm.</param>
        public void Confirm(int requestId)
        {
            _authService.CheckAccess(AuthOperations.Requests.Confirm);
            var request = Get(requestId);

            if (request == null)
            {
                throw new MissingEntityException(ServiceResources.ExceptionMessages.RequestNotFound, requestId);
            }

            var user = _userService.GetUser(request.UserId);

            if (user == null)
            {
                throw new MissingEntityException(ServiceResources.ExceptionMessages.UserNotFound);
            }

            user.PlayerId = request.PlayerId;

            _userRepository.Update(user);
            _requestRepository.Remove(requestId);
            _userRepository.UnitOfWork.Commit();
        }
Exemple #21
0
        public EitherAsync <Error, TResponse> Handle(TRequest request)
        {
            var permissionEnabled = ExtractPermissionToCheck(RootInstance)
                                    .MapAsync(async perm => await _authZService.CheckAccess(perm))
                                    .Map(p => p.Match(
                                             Right: allowed => allowed
                                                        ? (Either <Error, Unit>)Unit.Default
                                                        : Error.NotAuthorized("No permission"),
                                             Left: e => e
                                             ))
                                    .ToAsync();

            return(permissionEnabled.Bind(_ => Decoratee.Handle(request)));
        }
        public void CreateTerm(TermPart termPart)
        {
            if (GetTermByName(termPart.TaxonomyId, termPart.Name) == null)
            {
                _authorizationService.CheckAccess(Permissions.CreateTerm, _services.WorkContext.CurrentUser, null);

                termPart.As <ICommonPart>().Container = GetTaxonomy(termPart.TaxonomyId).ContentItem;
                _contentManager.Create(termPart);
            }
            else
            {
                _notifier.Warning(T("The term {0} already exists in this taxonomy", termPart.Name));
            }
        }
Exemple #23
0
        public async Task GivenInvalidAuthorization_WhenHandlingRequest_ThenThrowUnauthorizedDicomActionException()
        {
            using var source = new CancellationTokenSource();
            IAuthorizationService <DataActions> auth = Substitute.For <IAuthorizationService <DataActions> >();
            IDicomOperationsClient client            = Substitute.For <IDicomOperationsClient>();
            var handler = new OperationStatusHandler(auth, client);

            auth.CheckAccess(DataActions.Read, source.Token).Returns(DataActions.None);

            await Assert.ThrowsAsync <UnauthorizedDicomActionException>(() => handler.Handle(new OperationStatusRequest(Guid.NewGuid()), source.Token));

            await auth.Received(1).CheckAccess(DataActions.Read, source.Token);

            await client.DidNotReceiveWithAnyArgs().GetStatusAsync(default, default);
        public async Task <GetImportResponse> Handle(GetImportRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Import, cancellationToken) != DataActions.Import)
            {
                throw new UnauthorizedFhirActionException();
            }

            TaskInfo taskInfo = await _taskManager.GetTaskAsync(request.TaskId, cancellationToken);

            if (taskInfo == null)
            {
                throw new ResourceNotFoundException(string.Format(Resources.ImportTaskNotFound, request.TaskId));
            }

            if (taskInfo.Status != TaskManagement.TaskStatus.Completed)
            {
                if (taskInfo.IsCanceled)
                {
                    throw new OperationFailedException(Resources.UserRequestedCancellation, HttpStatusCode.BadRequest);
                }

                return(new GetImportResponse(HttpStatusCode.Accepted));
            }
            else
            {
                TaskResultData resultData = JsonConvert.DeserializeObject <TaskResultData>(taskInfo.Result);
                if (resultData.Result == TaskResult.Success)
                {
                    ImportTaskResult result = JsonConvert.DeserializeObject <ImportTaskResult>(resultData.ResultData);
                    return(new GetImportResponse(HttpStatusCode.OK, result));
                }
                else if (resultData.Result == TaskResult.Fail)
                {
                    ImportTaskErrorResult errorResult = JsonConvert.DeserializeObject <ImportTaskErrorResult>(resultData.ResultData);

                    string         failureReason     = errorResult.ErrorMessage;
                    HttpStatusCode failureStatusCode = errorResult.HttpStatusCode;

                    throw new OperationFailedException(
                              string.Format(Resources.OperationFailed, OperationsConstants.Import, failureReason), failureStatusCode);
                }
                else
                {
                    throw new OperationFailedException(Resources.UserRequestedCancellation, HttpStatusCode.BadRequest);
                }
            }
        }
        public async Task <CreateImportResponse> Handle(CreateImportRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Import, cancellationToken) != DataActions.Import)
            {
                throw new UnauthorizedFhirActionException();
            }

            string taskId = Guid.NewGuid().ToString("N");

            // Processing task might be dispatch to different environment with differenet queueid later.
            string processingTaskQueueId = string.IsNullOrEmpty(_importTaskConfiguration.ProcessingTaskQueueId) ? _taskHostingConfiguration.QueueId : _importTaskConfiguration.ProcessingTaskQueueId;
            ImportOrchestratorTaskInputData inputData = new ImportOrchestratorTaskInputData()
            {
                RequestUri    = request.RequestUri,
                BaseUri       = new Uri(request.RequestUri.GetLeftPart(UriPartial.Authority)),
                Input         = request.Input,
                InputFormat   = request.InputFormat,
                InputSource   = request.InputSource,
                StorageDetail = request.StorageDetail,
                MaxConcurrentProcessingTaskCount = _importTaskConfiguration.MaxRunningProcessingTaskCount,
                ProcessingTaskQueueId            = processingTaskQueueId,
                ProcessingTaskMaxRetryCount      = _importTaskConfiguration.MaxRetryCount,
                TaskId         = taskId,
                TaskCreateTime = Clock.UtcNow,
            };

            TaskInfo taskInfo = new TaskInfo()
            {
                TaskId        = taskId,
                TaskTypeId    = ImportOrchestratorTask.ImportOrchestratorTaskId,
                MaxRetryCount = _importTaskConfiguration.MaxRetryCount,
                QueueId       = _taskHostingConfiguration.QueueId,
                InputData     = JsonConvert.SerializeObject(inputData),
            };

            try
            {
                await _taskManager.CreateTaskAsync(taskInfo, true, cancellationToken);
            }
            catch (TaskConflictException)
            {
                _logger.LogInformation("Already a running import task.");
                throw new OperationFailedException(Resources.ImportTaskIsRunning, HttpStatusCode.Conflict);
            }

            return(new CreateImportResponse(taskId));
        }
Exemple #26
0
        /// <inheritdoc />
        public async Task <SearchResourceResponse> Handle(SearchResourceRequest message, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(message, nameof(message));

            if (await _authorizationService.CheckAccess(DataActions.Read, cancellationToken) != DataActions.Read)
            {
                throw new UnauthorizedFhirActionException();
            }

            SearchResult searchResult = await _searchService.SearchAsync(message.ResourceType, message.Queries, cancellationToken);

            ResourceElement bundle = _bundleFactory.CreateSearchBundle(searchResult);

            return(new SearchResourceResponse(bundle));
        }
        public async Task <ReindexSingleResourceResponse> Handle(ReindexSingleResourceRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Reindex, cancellationToken) != DataActions.Reindex)
            {
                throw new UnauthorizedFhirActionException();
            }

            var             key            = new ResourceKey(request.ResourceType, request.ResourceId);
            ResourceWrapper storedResource = await _fhirDataStore.GetAsync(key, cancellationToken);

            if (storedResource == null)
            {
                throw new ResourceNotFoundException(string.Format(Core.Resources.ResourceNotFoundById, request.ResourceType, request.ResourceId));
            }

            await _searchParameterOperations.GetAndApplySearchParameterUpdates(cancellationToken);

            // We need to extract the "new" search indices since the assumption is that
            // a new search parameter has been added to the fhir server.
            ResourceElement resourceElement = _resourceDeserializer.Deserialize(storedResource);
            IReadOnlyCollection <SearchIndexEntry> newIndices = _searchIndexer.Extract(resourceElement);

            // If it's a post request we need to go update the resource in the database.
            if (request.HttpMethod == HttpPostName)
            {
                await ProcessPostReindexSingleResourceRequest(storedResource, newIndices);
            }

            // Create a new parameter resource and include the new search indices and the corresponding values.
            var parametersResource = new Parameters
            {
                Id        = Guid.NewGuid().ToString(),
                VersionId = "1",
                Parameter = new List <Parameters.ParameterComponent>(),
            };

            foreach (SearchIndexEntry searchIndex in newIndices)
            {
                parametersResource.Parameter.Add(new Parameters.ParameterComponent()
                {
                    Name = searchIndex.SearchParameter.Code.ToString(), Value = new FhirString(searchIndex.Value.ToString())
                });
            }

            return(new ReindexSingleResourceResponse(parametersResource.ToResourceElement()));
        }
        public ReindexSingleResourceRequestHandlerTests()
        {
            _authorizationService = Substitute.For <IAuthorizationService <DataActions> >();
            _fhirDataStore        = Substitute.For <IFhirDataStore>();
            _searchIndexer        = Substitute.For <ISearchIndexer>();
            _resourceDeserializer = Substitute.For <IResourceDeserializer>();
            _cancellationToken    = CancellationToken.None;

            _authorizationService.CheckAccess(Arg.Is(DataActions.Reindex), Arg.Any <CancellationToken>()).Returns(DataActions.Reindex);

            _reindexHandler = new ReindexSingleResourceRequestHandler(
                _authorizationService,
                _fhirDataStore,
                _searchIndexer,
                _resourceDeserializer);
        }
        /// <summary>
        /// Handles validation requests.
        /// </summary>
        /// <param name="request">The request</param>
        /// <param name="cancellationToken">The CancellationToken</param>
        public async Task <ValidateOperationResponse> Handle(ValidateOperationRequest request, CancellationToken cancellationToken)
        {
            if (await _authorizationService.CheckAccess(DataActions.ResourceValidate, cancellationToken) != DataActions.ResourceValidate)
            {
                throw new UnauthorizedFhirActionException();
            }

            var outcome = _profileValidator.TryValidate(request.Resource.Instance, request.Profile?.ToString());

            if (outcome.Length == 0)
            {
                return(new ValidateOperationResponse(ValidationPassed));
            }

            return(new ValidateOperationResponse(outcome));
        }
Exemple #30
0
        public async Task <GetExportResponse> Handle(GetExportRequest request, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(request, nameof(request));

            if (await _authorizationService.CheckAccess(DataActions.Export, cancellationToken) != DataActions.Export)
            {
                throw new UnauthorizedFhirActionException();
            }

            ExportJobOutcome outcome = await _fhirOperationDataStore.GetExportJobByIdAsync(request.JobId, cancellationToken);

            // We have an existing job. We will determine the response based on the status of the export operation.
            GetExportResponse exportResponse;

            if (outcome.JobRecord.Status == OperationStatus.Completed)
            {
                List <ExportFileInfo> allFiles = new List <ExportFileInfo>();
                foreach (List <ExportFileInfo> fileList in outcome.JobRecord.Output.Values)
                {
                    allFiles.AddRange(fileList);
                }

                var jobResult = new ExportJobResult(
                    outcome.JobRecord.QueuedTime,
                    outcome.JobRecord.RequestUri,
                    requiresAccessToken: false,
                    allFiles.Select(x => x.ToExportOutputResponse()).OrderBy(x => x.Type, StringComparer.Ordinal).ToList(),
                    outcome.JobRecord.Error.Select(x => x.ToExportOutputResponse()).ToList(),
                    outcome.JobRecord.Issues);

                exportResponse = new GetExportResponse(HttpStatusCode.OK, jobResult);
            }
            else if (outcome.JobRecord.Status == OperationStatus.Failed || outcome.JobRecord.Status == OperationStatus.Canceled)
            {
                string         failureReason     = outcome.JobRecord.FailureDetails != null ? outcome.JobRecord.FailureDetails.FailureReason : Resources.UnknownError;
                HttpStatusCode failureStatusCode = outcome.JobRecord.FailureDetails != null ? outcome.JobRecord.FailureDetails.FailureStatusCode : HttpStatusCode.InternalServerError;

                throw new OperationFailedException(
                          string.Format(Resources.OperationFailed, OperationsConstants.Export, failureReason), failureStatusCode);
            }
            else
            {
                exportResponse = new GetExportResponse(HttpStatusCode.Accepted);
            }

            return(exportResponse);
        }