예제 #1
0
        public async Task GetAll_ReturnsRepositoryData()
        {
            var repo     = new Mock <IRepository <AuditRecord> >();
            var repoData = new[]
            {
                new AuditRecord {
                    Id = "a"
                },
                new AuditRecord {
                    Id = "b"
                },
                new AuditRecord {
                    Id = "c"
                },
            };

            repo.Setup(x => x.GetAll(It.IsAny <Pagination <AuditRecord> >())).ReturnsAsync(repoData);
            var aConfig = new AuditSettings();
            var ecrs    = new[]
            {
                new EntityConfigRecord {
                    Type = typeof(AuditRecord), EventKeys = new EventKeyRecord("c", "r", "u", "d")
                }
            };
            var logger = new Mock <ILogger <AuditManager> >();
            var aSrv   = new AuditManager(repo.Object, aConfig, ecrs, null, logger.Object);
            var srvRes = await aSrv.GetAll(new AuditPagination());

            srvRes.Result.ShouldBe(ServiceResult.Ok);
            srvRes.Payload.Data.ShouldBe(repoData);
        }
예제 #2
0
        public AnyServiceConfig()
        {
            MaxMultipartBoundaryLength = 50;
            ErrorEventKey             = LoggingEvents.UnexpectedException.Name;
            MaxValueCount             = 25;
            DefaultPaginationSettings = new PaginationSettings
            {
                DefaultOrderBy   = nameof(IEntity.Id),
                DefaultOffset    = 0,
                DefaultPageSize  = 50,
                DefaultSortOrder = PaginationSettings.Asc,
            };
            FilterFactoryType         = typeof(DefaultFilterFactory);
            ModelPrepararType         = typeof(DummyModelPreparar <>);
            ServiceResponseMapperType = typeof(DataOnlyServiceResponseMapper);
            AuditSettings             = new AuditSettings
            {
                AuditRules = new AuditRules
                {
                    AuditCreate = true,
                    AuditRead   = true,
                    AuditUpdate = true,
                    AuditDelete = true,
                }
            };

            UseLogRecordEndpoint = true;
            UseErrorEndpointForExceptionHandling = true;
            MapperName = "default";
        }
예제 #3
0
 public ApplicationDbContext(
     DbContextOptions options,
     ICurrentUserService currentUserService,
     ILoggerFactory loggerFactory,
     IOptions <AuditSettings> auditSettings)
     : base(options)
 {
     _currentUserService = currentUserService;
     _loggerFactory      = loggerFactory;
     _auditSettings      = auditSettings.Value;
 }
        public bool Validate(AuditSettings sourceAuditsettings, AuditSettings targetAuditSettings, TokenParser tokenParser)
        {
            ProvisioningTemplate sourcePt = new ProvisioningTemplate();
            sourcePt.AuditSettings = sourceAuditsettings;
            var sourceXml = ExtractElementXml(sourcePt);

            ProvisioningTemplate targetPt = new ProvisioningTemplate();
            targetPt.AuditSettings = targetAuditSettings;
            var targetXml = ExtractElementXml(targetPt);

            return ValidateObjectXML(sourceXml, targetXml, null);
        }
예제 #5
0
 public ApplicationDbContext(
     DbContextOptions options,
     ICurrentUser currentUser,
     IPasswordHasher passwordHasher,
     ILoggerFactory loggerFactory,
     IOptions <AuditSettings> auditSettings)
     : base(options)
 {
     _currentUser    = currentUser;
     _passwordHasher = passwordHasher;
     _loggerFactory  = loggerFactory;
     _auditSettings  = auditSettings.Value;
 }
        public bool Validate(AuditSettings sourceAuditsettings, AuditSettings targetAuditSettings, TokenParser tokenParser)
        {
            ProvisioningTemplate sourcePt = new ProvisioningTemplate();

            sourcePt.AuditSettings = sourceAuditsettings;
            var sourceXml = ExtractElementXml(sourcePt);

            ProvisioningTemplate targetPt = new ProvisioningTemplate();

            targetPt.AuditSettings = targetAuditSettings;
            var targetXml = ExtractElementXml(targetPt);

            return(ValidateObjectXML(sourceXml, targetXml, null));
        }
