Exemplo n.º 1
0
        public ResourceBase DeleteResource(string resourceType, string id)
        {
            this.ThrowIfNotReady();

            try
            {
                // Setup outgoing content/
                RestOperationContext.Current.OutgoingResponse.StatusCode = (int)HttpStatusCode.NoContent;

                // Create or update?
                var handler = FhirResourceHandlerUtil.GetResourceHandler(resourceType);
                if (handler == null)
                {
                    throw new FileNotFoundException(); // endpoint not found!
                }
                var result = handler.Delete(id, TransactionMode.Commit);

                AuditUtil.AuditDataAction <ResourceBase>(EventTypeCodes.Import, ActionType.Delete, AuditableObjectLifecycle.LogicalDeletion, EventIdentifierType.Import, OutcomeIndicator.Success, id, result);
                return(null);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error deleting FHIR resource {0}({1}): {2}", resourceType, id, e);
                AuditUtil.AuditDataAction <ResourceBase>(EventTypeCodes.Import, ActionType.Delete, AuditableObjectLifecycle.LogicalDeletion, EventIdentifierType.Import, OutcomeIndicator.EpicFail, id);
                throw;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Perform an admission operation
        /// </summary>
        protected virtual IMessage PerformAdmit(Hl7MessageReceivedEventArgs e, Bundle insertBundle)
        {
            try
            {
                var patient = insertBundle.Item.OfType <Patient>().FirstOrDefault(it => it.Tags.Any(t => t.TagKey == ".v2.segment" && t.Value == "PID"));
                if (patient == null)
                {
                    throw new ArgumentNullException(nameof(insertBundle), "Message did not contain a patient");
                }

                var repoService = ApplicationServiceContext.Current.GetService <IRepositoryService <Bundle> >();
                if (repoService == null)
                {
                    throw new InvalidOperationException("Cannot find repository for Patient");
                }

                insertBundle = repoService.Insert(insertBundle);

                AuditUtil.AuditCreate(Core.Auditing.OutcomeIndicator.Success, null, insertBundle.Item.ToArray());
                // Create response message
                return(this.CreateACK(typeof(ACK), e.Message, "CA", $"{patient.Key} created"));
            }
            catch
            {
                AuditUtil.AuditUpdate(Core.Auditing.OutcomeIndicator.MinorFail, null, insertBundle.Item.ToArray());
                throw;
            }
        }
Exemplo n.º 3
0
        public ResourceBase CreateResource(string resourceType, ResourceBase target)
        {
            this.ThrowIfNotReady();
            try
            {
                // Setup outgoing content

                // Create or update?
                var handler = FhirResourceHandlerUtil.GetResourceHandler(resourceType);
                if (handler == null)
                {
                    throw new FileNotFoundException(); // endpoint not found!
                }
                var result = handler.Create(target, TransactionMode.Commit);
                RestOperationContext.Current.OutgoingResponse.StatusCode = (int)HttpStatusCode.Created;


                AuditUtil.AuditDataAction <ResourceBase>(EventTypeCodes.Import, ActionType.Create, AuditableObjectLifecycle.Creation, EventIdentifierType.Import, OutcomeIndicator.Success, null, result);

                String baseUri = MessageUtil.GetBaseUri();
                RestOperationContext.Current.OutgoingResponse.Headers.Add("Content-Location", String.Format("{0}/{1}/{2}/_history/{3}", baseUri, resourceType, result.Id, result.VersionId));
                RestOperationContext.Current.OutgoingResponse.SetLastModified(result.Timestamp);
                RestOperationContext.Current.OutgoingResponse.SetETag($"W/\"{result.VersionId}\"");


                return(result);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error creating FHIR resource {0}: {1}", resourceType, e);
                AuditUtil.AuditDataAction <ResourceBase>(EventTypeCodes.Import, ActionType.Create, AuditableObjectLifecycle.Creation, EventIdentifierType.Import, OutcomeIndicator.EpicFail, null);
                throw;
            }
        }
 /// <summary>
 /// Remove the specified object
 /// </summary>
 public object Remove(Type scopingType, object scopingKey, object key)
 {
     if (key == null || key.Equals("*"))
     {
         this.m_queueService.Purge((String)scopingKey);
         AuditUtil.SendAudit(new Core.Auditing.AuditData()
                             .WithLocalDevice()
                             .WithUser()
                             .WithAction(Core.Auditing.ActionType.Delete)
                             .WithEventIdentifier(Core.Auditing.EventIdentifierType.ApplicationActivity)
                             .WithOutcome(Core.Auditing.OutcomeIndicator.Success)
                             .WithTimestamp(DateTimeOffset.Now)
                             .WithEventType("PurgeQueue")
                             .WithHttpInformation(RestOperationContext.Current.IncomingRequest)
                             .WithSystemObjects(Core.Auditing.AuditableObjectRole.Resource, Core.Auditing.AuditableObjectLifecycle.PermanentErasure, new Uri($"urn:santedb:org:DispatcherQueueInfo/{scopingKey}/event/*")));
     }
     else
     {
         var data = this.m_queueService.DequeueById((String)scopingKey, (string)key);
         AuditUtil.SendAudit(new Core.Auditing.AuditData()
                             .WithLocalDevice()
                             .WithUser()
                             .WithAction(Core.Auditing.ActionType.Delete)
                             .WithEventIdentifier(Core.Auditing.EventIdentifierType.ApplicationActivity)
                             .WithOutcome(Core.Auditing.OutcomeIndicator.Success)
                             .WithTimestamp(DateTimeOffset.Now)
                             .WithEventType("PurgeQueueObject")
                             .WithHttpInformation(RestOperationContext.Current.IncomingRequest)
                             .WithSystemObjects(Core.Auditing.AuditableObjectRole.Resource, Core.Auditing.AuditableObjectLifecycle.PermanentErasure, new Uri($"urn:santedb:org:DispatcherQueueInfo/{scopingKey}/event/{key}")));
     }
     return(null);
 }
        public void addRequest(Request request)
        {
            try
            {
                request.Status = Status.Unprocessed;
                DbCommand cmd = _weidb.GetStoredProcCommand("Wei_AddRequest");

                _weidb.AddInParameter(cmd, "@name", DbType.String, request.Name);
                _weidb.AddInParameter(cmd, "@messagebody", DbType.String, request.MessageBody);
                _weidb.AddInParameter(cmd, "@interfaceid", DbType.Int32, request.InterfaceId);
                _weidb.AddInParameter(cmd, "@requestheader", DbType.String, request.Header);
                _weidb.AddInParameter(cmd, "@status", DbType.Int32, request.Status);
                _weidb.AddInParameter(cmd, "@iserror", DbType.Int32, request.IsError);
                _weidb.AddInParameter(cmd, "@CreatedOper", DbType.String, request.CreateOper);
                decimal requestId = (decimal)_weidb.ExecuteScalar(cmd);

                request.RequestId = (int)requestId;

                LogUtil.logInfo("Created new request");
                AuditUtil.getInstance().audit((int)requestId, AuditLevel.Info, "Created new request-" + requestId);
            }
            catch (SqlException ex)
            {
                LogUtil.logError("Error while adding request:  " + ex.ToString());
                throw new Exception("Error while adding request: ", ex);
            }
        }
        /// <summary>
        /// Dispose of the job
        /// </summary>
        public void Dispose()
        {
            AuditData securityAlertData = new AuditData(DateTime.Now, ActionType.Execute, OutcomeIndicator.Success, EventIdentifierType.SecurityAlert, AuditUtil.CreateAuditActionCode(EventTypeCodes.AuditLoggingStopped));

            AuditUtil.AddLocalDeviceActor(securityAlertData);
            AuditUtil.SendAudit(securityAlertData);
        }
        /// <summary>
        /// Synchronized dispatch service
        /// </summary>
        public SynchronizedAuditDispatchService(IConfigurationManager configurationManager, IJobStateManagerService jobStateManager, IJobManagerService scheduleManager, IThreadPoolService threadPool, IQueueManagerService queueManagerService)
        {
            this.m_securityConfiguration = configurationManager.GetSection <SecurityConfigurationSection>();
            this.m_jobStateManager       = jobStateManager;
            this.m_queueManagerService   = queueManagerService;

            if (!scheduleManager.GetJobSchedules(this).Any())
            {
                scheduleManager.SetJobSchedule(this, new TimeSpan(0, 5, 0));
            }

            threadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    AuditData securityAlertData = new AuditData(DateTime.Now, ActionType.Execute, OutcomeIndicator.Success, EventIdentifierType.SecurityAlert, AuditUtil.CreateAuditActionCode(EventTypeCodes.AuditLoggingStarted));
                    AuditUtil.AddLocalDeviceActor(securityAlertData);
                    AuditUtil.SendAudit(securityAlertData);
                }
                catch (Exception ex)
                {
                    this.m_tracer.TraceError("Error starting up audit repository service: {0}", ex);
                }
            });
        }
