Example #1
0
 public void Setup()
 {
     _provider     = new Mock <IAuditProvider>();
     controllerObj = new AuditCheckListController(_provider.Object);
     _repo         = new Mock <IAuditRepository>();
     _auditprov    = new AuditProvider(_repo.Object);
 }
Example #2
0
        public static void Log(int AuditingLevel, string UserName = "******")
        {
            //Stores the Request in an Accessible object
            var request = HttpContext.Current.Request;

            //Generate the appropriate key based on the user's Authentication Cookie
            //This is overkill as you should be able to use the Authorization Key from
            //Forms Authentication to handle this.
            HttpSessionState sessionValue      = HttpContext.Current.Session;
            string           sessionIdentifier = string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(sessionValue.SessionID.ToString())).Select(s => s.ToString("x2")));
            //string sessionIdentifier = string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(request.Cookies[FormsAuthentication.FormsCookieName].Value)).Select(s => s.ToString("x2")));

            //Generate an audit
            AuditVM audit = new AuditVM()
            {
                SessionID    = sessionIdentifier,
                IPAddress    = RequestHelpers.GetClientIpAddress(request),
                URLAccessed  = request.RawUrl,
                TimeAccessed = DateTime.Now,
                UserName     = (request.IsAuthenticated) ? HttpContext.Current.User.Identity.Name : UserName,
                //HttpContext.Current.Controller.GetType().Name,
                //HttpContext.Current.ActionDescriptor.ActionName,
                //HttpContext.Current.ActionDescriptor.GetParameters(),

                Data = RequestHelpers.SerializeRequest(request, AuditingLevel)
            };

            AuditProvider.Add(audit);
        }
 internal void LogAuditChanges(Project project)
 {
     // Record changes
     AuditProvider.LogChanges(
         ServiceContext.PortfolioContext,
         (ts, txt) => auditLogFactory(ts, txt),
         project.AuditLogs,
         DateTime.Now);
 }
Example #4
0
        public void Audit_With_FileConfiguration_Should_Create_Valid_Audit_File()
        {
            var fileName = "test-audit-log.json";
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);

            // Make sure the testing audit file does not exist
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            // Audit entry setup
            var auditProvider = new AuditProvider(new FileAuditingConfiguration
            {
                DirectoryPath   = AppDomain.CurrentDomain.BaseDirectory,
                FilenameBuilder = () => fileName
            });

            var auditEntry = auditProvider.Entry();

            auditEntry.Payload    = "Payload";
            auditEntry.Originator = "Originator";
            auditEntry.Process    = "RegisterUser";
            auditEntry.EventType  = "Register user";
            auditEntry.Data.Process["ProcessInfo"] = "Some process info";
            auditEntry.Data.Source["SourceInfo"]   = "Some source info";

            auditProvider.Audit(auditEntry, () =>
            {
                Thread.Sleep(100);
            });

            // Check if the audit file has been created
            Assert.True(File.Exists(filePath));

            // Read the audit file and deserialize it to audit entry
            var content = File.ReadAllText(filePath);
            var entry   = JsonConvert.DeserializeObject <AuditEntry>(content);

            Assert.NotNull(entry);
            Assert.Equal("Payload", entry.Payload);
            Assert.Equal("Originator", entry.Originator);
            Assert.Equal("RegisterUser", entry.Process);
            Assert.Equal("Register user", entry.EventType);
            Assert.Equal("Some process info", entry.Data.Process["ProcessInfo"]);
            Assert.Equal("Some source info", entry.Data.Source["SourceInfo"]);

            // Clean up
            File.Delete(filePath);
        }
Example #5
0
 public AgentInstanceContext(
     StatementContext statementContext,
     EPStatementAgentInstanceHandle epStatementAgentInstanceHandle,
     AgentInstanceFilterProxy agentInstanceFilterProxy,
     MappedEventBean contextProperties,
     AuditProvider auditProvider,
     InstrumentationCommon instrumentationProvider)
 {
     StatementContext = statementContext;
     FilterVersionAfterAllocation = statementContext.FilterService.FiltersVersion;
     EpStatementAgentInstanceHandle = epStatementAgentInstanceHandle;
     AgentInstanceFilterProxy = agentInstanceFilterProxy;
     _contextProperties = contextProperties;
     AuditProvider = auditProvider;
     InstrumentationProvider = instrumentationProvider;
 }