예제 #7
0
 public DummyAuditManager(
     IRepository <AuditRecord> repository,
     AuditSettings auditConfig,
     IEnumerable <EntityConfigRecord> entityConfigRecords,
     IEventBus eventBus,
     ILogger <AuditManager> logger)
     : base(
         repository,
         auditConfig,
         entityConfigRecords,
         eventBus,
         logger)
 {
 }
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var auditSettings = new AuditSettings();

                var site = (web.Context as ClientContext).Site;

                site.EnsureProperties(s => s.Audit, s => s.AuditLogTrimmingRetention, s => s.TrimAuditLog);

                var siteAuditSettings = site.Audit;

                bool include = false;
                if (siteAuditSettings.AuditFlags != auditSettings.AuditFlags)
                {
                    include = true;
                    auditSettings.AuditFlags = siteAuditSettings.AuditFlags;
                }

                if (site.AuditLogTrimmingRetention != auditSettings.AuditLogTrimmingRetention)
                {
                    include = true;
                    auditSettings.AuditLogTrimmingRetention = site.AuditLogTrimmingRetention;
                }

                if (site.TrimAuditLog != auditSettings.TrimAuditLog)
                {
                    include = true;
                    auditSettings.TrimAuditLog = site.TrimAuditLog;
                }

                if (include)
                {
                    // If a base template is specified then use that one to "cleanup" the generated template model
                    if (creationInfo.BaseTemplate != null)
                    {
                        if (!auditSettings.Equals(creationInfo.BaseTemplate.AuditSettings))
                        {
                            template.AuditSettings = auditSettings;
                        }
                    }
                    else
                    {
                        template.AuditSettings = auditSettings;
                    }
                }
            }
            return(template);
        }
예제 #9
0
        public AuditManager(
            IRepository <AuditRecord> repository,
            AuditSettings auditConfig,
            IEnumerable <EntityConfigRecord> entityConfigRecords,
            IEventBus eventBus,
            ILogger <AuditManager> logger
            )
        {
            _repository          = repository;
            _auditSettings       = auditConfig;
            _entityConfigRecords = entityConfigRecords;
            _eventBus            = eventBus;
            _logger = logger;

            EventKeys ??= _entityConfigRecords.First(typeof(AuditRecord)).EventKeys;
        }
예제 #10
0
        public async Task DoesNotCreateRecord(string art)
        {
            var aSettings = new AuditSettings
            {
                AuditRules = new AuditRules()
            };
            var ecrs = new[]
            {
                new EntityConfigRecord {
                    Type = typeof(AuditRecord), EventKeys = new EventKeyRecord("c", "r", "u", "d")
                }
            };
            var am  = new AuditManager(null, aSettings, ecrs, null, null);
            var res = await am.InsertAuditRecord(null, null, art, null, null);

            res.ShouldBeNull();
        }
예제 #11
0
        public static IServiceCollection RegisterAuditServices(this IServiceCollection services, IConfiguration configuration, Action <AuditScope> onSavingAction)
        {
            var auditSettings = new AuditSettings();

            configuration.Bind(nameof(AuditSettings), auditSettings);

            Configuration.AddOnSavingAction(scope => onSavingAction(scope));

            Configuration.Setup()
            .UseElasticsearch(config => config
                              .ConnectionSettings(new AuditConnectionSettings(new SingleNodeConnectionPool(new Uri(auditSettings.Url)), new AwsHttpConnection(configuration.GetAWSOptions())))
                              .Index(auditEvent => $"demoapi.{auditEvent.EventType.ToLowerInvariant()}")
                              .Id(ev => Guid.NewGuid()));

            services.AddSingleton <IElasticClient>(provider => new ElasticClient(((ElasticsearchDataProvider)Configuration.DataProvider).ConnectionSettings));

            return(services);
        }