Exemplo n.º 8
0
        public SessionInfo Abandon()
        {
            var cookie = MiniImsServer.CurrentContext.Request.Cookies["_s"];

            var value = Guid.Empty;

            if (cookie != null && Guid.TryParse(cookie.Value, out value))
            {
                ISessionManagerService sessionService = ApplicationContext.Current.GetService <ISessionManagerService>();
                var sessionInfo = sessionService.Delete(value);
                if (MiniImsServer.CurrentContext.Request.Cookies["_s"] == null)
                {
                    MiniImsServer.CurrentContext.Response.SetCookie(new Cookie("_s", Guid.Empty.ToString(), "/")
                    {
                        Expired = true, Expires = DateTime.Now.AddSeconds(-20)
                    });
                }

                if (sessionInfo != null)
                {
                    AuditUtil.AuditLogout(sessionInfo.Principal);
                }
            }

            return(new SessionInfo());
        }
Exemplo n.º 9
0
        /// <summary>
        /// Remove user from role
        /// </summary>
        public object Remove(Type scopingType, object scopingKey, object key)
        {
            var scope = this.m_roleRepository.Get((Guid)scopingKey);

            if (scope == null)
            {
                throw new KeyNotFoundException($"Could not find SecurityRole with identifier {scopingKey}");
            }

            var user = this.m_userRepository.Get(Guid.Parse(key.ToString()));

            if (user == null)
            {
                throw new KeyNotFoundException($"User {key} not found");
            }

            try
            {
                this.m_pep.Demand(PermissionPolicyIdentifiers.AlterRoles);
                this.m_roleProvider.RemoveUsersFromRoles(new string[] { user.UserName }, new string[] { scope.Name }, AuthenticationContext.Current.Principal);
                AuditUtil.AuditSecurityAttributeAction(new object[] { scope }, true, $"del user={user.UserName}");
                return(user);
            }
            catch
            {
                AuditUtil.AuditSecurityAttributeAction(new object[] { scope }, false, $"del user={key}");
                throw;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Stop the application context
        /// </summary>
        public void Stop()
        {
            if (this.Stopping != null)
            {
                this.Stopping(this, null);
            }

            this.m_running = false;

            foreach (var svc in this.m_serviceInstances.OfType <IDaemonService>().ToArray())
            {
                Trace.TraceInformation("Stopping daemon service {0}...", svc.GetType().Name);
                svc.Stop();
            }

            // Dispose services
            foreach (var svc in this.m_serviceInstances.OfType <IDisposable>().Where(o => o != this))
            {
                svc.Dispose();
            }

            AuditUtil.AuditApplicationStartStop(EventTypeCodes.ApplicationStop);

            if (this.Stopped != null)
            {
                this.Stopped(this, null);
            }

            this.Dispose();
        }
        /// <summary>
        /// Remove the challenge
        /// </summary>
        public object Remove(Type scopingType, object scopingKey, object key)
        {
            // Get scope
            object scope = this.GetScope(scopingType, scopingKey);

            if (scope == null)
            {
                throw new KeyNotFoundException($"Could not find scoped object with identifier {scopingKey}");
            }

            var policy = this.m_pip.GetPolicies().FirstOrDefault(o => o.Key == (Guid)key);

            if (policy == null)
            {
                throw new KeyNotFoundException($"Policy {key} not found");
            }

            try
            {
                this.DemandFor(scopingType);
                this.m_pip.RemovePolicies(scope, AuthenticationContext.Current.Principal, policy.Oid);
                AuditUtil.AuditSecurityAttributeAction(new object[] { scope }, true, $"removed policy={policy.Oid}");
                return(null);
            }
            catch
            {
                AuditUtil.AuditSecurityAttributeAction(new object[] { scope }, false, $"removed policy={policy.Oid}");
                throw;
            }
        }
        /// <summary>
        /// Add the security challenge
        /// </summary>
        public object Add(Type scopingType, object scopingKey, object item)
        {
            // Get scope
            object scope = this.GetScope(scopingType, scopingKey);

            if (scope == null)
            {
                throw new KeyNotFoundException($"Could not find scoped object with identifier {scopingKey}");
            }

            try
            {
                this.DemandFor(scopingType);
                // Get or create the scoped item
                if (item is SecurityPolicy policy)
                {
                    item = new SecurityPolicyInfo(policy);
                }

                var rd = item as SecurityPolicyInfo;
                this.m_pip.AddPolicies(scope, rd.Grant, AuthenticationContext.Current.Principal, rd.Oid);
                AuditUtil.AuditSecurityAttributeAction(new object[] { scope }, true, $"added policy={rd.Oid}:{rd.Policy}");
                return(rd);
            }
            catch
            {
                AuditUtil.AuditSecurityAttributeAction(new object[] { scope }, false);
                throw;
            }
        }
        /// <summary>
        /// Demand the permission
        /// </summary>
        public void Demand()
        {
            var pdp       = ApplicationServiceContext.Current.GetService <IPolicyDecisionService>();
            var principal = this.m_principal ?? AuthenticationContext.Current.Principal;
            var action    = AuthenticationContext.Current.Principal == AuthenticationContext.SystemPrincipal ? PolicyGrantType.Grant : PolicyGrantType.Deny;

            // Non system principals must be authenticated
            if (!principal.Identity.IsAuthenticated &&
                principal != AuthenticationContext.SystemPrincipal &&
                this.m_isUnrestricted == true)
            {
                throw new PolicyViolationException(principal, this.m_policyId, PolicyGrantType.Deny);
            }
            else
            {
                if (pdp == null) // No way to verify
                {
                    action = PolicyGrantType.Deny;
                }
                else if (pdp != null)
                {
                    action = pdp.GetPolicyOutcome(principal, this.m_policyId);
                }
            }

            this.m_traceSource.TraceVerbose("Policy Enforce: {0}({1}) = {2}", principal?.Identity?.Name, this.m_policyId, action);

            AuditUtil.AuditAccessControlDecision(principal, m_policyId, action);
            if (action != PolicyGrantType.Grant)
            {
                throw new PolicyViolationException(principal, this.m_policyId, action);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Perform an update of the specified patient
        /// </summary>
        protected virtual IMessage PerformUpdate(Hl7MessageReceivedEventArgs e, Bundle updateBundle)
        {
            try
            {
                var patient = updateBundle.Item.OfType <Patient>().FirstOrDefault(it => it.Tags.Any(t => t.TagKey == ".v2.segment" && t.Value == "PID"));
                if (patient == null)
                {
                    throw new ArgumentNullException(nameof(updateBundle), "Message did not contain a patient");
                }
                else if (!patient.Key.HasValue)
                {
                    throw new InvalidOperationException("Update can only be performed on existing patients. Ensure that a unique identifier exists on the update record");
                }
                var repoService = ApplicationServiceContext.Current.GetService <IRepositoryService <Bundle> >();
                if (repoService == null)
                {
                    throw new InvalidOperationException("Cannot find repository for Patient");
                }

                updateBundle = repoService.Save(updateBundle);
                AuditUtil.AuditUpdate(Core.Auditing.OutcomeIndicator.Success, null, updateBundle.Item.ToArray());

                // Create response message
                return(this.CreateACK(typeof(ACK), e.Message, "CA", $"{patient.Key} updated"));
            }
            catch
            {
                AuditUtil.AuditUpdate(Core.Auditing.OutcomeIndicator.MinorFail, null, updateBundle.Item.ToArray());
                throw;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Provide the fault
        /// </summary>
        public bool ProvideFault(Exception error, RestResponseMessage response)
        {
            var errCode = WebErrorUtility.ClassifyException(error, true);
            var hdlr    = ApplicationContext.Current.GetService <IAppletManagerService>().Applets.SelectMany(o => o.ErrorAssets).FirstOrDefault(o => o.ErrorCode == errCode);

#if DEBUG
            var ie = error;
            while (ie != null)
            {
                this.m_tracer.TraceError("{0} - ({1}){2} - {3}", error == ie ? "" : "Caused By",
                                         RestOperationContext.Current.EndpointOperation?.Description.InvokeMethod.Name,
                                         ie.GetType().FullName, ie.Message);
                ie = ie.InnerException;
            }
#else
            if (error is TargetInvocationException)
            {
                this.m_tracer.TraceError("{0} - {1} / {2}", RestOperationContext.Current.EndpointOperation.Description.InvokeMethod.Name, error.Message, error.InnerException?.Message);
            }
            else
            {
                this.m_tracer.TraceError("{0} - {1}", RestOperationContext.Current.EndpointOperation.Description.InvokeMethod.Name, error.Message);
            }
#endif

            // Grab the asset handler
            try
            {
                if (hdlr != null)
                {
                    response.Body = new MemoryStream(new byte[0]);
                    RestOperationContext.Current.OutgoingResponse.Redirect(hdlr.Asset);
                }
                else
                {
                    RestOperationContext.Current.OutgoingResponse.StatusCode = errCode;
                    using (var sr = new StreamReader(typeof(AgsWebErrorHandlerServiceBehavior).Assembly.GetManifestResourceStream("SanteDB.DisconnectedClient.Ags.Resources.GenericError.html")))
                    {
                        string errRsp = sr.ReadToEnd().Replace("{status}", response.StatusCode.ToString())
                                        .Replace("{description}", response.StatusDescription)
                                        .Replace("{type}", error.GetType().Name)
                                        .Replace("{message}", error.Message)
                                        .Replace("{details}", error.ToString())
                                        .Replace("{trace}", error.StackTrace);
                        RestOperationContext.Current.OutgoingResponse.ContentType = "text/html";
                        response.Body = new MemoryStream(Encoding.UTF8.GetBytes(errRsp));
                    }
                }

                AuditUtil.AuditNetworkRequestFailure(error, RestOperationContext.Current.IncomingRequest.Url, RestOperationContext.Current.IncomingRequest.Headers.AllKeys.ToDictionary(o => o, o => RestOperationContext.Current.IncomingRequest.Headers[o]), RestOperationContext.Current.OutgoingResponse.Headers.AllKeys.ToDictionary(o => o, o => RestOperationContext.Current.OutgoingResponse.Headers[o]));

                return(true);
            }
            catch (Exception e)
            {
                Tracer.GetTracer(typeof(AgsWebErrorHandlerServiceBehavior)).TraceError("Could not provide fault: {0}", e.ToString());
                throw;
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Searches a resource from the client registry datastore
        /// </summary>
        public Bundle SearchResource(string resourceType)
        {
            this.ThrowIfNotReady();

            // Get the services from the service registry
            var auditService = ApplicationContext.Current.GetService(typeof(IAuditorService)) as IAuditorService;

            // Stuff for auditing and exception handling
            AuditData            audit   = null;
            List <IResultDetail> details = new List <IResultDetail>();
            FhirQueryResult      result  = null;

            try
            {
                // Get query parameters
                var queryParameters   = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;
                var resourceProcessor = FhirResourceHandlerUtil.GetResourceHandler(resourceType);

                // Setup outgoing content
                WebOperationContext.Current.OutgoingRequest.Headers.Add("Last-Modified", DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz"));

                if (resourceProcessor == null) // Unsupported resource
                {
                    throw new FileNotFoundException();
                }

                // TODO: Appropriately format response
                // Process incoming request
                result = resourceProcessor.Query(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters);

                if (result == null || result.Outcome == ResultCode.Rejected)
                {
                    throw new InvalidDataException("Message was rejected");
                }
                else if (result.Outcome != ResultCode.Accepted)
                {
                    throw new DataException("Query failed");
                }

                audit = AuditUtil.CreateAuditData(result.Results);
                // Create the Atom feed
                return(MessageUtil.CreateBundle(result));
            }
            catch (Exception e)
            {
                audit         = AuditUtil.CreateAuditData(null);
                audit.Outcome = OutcomeIndicator.EpicFail;
                return(this.ErrorHelper(e, result, true) as Bundle);
            }
            finally
            {
                if (auditService != null)
                {
                    auditService.SendAudit(audit);
                }
            }
        }
        /// <summary>
        /// Apply the authorization policy rule
        /// </summary>
        public void Apply(RestRequestMessage request)
        {
            try
            {
                this.m_traceSource.TraceInfo("CheckAccess");

                // Http message inbound
                var httpMessage = RestOperationContext.Current.IncomingRequest;


                // Get the authorize header
                String authorization = httpMessage.Headers["Authorization"];
                if (authorization == null)
                {
                    if (httpMessage.HttpMethod == "OPTIONS" || httpMessage.HttpMethod == "PING")
                    {
                        return;
                    }
                    else
                    {
                        throw new SecuritySessionException(SessionExceptionType.NotEstablished, "Missing Authorization header", null);
                    }
                }

                // Authorization method
                var auth = authorization.Split(' ').Select(o => o.Trim()).ToArray();
                switch (auth[0].ToLowerInvariant())
                {
                case "bearer":
                    var contextToken = this.CheckBearerAccess(auth[1]);
                    RestOperationContext.Current.Disposed += (o, e) => contextToken.Dispose();
                    break;

                default:
                    throw new SecuritySessionException(SessionExceptionType.TokenType, "Invalid authentication scheme", null);
                }
            }
            catch (UnauthorizedAccessException e)
            {
                this.m_traceSource.TraceError("Token Error (From: {0}) : {1}", RestOperationContext.Current.IncomingRequest.RemoteEndPoint, e);
                AuditUtil.AuditNetworkRequestFailure(e, RestOperationContext.Current.IncomingRequest.Url, RestOperationContext.Current.IncomingRequest.Headers, null);
                throw;
            }
            catch (KeyNotFoundException e)
            {
                this.m_traceSource.TraceError("Token Error (From: {0}) : {1}", RestOperationContext.Current.IncomingRequest.RemoteEndPoint, e);
                AuditUtil.AuditNetworkRequestFailure(e, RestOperationContext.Current.IncomingRequest.Url, RestOperationContext.Current.IncomingRequest.Headers, null);
                throw new SecuritySessionException(SessionExceptionType.NotEstablished, e.Message, e);
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceError("Token Error (From: {0}) : {1}", RestOperationContext.Current.IncomingRequest.RemoteEndPoint, e);
                AuditUtil.AuditNetworkRequestFailure(e, RestOperationContext.Current.IncomingRequest.Url, RestOperationContext.Current.IncomingRequest.Headers, null);
                throw new SecuritySessionException(SessionExceptionType.Other, e.Message, e);
            }
        }
        /// <summary>
        /// Demand policy enforcement
        /// </summary>
        public void Demand(string policyId, IPrincipal principal)
        {
            var result = this.GetGrant(principal, policyId);

            AuditUtil.AuditAccessControlDecision(principal, policyId, result);
            if (result != PolicyGrantType.Grant)
            {
                throw new PolicyViolationException(principal, policyId, result);
            }
        }
        /// <summary>
        /// Demand the permission
        /// </summary>
        public void Demand()
        {
            var result = this.DemandSoft();

            AuditUtil.AuditAccessControlDecision(this.m_principal, this.m_policyId, result);
            if (result != PolicyGrantType.Grant)
            {
                throw new PolicyViolationException(this.m_principal, this.m_policyId, result);
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// Force stop
 /// </summary>
 public virtual void Stop()
 {
     this.Stopping?.Invoke(this, EventArgs.Empty);
     AuditUtil.AuditApplicationStartStop(EventTypeCodes.ApplicationStop);
     this.m_serviceManager.Stop();
     this.m_serviceManager.Dispose();
     this.m_serviceManager = null;
     this.m_configManager  = null;
     this.Stopped?.Invoke(this, EventArgs.Empty);
     this.m_running = false;
     s_context      = null; // tear down singleton
 }
Exemplo n.º 21
0
        /// <summary>
        /// Delete a resource
        /// </summary>
        public DomainResourceBase DeleteResource(string resourceType, string id, string mimeType)
        {
            this.ThrowIfNotReady();

            FhirOperationResult result       = null;
            AuditData           audit        = null;
            IAuditorService     auditService = ApplicationContext.Current.GetService(typeof(IAuditorService)) as IAuditorService;

            try
            {
                // Setup outgoing content/
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NoContent;

                // Create or update?
                var handler = FhirResourceHandlerUtil.GetResourceHandler(resourceType);
                if (handler == null)
                {
                    throw new FileNotFoundException(); // endpoint not found!
                }
                result = handler.Delete(id, TransactionMode.Commit);

                if (result == null || result.Outcome == ResultCode.Rejected)
                {
                    throw new NotSupportedException();
                }
                else if (result.Outcome == ResultCode.TypeNotAvailable)
                {
                    throw new FileNotFoundException(String.Format("Resource {0} not found", WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri));
                }
                else if (result.Outcome != ResultCode.Accepted)
                {
                    throw new DataException("Delete failed");
                }

                audit = AuditUtil.CreateAuditData(result.Results);

                return(null);
            }
            catch (Exception e)
            {
                audit         = AuditUtil.CreateAuditData(null);
                audit.Outcome = OutcomeIndicator.EpicFail;
                return(this.ErrorHelper(e, result, false) as DomainResourceBase);
            }
            finally
            {
                if (auditService != null)
                {
                    auditService.SendAudit(audit);
                }
            }
        }
        /// <summary>
        /// Process a response message doing query continuation if needed
        /// </summary>
        private void PullPatientsAsync(Object state)
        {
            // Cast request
            QBP_Q21 request = state as QBP_Q21;

            // Send the PDQ message
            try
            {
                var response = this.m_sender.SendAndReceive(request) as RSP_K21;
                AuditUtil.SendPDQAudit(request, response);
                if (response == null || response.MSA.AcknowledgmentCode.Value != "AA")
                {
                    foreach (var err in response.ERR.GetErrorCodeAndLocation())
                    {
                        Trace.TraceError("{0}: CR ERR: {1} ({2})", this.m_context.JobId, err.CodeIdentifyingError.Text, err.CodeIdentifyingError.AlternateText);
                    }
                    // Kill!
                    Trace.TraceError("Stopping sync");
                    this.m_errorState = true;
                }

                // Is there a continuation pointer?
                if (!String.IsNullOrEmpty(response.DSC.ContinuationPointer.Value))
                {
                    Trace.TraceInformation("{0}: Need to continue query", this.m_context.JobId);
                    request.DSC.ContinuationPointer.Value = response.DSC.ContinuationPointer.Value;
                    this.UpdateMSH(request.MSH, "QBP_Q21", "QBP", "Q22");
                    this.m_waitThread.QueueUserWorkItem(this.PullPatientsAsync, request);
                }

                // Process the patients in this response
                lock (this.m_syncState)
                    for (int i = 0; i < response.QUERY_RESPONSERepetitionsUsed; i++)
                    {
                        var responseData = response.GetQUERY_RESPONSE(i);
                        this.m_workerItems.Push(responseData);
                    }

                // Relieve memorypressure
                lock (this.m_syncState)
                    while (this.m_workerItems.Count > 0)
                    {
                        this.m_waitThread.QueueUserWorkItem(this.ProcessPIDAsync, this.m_workerItems.Pop());
                    }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                this.m_errorState = true;
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Start auditor service
        /// </summary>
        public bool Start()
        {
            this.Starting?.Invoke(this, EventArgs.Empty);

            this.m_safeToStop = false;
            ApplicationServiceContext.Current.Stopping += (o, e) =>
            {
                this.m_safeToStop = true;
                this.Stop();
            };
            ApplicationServiceContext.Current.Started += (o, e) =>
            {
                try
                {
                    this.m_tracer.TraceInfo("Binding to service events...");

                    if (ApplicationServiceContext.Current.GetService <IIdentityProviderService>() != null)
                    {
                        ApplicationServiceContext.Current.GetService <IIdentityProviderService>().Authenticated += (so, se) =>
                        {
                            AuditUtil.AuditLogin(se.Principal, se.UserName, so as IIdentityProviderService, se.Success);
                        }
                    }
                    ;
                    if (ApplicationServiceContext.Current.GetService <ISessionProviderService>() != null)
                    {
                        ApplicationServiceContext.Current.GetService <ISessionProviderService>().Established += (so, se) =>
                        {
                            if (se.Elevated)
                            {
                                AuditUtil.AuditOverride(se.Session, se.Principal, se.Purpose, se.Policies, se.Success);
                            }
                            AuditUtil.AuditSessionStart(se.Session, se.Principal, se.Success);
                        };
                        ApplicationServiceContext.Current.GetService <ISessionProviderService>().Abandoned += (so, se) => AuditUtil.AuditSessionStop(se.Session, se.Principal, se.Success);
                    }
                    // Audit that Audits are now being recorded
                    var audit = new AuditData(DateTimeOffset.Now, ActionType.Execute, OutcomeIndicator.Success, EventIdentifierType.ApplicationActivity, AuditUtil.CreateAuditActionCode(EventTypeCodes.AuditLoggingStarted));
                    AuditUtil.AddLocalDeviceActor(audit);
                    AuditUtil.SendAudit(audit);
                }
                catch (Exception ex)
                {
                    this.m_tracer.TraceError("Error starting up audit repository service: {0}", ex);
                }
            };

            this.Started?.Invoke(this, EventArgs.Empty);
            return(true);
        }
Exemplo n.º 24
0
        public PostPatientAllergiesResponse Post(PostPatientAllergiesRequest request)
        {
            PostPatientAllergiesResponse response = new PostPatientAllergiesResponse();
            ValidateTokenResponse        result   = null;

            try
            {
                if (base.Request != null)
                {
                    request.Token = base.Request.Headers["Token"] as string;
                }
                result = Security.IsUserValidated(request.Version, request.Token, request.ContractNumber);
                if (result.UserId.Trim() != string.Empty)
                {
                    request.UserId            = result.UserId;
                    response.PatientAllergies = AllergyManager.UpdatePatientAllergies(request);
                }
                else
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch (Exception ex)
            {
                CommonFormatter.FormatExceptionResponse(response, base.Response, ex);
                if ((ex is WebServiceException) == false)
                {
                    AllergyManager.LogException(ex);
                }
            }
            finally
            {
                List <string> patientIds = null;
                if (request.PatientAllergies != null && request.PatientAllergies.Count > 0)
                {
                    patientIds = new List <string>();
                    request.PatientAllergies.ForEach(p =>
                    {
                        patientIds.Add(p.PatientId);
                    });
                }
                if (result != null)
                {
                    string browser     = (base.Request != null) ? base.Request.UserAgent : unknownBrowserType;
                    string hostAddress = (base.Request != null) ? base.Request.UserHostAddress : unknownUserHostAddress;
                    AuditUtil.LogAuditData(request, result.SQLUserId, patientIds, browser, hostAddress, request.GetType().Name);
                }
            }
            return(response);
        }
Exemplo n.º 25
0
        public GetMedNamesResponse Get(GetMedNamesRequest request)
        {
            GetMedNamesResponse   response = new GetMedNamesResponse();
            ValidateTokenResponse result   = null;

            try
            {
                if (base.Request != null)
                {
                    request.Token = base.Request.Headers["Token"] as string;
                }
                result = Security.IsUserValidated(request.Version, request.Token, request.ContractNumber);
                if (result.UserId.Trim() != string.Empty)
                {
                    request.UserId = result.UserId;
                    var res   = SearchManager.GetSearchMedNameResults(request);
                    var count = res.Count;
                    if (request.Take > 0 && res.Count > request.Take)
                    {
                        res = res.Take(request.Take).ToList();
                        response.Message = request.Take + " out of " + count + ". Please refine your search.";
                    }

                    response.ProprietaryNames = res;
                }
                else
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch (Exception ex)
            {
                CommonFormatterUtil.FormatExceptionResponse(response, base.Response, ex);
                if ((ex is WebServiceException) == false)
                {
                    SearchManager.LogException(ex);
                }
            }
            finally
            {
                if (result != null)
                {
                    string browser     = (base.Request != null) ? base.Request.UserAgent : unknownBrowserType;
                    string hostAddress = (base.Request != null) ? base.Request.UserHostAddress : unknownUserHostAddress;
                    AuditUtil.LogAuditData(request, result.SQLUserId, null, browser, hostAddress, request.GetType().Name);
                }
            }

            return(response);
        }
Exemplo n.º 26
0
        public virtual Object Create(Object data, bool updateIfExists)
        {
            if (data == null)
            {
                this.m_tracer.TraceError($"{nameof(data)} cannot be null");
                throw new ArgumentNullException(this.m_localizationService.FormatString("error.type.ArgumentNullException.param", new { param = nameof(data) }));
            }
            else if ((this.Capabilities & ResourceCapabilityType.Create) == 0 &&
                     (this.Capabilities & ResourceCapabilityType.CreateOrUpdate) == 0)
            {
                throw new NotSupportedException(this.m_localizationService.GetString("error.type.NotSupportedException"));
            }

            var bundle = data as Bundle;

            bundle?.Reconstitute();

            var processData = bundle?.GetFocalObject() ?? data;

            try
            {
                if (!(processData is TResource))
                {
                    this.m_tracer.TraceError($"Invalid data submission. Expected {typeof(TResource).FullName} but received {processData.GetType().FullName}. If you are submitting a bundle, ensure it has an entry point.");
                    throw new ArgumentException(this.m_localizationService.FormatString("error.rest.common.invalidDataSubmission", new
                    {
                        param  = typeof(TResource).FullName,
                        param1 = processData.GetType().FullName
                    }));
                }
                else if (processData is TResource)
                {
                    var resourceData = processData as TResource;
                    resourceData = updateIfExists ? this.GetRepository().Save(resourceData) : this.GetRepository().Insert(resourceData);

                    AuditUtil.AuditCreate(Core.Auditing.OutcomeIndicator.Success, null, resourceData);

                    return(resourceData);
                }
            }
            catch (Exception e)
            {
                AuditUtil.AuditCreate(Core.Auditing.OutcomeIndicator.MinorFail, null, data);
                this.m_tracer.TraceError($"Error creating {data}");
                throw new Exception(this.m_localizationService.FormatString("error.rest.common.errorCreatingParam", new { param = nameof(data) }), e);
            }
            this.m_tracer.TraceError($"Invalid data type: {nameof(data)}");
            throw new ArgumentException(nameof(data), this.m_localizationService.GetString("error.rest.common.invalidDataType"));
        }
Exemplo n.º 27
0
 public object Obsolete(object key)
 {
     this.m_queueService.Purge((String)key);
     AuditUtil.SendAudit(new Core.Auditing.AuditData()
                         .WithLocalDevice()
                         .WithUser()
                         .WithAction(Core.Auditing.ActionType.Delete)
                         .WithEventIdentifier(Core.Auditing.EventIdentifierType.ApplicationActivity)
                         .WithOutcome(Core.Auditing.OutcomeIndicator.Success)
                         .WithTimestamp(DateTimeOffset.Now)
                         .WithEventType("PurgeQueue")
                         .WithHttpInformation(RestOperationContext.Current.IncomingRequest)
                         .WithSystemObjects(Core.Auditing.AuditableObjectRole.Resource, Core.Auditing.AuditableObjectLifecycle.PermanentErasure, new Uri($"urn:santedb:org:DispatcherQueueInfo/{key}/event")));
     return(null);
 }
Exemplo n.º 28
0
        public GetMedFieldsResponse Get(GetMedFieldsRequest request)
        {
            GetMedFieldsResponse  response = new GetMedFieldsResponse();
            ValidateTokenResponse result   = null;

            try
            {
                if (base.Request != null)
                {
                    request.Token = base.Request.Headers["Token"] as string;
                }
                result = Security.IsUserValidated(request.Version, request.Token, request.ContractNumber);
                if (result.UserId.Trim() != string.Empty)
                {
                    request.UserId = result.UserId;
                    var results = SearchManager.GetSearchMedFieldsResults(request);

                    response.DosageForms = results.FormList;
                    response.Routes      = results.RouteList;
                    response.Strengths   = results.StrengthList;
                    response.Units       = results.UnitsList;
                }
                else
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch (Exception ex)
            {
                CommonFormatterUtil.FormatExceptionResponse(response, base.Response, ex);
                if ((ex is WebServiceException) == false)
                {
                    SearchManager.LogException(ex);
                }
            }
            finally
            {
                if (result != null)
                {
                    string browser     = (base.Request != null) ? base.Request.UserAgent : unknownBrowserType;
                    string hostAddress = (base.Request != null) ? base.Request.UserHostAddress : unknownUserHostAddress;
                    AuditUtil.LogAuditData(request, result.SQLUserId, null, browser, hostAddress, request.GetType().Name);
                }
            }

            return(response);
        }
Exemplo n.º 29
0
        public GetPatientSystemsResponse Get(GetPatientSystemsRequest request)
        {
            GetPatientSystemsResponse response = new GetPatientSystemsResponse();
            ValidateTokenResponse     result   = null;

            try
            {
                if (base.Request != null)
                {
                    request.Token = base.Request.Headers["Token"] as string;
                }
                result = Security.IsUserValidated(request.Version, request.Token, request.ContractNumber);
                if (result.UserId.Trim() != string.Empty)
                {
                    ServiceContext.UserId   = result.UserId;
                    response.PatientSystems = PatientSystemManager.GetPatientSystems(ServiceContext, request.PatientId);
                }
                else
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch (Exception ex)
            {
                CommonFormatterUtil.FormatExceptionResponse(response, base.Response, ex);
                if ((ex is WebServiceException) == false)
                {
                    PatientSystemManager.LogException(ex);
                }
            }
            finally
            {
                if (result != null)
                {
                    List <string> patientIds = null;
                    if (response.PatientSystems != null)
                    {
                        patientIds = response.PatientSystems.Select(x => x.PatientId).ToList();
                    }
                    string browser     = (base.Request != null) ? base.Request.UserAgent : unknownBrowserType;
                    string hostAddress = (base.Request != null) ? base.Request.UserHostAddress : unknownUserHostAddress;
                    AuditUtil.LogAuditData(request, result.SQLUserId, patientIds, browser, hostAddress, request.GetType().Name);
                }
            }

            return(response);
        }
Exemplo n.º 30
0
        public bool processMessageForOFACCheck(Request request, bool fromErrorQueue)
        {
            //AuditUtil.getInstance().audit(request.RequestId, AuditLevel.Info, "Started processing the message");
            bool      bLocked  = false;
            int       iStatus  = 0;
            bool      bSuccess = false;
            Interface i        = InterfaceManager.getInterface(request.InterfaceId);

            try
            {
                bLocked = _dbUtils.acquireLock(request.RequestId);
                if (bLocked)
                {
                    iStatus = _dbUtils.getStatusByRequest(request.RequestId);
                    if (iStatus == Convert.ToInt32(Status.Review))
                    {
                        bSuccess = i.Driver.sendForOfacCheck(request);
                        if (bSuccess)
                        {
                            request.Status  = Status.SentForOfacCheck;
                            request.IsError = false;
                            _dbUtils.changeStatus(request);
                            AuditUtil.getInstance().audit(request.RequestId, AuditLevel.Info, "Message sent for watchlist filtering check");
                        }
                    }
                }
                else
                {
                    LogUtil.logError("Cannot acquire lock for message :" + request.RequestId + ". Translation incomplete");
                    AuditUtil.getInstance().audit(request.RequestId, AuditLevel.Error, "Abort processing. Cannot acquire lock");
                }
            }
            catch (Exception e)
            {
                LogUtil.log("Error while sending the message for OFAC check:" + request.RequestId, e);
                AuditUtil.getInstance().audit(request.RequestId, AuditLevel.Error, "Error while sending the message for OFAC check");
            }
            finally
            {
                if (bLocked)
                {
                    _dbUtils.releaseLock(request.RequestId);
                }
            }
            return(bSuccess);
        }