Example #6
0
        public void Audit_With_Existing_DatabaseConfiguration_Should_Insert_Valid_Audit_Log()
        {
            var databaseConfiguration = new DatabaseAuditingConfiguration
            {
                TableName        = "AuditLogTest2",
                ConnectionString = "Server=[SERVER];Database=[DB];User Id=[USR];Password=[PWD];"
            };

            using (var connection = new SqlConnection(databaseConfiguration.ConnectionString))
            {
                connection.Open();

                // Make sure the table exists
                var createTableSql =
                    $@"
                        IF NOT EXISTS 
                        (	
                            SELECT * 
	                        FROM sys.tables t
	                        WHERE t.name = '{databaseConfiguration.TableName}'
                        ) 
                        BEGIN
                            CREATE TABLE [{databaseConfiguration.TableName}]
                            (
                                [Id] INT IDENTITY(1,1) NOT NULL, 
                                [Process] NVARCHAR(MAX),
                                [ProcessInstanceId] NVARCHAR(MAX),
                                [Payload] NVARCHAR(MAX),
                                [EventType] NVARCHAR(MAX),
                                [Originator] NVARCHAR(MAX),
                                [StartDate] datetime2(7),
                                [EndDate] datetime2(7),
                                [Data] NVARCHAR(MAX)
                            )
                        END
                        DELETE FROM [{databaseConfiguration.TableName}]
                    ";

                var command = new SqlCommand(createTableSql, connection);
                command.ExecuteNonQuery();

                var auditProvider = new AuditProvider(databaseConfiguration);

                var auditEntry = auditProvider.Entry();
                auditEntry.Originator = "Originator";
                auditEntry.Process    = "RegisterUser";
                auditEntry.EventType  = "Register user";
                auditEntry.Payload    = "Payload";
                auditEntry.Data.Process["ProcessInfo"] = "Some process info";
                auditEntry.Data.Source["SourceInfo"]   = "Some source info";

                auditProvider.Audit(auditEntry, () =>
                {
                    Thread.Sleep(100);
                });

                // Retrieve the audit from the database
                var getAuditSql =
                    $@"
                        SELECT * FROM [{databaseConfiguration.TableName}]
                    ";

                command = new SqlCommand(getAuditSql, connection);
                var reader = command.ExecuteReader();

                // Make sure there is at least one audit entry
                Assert.True(reader.HasRows);

                while (reader.Read())
                {
                    Assert.Equal("Payload", reader["Payload"].ToString());
                    Assert.Equal("Originator", reader["Originator"].ToString());
                    Assert.Equal("RegisterUser", reader["Process"].ToString());
                    Assert.Equal("Register user", reader["EventType"].ToString());

                    // Deserialize the Data object and check its values
                    var content   = reader["Data"].ToString();
                    var entryData = JsonConvert.DeserializeObject <AuditEntryData>(content);

                    Assert.Equal("Some process info", entryData.Process["ProcessInfo"]);
                    Assert.Equal("Some source info", entryData.Source["SourceInfo"]);
                }
                reader.Close();

                // Cleanup
                var cleanUpSql = $@"DELETE FROM {databaseConfiguration.TableName}";
                command = new SqlCommand(cleanUpSql, connection);
                command.ExecuteNonQuery();

                connection.Close();
            }
        }
        public async Task UpdateConfigAsync(string viewKey, PortfolioConfigUpdateRequest update)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(viewKey))
                {
                    viewKey = update.ViewKey;
                }

                var context = ServiceContext.PortfolioContext;

                // Map the updates to labels
                var labelUpdates = PortfolioMapper.ConfigMapper.Map <IEnumerable <PortfolioLabelConfig> >(update.Labels);

                // Get the config with labels
                var config = await context.PortfolioConfigurations
                             .IncludeFullConfiguration()
                             .Where(p => p.Portfolio.ViewKey == viewKey)
                             .SingleAsync();

                ServiceContext.AssertAdmin(config.Portfolio);

                // Update the labels
                foreach (var labelUpdate in labelUpdates)
                {
                    var label = config.Labels.Single(l => l.FieldName == labelUpdate.FieldName);
                    PortfolioMapper.UpdateMapper.Map(labelUpdate, label);
                }

                // Record changes
                AuditProvider.LogChanges(
                    context,
                    (ts, txt) => auditLogFactory(config, nameof(PortfolioLabelConfig), ts, txt),
                    context.PortfolioConfigAuditLogs,
                    DateTime.Now);

                // Map the collections here: don't do this in mapping because can't use async in resolvers
                await UpdateCollections(config);
            }
            catch (PortfolioConfigurationException pce)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = pce.Message
                };
                throw new HttpResponseException(resp);
            }
            catch (DbEntityValidationException e)
            {
                var stringBuilder = new StringBuilder();
                foreach (var eve in e.EntityValidationErrors)
                {
                    var label = eve.Entry.Entity as PortfolioLabelConfig;
                    if (label != null)
                    {
                        stringBuilder.Append($"Problem with configuration for field {label.FieldTitle}: ");
                        stringBuilder.Append(string.Join("; ", eve.ValidationErrors.Select(ve => ve.ErrorMessage)));
                    }
                    else
                    {
                        stringBuilder.Append($"Contact administrator: unrecognised issue with configuration update.");
                    }
                }
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = stringBuilder.ToString()
                };
                throw new HttpResponseException(resp);
            }
            catch (Exception e)
            {
                AppLog.Trace(e);
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = e.Message
                };
                throw new HttpResponseException(resp);
            }
        }