예제 #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Auditing Service", Version = "v1"
                });
            });

            var context = new AuditSettings(
                Configuration.GetSection("MongoConnection:ConnectionString").Value,
                Configuration.GetSection("MongoConnection:Database").Value);

            services.AddSingleton(context);

            services.AddSingleton <IAuditRepository, AuditRepository>();
        }
예제 #13
0
        public async Task GetAll_ReturnsErrorOn_RepositoryException()
        {
            var repo = new Mock <IRepository <AuditRecord> >();

            repo.Setup(x => x.GetAll(It.IsAny <Pagination <AuditRecord> >()))
            .ThrowsAsync(new Exception());
            var aConfig = new AuditSettings();
            var ecrs    = new[]
            {
                new EntityConfigRecord {
                    Type = typeof(AuditRecord), EventKeys = new EventKeyRecord("c", "r", "u", "d")
                }
            };
            var logger = new Mock <ILogger <AuditManager> >();
            var aSrv   = new AuditManager(repo.Object, aConfig, ecrs, null, logger.Object);
            var srvRes = await aSrv.GetAll(new AuditPagination());

            srvRes.Result.ShouldBe(ServiceResult.Error);
        }
예제 #14
0
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var auditSettings = new AuditSettings();

                var site = (web.Context as ClientContext).Site;

                site.EnsureProperties(s => s.Audit, s => s.AuditLogTrimmingRetention, s => s.TrimAuditLog);

                var siteAuditSettings = site.Audit;

                bool include = false;
                if (siteAuditSettings.AuditFlags != auditSettings.AuditFlags)
                {
                    include = true;
                    auditSettings.AuditFlags = siteAuditSettings.AuditFlags;
                }

                if (site.AuditLogTrimmingRetention != auditSettings.AuditLogTrimmingRetention)
                {
                    include = true;
                    auditSettings.AuditLogTrimmingRetention = site.AuditLogTrimmingRetention;
                }

                if (site.TrimAuditLog != auditSettings.TrimAuditLog)
                {
                    include = true;
                    auditSettings.TrimAuditLog = site.TrimAuditLog;
                }

                if (include)
                {
                    template.AuditSettings = auditSettings;
                }
            }
            return template;
        }
예제 #15
0
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var auditSettings = new AuditSettings();

                var site = (web.Context as ClientContext).Site;

                site.EnsureProperties(s => s.Audit, s => s.AuditLogTrimmingRetention, s => s.TrimAuditLog);

                var siteAuditSettings = site.Audit;

                bool include = false;
                if (siteAuditSettings.AuditFlags != auditSettings.AuditFlags)
                {
                    include = true;
                    auditSettings.AuditFlags = siteAuditSettings.AuditFlags;
                }

                if (site.AuditLogTrimmingRetention != auditSettings.AuditLogTrimmingRetention)
                {
                    include = true;
                    auditSettings.AuditLogTrimmingRetention = site.AuditLogTrimmingRetention;
                }

                if (site.TrimAuditLog != auditSettings.TrimAuditLog)
                {
                    include = true;
                    auditSettings.TrimAuditLog = site.TrimAuditLog;
                }

                if (include)
                {
                    template.AuditSettings = auditSettings;
                }
            }
            return(template);
        }
예제 #16
0
        public async Task CreatesNewRecord()
        {
            var aSettings = new AuditSettings
            {
                AuditRules = new AuditRules
                {
                    AuditCreate = true
                }
            };
            string eId        = "entity-id",
                   createdKey = "c";
            var data          = new TestClass();
            var dbData        = new AuditRecord();
            var wc            = new WorkContext
            {
            };
            var ecrs = new[]
            {
                new EntityConfigRecord {
                    Type = typeof(AuditRecord), EntityKey = eId, EventKeys = new EventKeyRecord(createdKey, "r", "u", "d")
                },
                new EntityConfigRecord {
                    Type = typeof(TestClass), Name = "name", EntityKey = "test-class", EventKeys = new EventKeyRecord("ccc", "r", "u", "d")
                }
            };
            var repo = new Mock <IRepository <AuditRecord> >();

            repo.Setup(r => r.Insert(It.IsAny <AuditRecord>())).ReturnsAsync(dbData);
            var eb     = new Mock <IEventBus>();
            var logger = new Mock <ILogger <AuditManager> >();

            var am  = new AuditManager(repo.Object, aSettings, ecrs, eb.Object, logger.Object);
            var res = await am.InsertAuditRecord(typeof(TestClass), eId, AuditRecordTypes.CREATE, wc, data);

            res.ShouldNotBeNull();
            eb.Verify(e => e.Publish(It.Is <string>(s => s == createdKey), It.Is <DomainEvent>(ded => ded.Data == dbData)), Times.Once);
        }
예제 #17
0
        /// <summary>
        /// Audits the item based on the sent id and collection
        /// </summary>
        /// <remarks>Error codes follow the format DAL-DMB-4XX</remarks>
        /// <typeparam name="T">The type of the object to audit</typeparam>
        /// <param name="items">An IEnumerable list of items to audit</param>
        /// <param name="auditCollectionName">The collection name for the audit</param>
        /// <param name="auditSettingsKey">Optional audit setting key to reference the AuditSettings dictionary</param>
        /// <param name="auditUser">Optional string for the audit user</param>
        /// <param name="auditCapSize">Optional int to set the audit cap size</param>
        public async Task AuditItems(string[] ids, string collectionName, string auditCollectionName, string auditSettingsKey = null, string auditUser = null, int auditCapSize = 100)
        {
            //set audit by default value item has not yet been created
            bool auditItem = AuditByDefault;

            if (auditItem)
            {
                //check the audit settings allow
                try
                {
                    auditItem = (!String.IsNullOrEmpty(auditSettingsKey) && AuditSettings != null && AuditSettings.ContainsKey(auditSettingsKey)) ? bool.Parse(AuditSettings[auditSettingsKey]) : auditItem;
                }
                catch { }
            }
            //audit item if set
            if (auditItem)
            {
                try
                {
                    auditCapSize = (!String.IsNullOrEmpty(auditCollectionName + ".Size") && AuditSettings != null && AuditSettings.ContainsKey(auditCollectionName + ".Size")) ? int.Parse(AuditSettings[auditCollectionName + ".Size"]) : auditCapSize;
                }
                catch { }
                FilterDefinitionBuilder <BaseIdWithQuickSearchModel> filterBuilder = Builders <BaseIdWithQuickSearchModel> .Filter;
                var filter = filterBuilder.Empty;
                filter = filter & filterBuilder.Where(w => ids.Contains(w.Id));
                var collection = Repository.Database.GetCollection <BaseIdWithQuickSearchModel>(collectionName);
                var items      = await collection.Find(filter).ToListAsync <BaseIdWithQuickSearchModel>();

                foreach (var item in items)
                {
                    await AuditManager.AuditItem <BaseIdWithQuickSearchModel>(Repository.Database, item, false, auditCollectionName, auditUser, auditCapSize);
                }
            }
        }
예제 #18
0
        /// <summary>
        /// Audits the item based on the sent id and collection
        /// </summary>
        /// <remarks>Error codes follow the format DAL-DMB-4XX</remarks>
        /// <typeparam name="T">The type of the object to audit</typeparam>
        /// <param name="id">The id of the item to audit</param>
        /// <param name="collectionName">The collection name of the audit item</param>
        /// <param name="auditCollectionName">The collection name for the audit</param>
        /// <param name="auditSettingsKey">Optional audit setting key to reference the AuditSettings dictionary</param>
        /// <param name="auditUser">Optional string for the audit user</param>
        /// <param name="auditCapSize">Optional int to set the audit cap size</param>
        public async Task AuditItem <T>(string id, string collectionName, string auditCollectionName, string auditSettingsKey = null, string auditUser = null, int auditCapSize = 100)
        {
            //set audit by default value item has not yet been created
            bool auditItem = AuditByDefault;

            if (auditItem)
            {
                //check the audit settings allow
                try
                {
                    auditItem = (!String.IsNullOrEmpty(auditSettingsKey) && AuditSettings != null && AuditSettings.ContainsKey(auditSettingsKey)) ? bool.Parse(AuditSettings[auditSettingsKey]) : auditItem;
                }
                catch { }
            }
            //audit item if set
            if (auditItem)
            {
                try
                {
                    auditCapSize = (!String.IsNullOrEmpty(auditCollectionName + ".Size") && AuditSettings != null && AuditSettings.ContainsKey(auditCollectionName + ".Size")) ? int.Parse(AuditSettings[auditCollectionName + ".Size"]) : auditCapSize;
                }
                catch { }
                T item = await SearchManager.Find <T>(Repository.Database, collectionName, id, WorkingClientId);

                await AuditManager.AuditItem <T>(Repository.Database, item, false, auditCollectionName, auditUser, auditCapSize);
            }
        }
예제 #19
0
        /// <summary>
        /// Audits the item based on the sent id and collection
        /// </summary>
        /// <remarks>Error codes follow the format DAL-DMB-4XX</remarks>
        /// <typeparam name="T">The type of the object to audit</typeparam>
        /// <param name="items">An IEnumerable list of items to audit</param>
        /// <param name="auditCollectionName">The collection name for the audit</param>
        /// <param name="auditSettingsKey">Optional audit setting key to reference the AuditSettings dictionary</param>
        /// <param name="auditUser">Optional string for the audit user</param>
        /// <param name="auditCapSize">Optional int to set the audit cap size</param>
        public async Task AuditItems <T>(IEnumerable <T> items, string auditCollectionName, string auditSettingsKey = null, string auditUser = null, int auditCapSize = 100)
        {
            //set audit by default value item has not yet been created
            bool auditItem = AuditByDefault;

            if (auditItem)
            {
                //check the audit settings allow
                try
                {
                    auditItem = (!String.IsNullOrEmpty(auditSettingsKey) && AuditSettings != null && AuditSettings.ContainsKey(auditSettingsKey)) ? bool.Parse(AuditSettings[auditSettingsKey]) : auditItem;
                }
                catch { }
            }
            //audit item if set
            if (auditItem)
            {
                try
                {
                    auditCapSize = (!String.IsNullOrEmpty(auditCollectionName + ".Size") && AuditSettings != null && AuditSettings.ContainsKey(auditCollectionName + ".Size")) ? int.Parse(AuditSettings[auditCollectionName + ".Size"]) : auditCapSize;
                }
                catch { }
                foreach (var item in items)
                {
                    await AuditManager.AuditItem <T>(Repository.Database, item, false, auditCollectionName, auditUser, auditCapSize);
                }
            }
        }
예제 #20
0
        /// <summary>
        /// Audits the sent item
        /// </summary>
        /// <remarks>Error codes follow the format DAL-DMB-5XX</remarks>
        /// <typeparam name="T">The type of the object to audit</typeparam>
        /// <param name="item">The item to audit</param>
        /// <param name="auditCollectionName">The collection name for the audit</param>
        /// <param name="auditSettingsKey">Optional audit setting key to reference the AuditSettings dictionary</param>
        /// <param name="auditUser">Optional string for the audit user</param>
        public async Task AuditItem <T>(T item, string auditCollectionName, string auditSettingsKey = null, string auditUser = null)
        {
            //set the user name if sent
            if (!String.IsNullOrEmpty(AuditUser) && String.IsNullOrEmpty(auditUser))
            {
                auditUser = AuditUser;
            }
            //create the new item or update the item audit fields
            bool newItem = (item is IAuditFieldsWithId) ? AuditManager.SetAuditFields(item as IAuditFieldsWithId, auditUser) : true;
            //set audit by default value item has not yet been created
            bool auditItem = AuditByDefault;

            if (auditItem)
            {
                //check the audit settings allow
                auditItem = (!String.IsNullOrEmpty(auditSettingsKey) && AuditSettings != null && AuditSettings.ContainsKey(auditSettingsKey))? bool.Parse(AuditSettings[auditSettingsKey]) : auditItem;
            }
            //audit item if set
            if (auditItem)
            {
                await AuditManager.AuditItem <T>(Repository.Database, item, newItem, auditCollectionName, auditUser);
            }
        }