public void Test_CheckAccess_NoEntities()
        {
            MockRepository               mockRepository;
            EntityAccessControlChecker   entityAccessControlChecker;
            Mock <IUserRoleRepository>   roleRepository;
            Mock <IQueryRepository>      queryRepository;
            Mock <IEntityTypeRepository> entityTypeRepository;
            IDictionary <long, bool>     result;
            UserAccount userAccount;

            userAccount = Entity.Get <UserAccount>(RequestContext.GetContext().Identity.Id);

            mockRepository = new MockRepository(MockBehavior.Strict);

            roleRepository             = mockRepository.Create <IUserRoleRepository>();
            queryRepository            = mockRepository.Create <IQueryRepository>();
            entityTypeRepository       = mockRepository.Create <IEntityTypeRepository>();
            entityAccessControlChecker = new EntityAccessControlChecker(roleRepository.Object,
                                                                        queryRepository.Object,
                                                                        entityTypeRepository.Object);
            result = entityAccessControlChecker.CheckAccess(new Collection <EntityRef>(),
                                                            new[] { Permissions.Read },
                                                            userAccount);

            mockRepository.VerifyAll();

            Assert.That(result, Is.Empty);
        }
        public void Test_GetQueries_NullPermission( )
        {
            Role       testSubject;
            EntityType testSecurableEntityType;
            IEnumerable <AccessRuleQuery> result;
            AccessRule      accessRule;
            Report          report;
            QueryRepository queryRepository;

            using (DatabaseContext.GetContext(true))
            {
                testSecurableEntityType = Entity.Create <EntityType>( );
                testSecurableEntityType.Save( );

                report = TestQueries.Entities( ).ToReport( );
                report.Save( );

                accessRule = Entity.Create <AccessRule>( );
                accessRule.AccessRuleEnabled = true;
                accessRule.PermissionAccess.Add(Entity.Get <Permission>(Permissions.Read));
                accessRule.ControlAccess    = testSecurableEntityType.As <SecurableEntity>( );
                accessRule.AccessRuleReport = report;
                accessRule.Save( );

                testSubject = Entity.Create <Role>( );
                testSubject.AllowAccess.Add(accessRule.As <AccessRule>( ));
                testSubject.Save( );

                queryRepository = new QueryRepository( );
                result          = new List <AccessRuleQuery>(queryRepository.GetQueries(testSubject.Id,
                                                                                        null, new [] { testSecurableEntityType.Id }));

                Assert.That(result, Is.Not.Empty);
            }
        }
Example #3
0
        public void EntityGetMatchesWithRelationship2( )
        {
            var stringField      = Entity.Get <EntityType>(new EntityRef("core", "stringField"));
            var fieldIsOnTypeRel = Entity.Get <Relationship>(new EntityRef("core", "fieldIsOnType"));

            var query = new StructuredQuery
            {
                RootEntity = new ResourceEntity(stringField)
            };

            // Root query type is 'EntityType'

            // Follow 'Fields' relationship
            var relatedResource = new RelatedResource
            {
                RelationshipDirection = RelationshipDirection.Forward,
                RelationshipTypeId    = fieldIsOnTypeRel.Id,
                ResourceMustExist     = false
            };

            query.RootEntity.RelatedEntities.Add(relatedResource);

            //// check the condition
            query.Conditions.Add(new QueryCondition
            {
                Expression = new ResourceDataColumn(relatedResource, EntityType.Name_Field),
                Operator   = ConditionType.Equal,
                Argument   = new TypedValue("Person")
            });

            IEnumerable <Field> descriptionStringFields = Entity.GetMatches <Field>(query);

            Assert.IsTrue(descriptionStringFields.Any( ), "There should be at least one person type");
        }
        public void Test_AddAllowCreate_AllowMultipleCreate()
        {
            EntityType[]             securableEntityTypes;
            const int                numTypes = 5;
            Subject                  subject;
            IDictionary <long, bool> result;

            IEntity[] entities;

            subject = Entity.Create <UserAccount>().As <Subject>();
            subject.Save();

            securableEntityTypes = new EntityType[numTypes];
            for (int i = 0; i < numTypes; i++)
            {
                securableEntityTypes[i] = Entity.Create <EntityType>();
                securableEntityTypes[i].Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityTypes[i].Save();

                new AccessRuleFactory().AddAllowCreate(subject, securableEntityTypes[i].As <SecurableEntity>());
            }

            entities = new IEntity[numTypes];
            for (int i = 0; i < numTypes; i++)
            {
                entities[i] = Entity.Create(securableEntityTypes[i]);
            }

            result = new EntityAccessControlChecker().CheckAccess(entities.Select(x => new EntityRef(x)).ToList(),
                                                                  new[] { Permissions.Create }, subject);

            Assert.That(result, Has.Count.EqualTo(numTypes));
            Assert.That(result.Keys, Is.EquivalentTo(entities.Select(x => x.Id)));
            Assert.That(result.Values, Has.All.True);
        }
        private void Do_AddAllowXXXQuery_AllowSingleXXXAddTwice(EntityRef permission)
        {
            EntityType       securableEntityType;
            IEntity          entity;
            Subject          subject;
            List <EntityRef> permissions;

            using (DatabaseContext.GetContext(true))
            {
                permissions = new List <EntityRef>()
                {
                    permission
                };

                securableEntityType = Entity.Create <EntityType>();
                securableEntityType.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType.Save();
                entity = Entity.Create(new EntityRef(securableEntityType.Id));
                entity.SetField("core:name", "Entity 1");
                entity.Save();
                subject = Entity.Create <UserAccount>().As <Subject>();
                subject.Save();

                new AccessRuleFactory().AddAllowByQuery(subject, securableEntityType.As <SecurableEntity>(), permissions, TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllowByQuery(subject, securableEntityType.As <SecurableEntity>(), permissions, TestQueries.Entities().ToReport());

                Assert.That(new EntityAccessControlChecker().CheckAccess(new[] { new EntityRef(entity.Id) }, permissions, subject),
                            Has.Exactly(1).Property("Key").EqualTo(entity.Id).And.Property("Value").True);
                Assert.That(subject.AllowAccess.Select(x => x.ControlAccess),
                            Has.Exactly(2).Property("Id").EqualTo(securableEntityType.Id));
                Assert.That(subject.AllowAccess.Where(x => x.ControlAccess.Id == securableEntityType.Id).SelectMany(x => x.PermissionAccess),
                            Has.Exactly(2).Property("Id").EqualTo(permission.Id));
            }
        }
        private void Do_AddAllowXXXQuery_AllowMultiple(Action <Subject, SecurableEntity> addAccess, ICollection <EntityRef> operations)
        {
            EntityType securableEntityType;
            const int  numEntities = 5;

            Entity[] entities;
            Subject  subject;
            IDictionary <long, bool> result;

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType = Entity.Create <EntityType>();
                securableEntityType.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType.Save();
                entities = new Entity[numEntities];
                for (int i = 0; i < numEntities; i++)
                {
                    entities[i] = Entity.Create(new EntityRef(securableEntityType.Id)).As <Entity>();
                    entities[i].Save();
                }
                subject = Entity.Create <UserAccount>().As <Subject>();
                subject.Save();

                addAccess(subject, securableEntityType.As <SecurableEntity>());

                result = new EntityAccessControlChecker().CheckAccess(entities.Select(x => (EntityRef)x).ToList(),
                                                                      operations.ToList(), subject);
                for (int i = 0; i < numEntities; i++)
                {
                    Assert.That(result,
                                Has.Exactly(1).Property("Key").EqualTo(entities[i].Id).And.Property("Value").True);
                }
            }
        }
Example #7
0
        private void CreateAccessRules(IAccessRuleFactory accessRuleFactory, IAccessRuleReportFactory accessRuleReportFactory,
                                       Subject subject, IList <string> typeNames, IList <EntityRef> permissions, string aliasTemplate,
                                       Solution solution = null)
        {
            AccessRule accessRule;

            foreach (string typeName in typeNames)
            {
                SecurableEntity targetType = Entity.Get <SecurableEntity>(typeName);
                Assert.That(targetType, Is.Not.Null,
                            string.Format("Type {0} does not exist", typeName));

                accessRule = accessRuleFactory.AddAllowByQuery(
                    subject,
                    targetType,
                    permissions,
                    accessRuleReportFactory.GetDisplayReportForSecurableEntity(targetType));
                accessRule                  = accessRule.AsWritable <AccessRule>();
                accessRule.Alias            = string.Format(aliasTemplate, new EntityRef(typeName).Alias);
                accessRule.AccessRuleHidden = true;
                if (solution != null)
                {
                    accessRule.InSolution = solution;
                }

                accessRule.Save();

                Console.WriteLine("Create access rule {0} {1}", accessRule.Alias, accessRule.Id);
            }
        }
Example #8
0
        public void SelfServeReportGrant( )
        {
            IAccessRuleFactory       accessRuleFactory;
            IAccessRuleReportFactory accessRuleReportFactory;
            Subject  selfServeRole;
            Solution coreDataSolution;

            accessRuleReportFactory = new AccessRuleDisplayReportFactory( );
            accessRuleFactory       = new AccessRuleFactory( );
            using (DatabaseContext databaseContext = DatabaseContext.GetContext(true))
                using (new SecurityBypassContext( ))
                {
                    selfServeRole    = Entity.Get <Subject>("core:selfServeRole", true);
                    coreDataSolution = CodeNameResolver.GetInstance("ReadiNow Core Data", "Application").As <Solution>( );

                    // Allow the test to be rerun by re-enabling the allow all Administrators access rule
                    //EnableAdministratorAccessAllRule( );

                    // Create access rules
                    //DeleteAccessRules( ReportTypeNames, SelfServeCreateAccessRuleNameTemplate );
                    CreateAccessRules(
                        accessRuleFactory,
                        accessRuleReportFactory,
                        selfServeRole,
                        SelfServeTypeNames,
                        new [] { Permissions.Create },
                        "core:createSelfServeComponentsAccessRule",
                        coreDataSolution);

                    // Disable the "allow all" administrator access rule
                    //DisableAdministratorAccessAllRule( );

                    databaseContext.CommitTransaction( );
                }
        }
Example #9
0
        public void HideCoreEveryoneRoles()
        {
            IList <AccessRule> accessRules;
            Solution           consoleSolution;

            using (DatabaseContext databaseContext = DatabaseContext.GetContext(true))
                using (new SecurityBypassContext())
                {
                    consoleSolution = Entity.Get <Solution>("core:consoleSolution");

                    accessRules = Entity.GetInstancesOfType <AccessRule>(false, "accessRuleHidden, allowAccess.{alias}, inSolution.{name}, controlAccess.{name}")
                                  .ToList();
                    foreach (AccessRule accessRule in accessRules)
                    {
                        if (accessRule.AllowAccessBy.Alias == "core:everyoneRole" &&
                            accessRule.InSolution != null && accessRule.InSolution.Name == "ReadiNow Core Data")
                        {
                            AccessRule writeableAccessRule = accessRule.AsWritable <AccessRule>();
                            writeableAccessRule.AccessRuleHidden = true;

                            if (writeableAccessRule.InSolution == consoleSolution)
                            {
                                writeableAccessRule.InSolution = null;
                            }

                            Console.Out.WriteLine("Making access rule on type {0} hidden", writeableAccessRule.ControlAccess.Name);

                            writeableAccessRule.Save();
                        }
                    }

                    databaseContext.CommitTransaction();
                }
        }
        public void GetQueriesAsDefaultTenant()
        {
            var factory = new SystemAccessRuleQueryFactory();
            var queries = factory.GetQueries();

            Assert.IsNotNull(queries, "The system access queries should not be null.");
            Assert.AreNotEqual(0, queries.Count, "The count of system access queries should not be 0.");

            using (new SecurityBypassContext())
            {
                // Verify the system rules
                foreach (var kvp in queries)
                {
                    var subjectPermission = kvp.Key;
                    var accessRuleQueries = kvp.Value;

                    Assert.IsNotNull(Entity.Get <Subject>(subjectPermission.SubjectId), "The subject does not exist.");
                    Assert.IsNotNull(Entity.Get <Permission>(subjectPermission.PermissionId), "The permission does not exist.");

                    foreach (var accessRuleQuery in accessRuleQueries)
                    {
                        Assert.IsNotNull(Entity.Get <EntityType>(accessRuleQuery.ControlsAccessForTypeId), "The entity types does not exist.");
                        Assert.IsNotNull(accessRuleQuery.Query, "The query should not be null.");

                        QueryResult result = Factory.QueryRunner.ExecuteQuery(accessRuleQuery.Query, new QuerySettings()
                        {
                            SecureQuery = false
                        });
                        Assert.AreNotEqual(0, result.Columns.Count, "The number of columns is invalid");
                        Assert.IsTrue(result.Columns[0].ColumnType is IdentifierType, "The column type is invalid.");
                    }
                }
            }
        }
        public void Test_AddAllowReadQuery_NameQuery()
        {
            using (DatabaseContext.GetContext(true))
            {
                EntityType securableEntityType1;
                IEntity    entity1A;
                IEntity    entity1Z;
                Subject    subject;
                Report     report;
                IDictionary <long, bool> result;

                securableEntityType1 = Entity.Create <EntityType>();
                securableEntityType1.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType1.Save();
                entity1A = Entity.Create(new EntityRef(securableEntityType1.Id));
                entity1A.SetField("core:name", "A");
                entity1A.Save();
                entity1Z = Entity.Create(new EntityRef(securableEntityType1.Id));
                entity1Z.SetField("core:name", "Z");
                entity1Z.Save();
                subject = Entity.Create <UserAccount>().As <Subject>();
                subject.Save();
                report = TestQueries.EntitiesWithNameA().ToReport();

                new AccessRuleFactory().AddAllowReadQuery(subject, securableEntityType1.As <SecurableEntity>(), report);

                result = new EntityAccessControlChecker().CheckAccess(
                    new[] { new EntityRef(entity1A.Id), new EntityRef(entity1Z.Id) },
                    new[] { Permissions.Read },
                    subject);
                Assert.That(result, Has.Property("Count").EqualTo(2));
                Assert.That(result, Has.Exactly(1).Property("Key").EqualTo(entity1A.Id).And.Property("Value").True);
                Assert.That(result, Has.Exactly(1).Property("Key").EqualTo(entity1Z.Id).And.Property("Value").False);
            }
        }
Example #12
0
        public void TestReportsReportFiltersReportsAssignedToAccessRules( )
        {
            using (new SecurityBypassContext( ))
            {
                var reportsReport = Entity.Get <ReadiNow.Model.Report>("k:reportsReport");

                var          reportInterface = new ReportingInterface( );
                ReportResult result          = reportInterface.RunReport(reportsReport, null);

                var errors = new StringBuilder( );

                foreach (DataRow row in from row in result.GridData let report = Entity.Get <ReadiNow.Model.Report>(row.EntityId) where report != null where report.ReportForAccessRule != null select row)
                {
                    if (errors.Length > 0)
                    {
                        errors.Append(",");
                    }
                    errors.AppendFormat("{0}", row.EntityId);
                }

                if (errors.Length > 0)
                {
                    errors.Insert(0, "The following reports are assigned to access rules: ");
                    Assert.Fail(errors.ToString( ));
                }
            }
        }
Example #13
0
        public void TestReportWithWriteOnlyField(bool isFieldWriteOnly)
        {
            try
            {
                var field = Entity.Get <Field>("test:afString", true);
                field.IsFieldWriteOnly = isFieldWriteOnly;
                field.Save();

                IEnumerable <IEntity> reports = Entity.GetByName("AF_String");

                var          reportInterface = new ReportingInterface();
                ReportResult result          = reportInterface.RunReport(reports.First().Id, null);

                if (isFieldWriteOnly)
                {
                    Assert.IsTrue(result.GridData.All(d => string.IsNullOrEmpty(d.Values[1].Value)), "We should not have any values");
                }
                else
                {
                    Assert.IsTrue(result.GridData.Any(d => !string.IsNullOrEmpty(d.Values[1].Value)), "We should have at least 1 value");
                }
            }
            finally
            {
                CacheManager.ClearCaches();
            }
        }
        public IHttpActionResult GetDocoSettings()
        {
            using (new GlobalAdministratorContext())
            {
                var docoSettingEntity = EntityModel.Get <SystemDocumentationSettings>("core:systemDocumentationSettingsInstance");

                if (docoSettingEntity == null)
                {
                    return(Ok());
                }

                var passwordSecureId = docoSettingEntity.DocumentationUserPasswordSecureId;

                var docoSettings = new DocoSettingsResult()
                {
                    DocumentationUserName     = docoSettingEntity.DocumentationUserName,
                    DocumentationUserPassword = passwordSecureId != null?Factory.SecuredData.Read(passwordSecureId.Value) : null,
                                                    DocumentationUrl          = docoSettingEntity.DocumentationUrl,
                                                    ContactSupportUrl         = docoSettingEntity.ContactSupportUrl,
                                                    ReleaseNotesUrl           = docoSettingEntity.ReleaseNotesUrl,
                                                    NavHeaderDocumentationUrl = docoSettingEntity.NavHeaderDocumentationUrl
                };

                return(Ok(docoSettings));
            }
        }
Example #15
0
        /// <summary>
        /// Creates an action menu item.
        /// </summary>
        /// <typeparam name="T">The action menu item implementation.</typeparam>
        /// <param name="name">The name of the menu item.</param>
        /// <param name="emptySelectName">The name to show when selection is empty.</param>
        /// <param name="multiSelectName">The name to show when there are multiple selections.</param>
        /// <param name="order">The ordinal of the menu item.</param>
        /// <param name="isMenu">True if the menu item has been or is to be included in the menu.</param>
        /// <param name="isContextMenu">True if the menu item shows on right click.</param>
        /// <param name="isButton">True if the menu item renders as a button.</param>
        /// <param name="isSeperator">True if this is just a separator for other items.</param>
        /// <param name="isSystem">True if this is a system reserved action menu item.</param>
        /// <param name="singleSelect">True if this menu item applies to single selection.</param>
        /// <param name="multiSelect">True if this menu item applies to multi selection.</param>
        /// <param name="requiredPermissions">Any permission required by this item to appear.</param>
        /// <param name="method">The method string indicating item behavior.</param>
        /// <param name="state">The state information modifying behaviour of the method above.</param>
        /// <param name="target">Optional specific information about the target this item should apply to.</param>
        /// <returns>The created action menu item entity.</returns>
        public static T CreateActionItem <T>(string name, string emptySelectName, string multiSelectName, int?order,
                                             bool isMenu, bool isContextMenu, bool isButton, bool isSeperator, bool isSystem,
                                             bool singleSelect, bool multiSelect, string[] requiredPermissions,
                                             string method, string state, string target) where T : ActionMenuItem
        {
            var action = Entity.Create <T>();

            action.Name                    = name;
            action.EmptySelectName         = emptySelectName;
            action.MultiSelectName         = multiSelectName;
            action.MenuOrder               = order;
            action.IsActionItem            = isMenu;
            action.IsContextMenu           = isContextMenu;
            action.IsActionButton          = isButton;
            action.IsMenuSeparator         = isSeperator;
            action.IsSystem                = isSystem;
            action.AppliesToSelection      = singleSelect;
            action.AppliesToMultiSelection = multiSelect;
            action.HtmlActionMethod        = method;
            action.HtmlActionState         = state;
            action.HtmlActionTarget        = target;
            foreach (var p in requiredPermissions)
            {
                action.ActionRequiresPermission.Add(Entity.Get <Permission>(p));
            }
            return(action);
        }
Example #16
0
        /// <summary>
        ///     Gets the type of the field data.
        /// </summary>
        /// <param name="fieldEntityRef">The field entity preference.</param>
        /// <returns>DatabaseType.</returns>
        private static DatabaseType GetFieldDataType(EntityRef fieldEntityRef)
        {
            DatabaseType type = DatabaseType.UnknownType;

            if (fieldEntityRef != null)
            {
                try
                {
                    var    field        = Entity.Get <Field>(fieldEntityRef);
                    string readiNowType = string.Format("EDC.Database.Types.{0}, {1}", field.GetFieldType().ReadiNowType, typeof(DatabaseType).Assembly.FullName);

                    var typeType = Type.GetType(readiNowType);

                    if (typeType != null)
                    {
                        return(Activator.CreateInstance(typeType) as DatabaseType);
                    }
                }
                catch
                {
                    type = DatabaseType.UnknownType;
                }
            }

            return(type);
        }
Example #17
0
        public void RunReportFromEntity()
        {
            var report = Entity.Get <Report>("templateReport");

            StructuredQuery sq = ReportToQueryConverter.Instance.Convert(report);

            QueryBuilder.GetSql(sq);
        }
        public void TestCloneAndUpdateUpdateFields()
        {
            var svc = new EntityInfoService();

            string initialName        = "Initial name" + Guid.NewGuid();
            string initialDescription = "Initial description" + Guid.NewGuid();

            string newName        = "New name" + Guid.NewGuid();
            string newDescription = "New description" + Guid.NewGuid();

            IEntity e = Entity.Create(new EntityRef("test:person"));

            e.SetField("core:name", initialName);
            e.SetField("core:description", initialDescription);
            e.Save();

            Assert.AreEqual(initialName, e.GetField("core:name"));
            Assert.AreEqual(initialDescription, e.GetField("core:description"));

            var data = new EntityData
            {
                Id     = e.Id,
                Fields = new List <FieldData>()
                {
                    new FieldData
                    {
                        FieldId = new EntityRef("name"),
                        Value   = new TypedValue(newName)
                    },
                    new FieldData
                    {
                        FieldId = new EntityRef("description"),
                        Value   = new TypedValue(newDescription)
                    }
                },
                DataState = DataState.Update
            };

            var cloneIdsMap = svc.CloneAndUpdateEntity(data);

            long cloneId;

            Assert.IsTrue(cloneIdsMap.TryGetValue(e.Id, out cloneId), "The initial entity is not found.");

            // Check the fields were cloned
            IEntity clonedEntity = Entity.Get(cloneId);

            Assert.AreEqual(newName, clonedEntity.GetField("core:name"));
            Assert.AreEqual(newDescription, clonedEntity.GetField("core:description"));

            // Check initial entity is not touched
            IEntity initialEntity = Entity.Get(e.Id);

            Assert.AreEqual(initialName, initialEntity.GetField("core:name"));
            Assert.AreEqual(initialDescription, initialEntity.GetField("core:description"));
        }
Example #19
0
        public void DisableAdministratorAccessAllRule()
        {
            using (new SecurityBypassContext())
            {
                AccessRule adminFullAuthorizationAccessRule;

                adminFullAuthorizationAccessRule = Entity.Get <AccessRule>(new EntityRef("core", "adminFullAuthorization"), true);
                adminFullAuthorizationAccessRule.AccessRuleEnabled = false;
                adminFullAuthorizationAccessRule.Save();
            }
        }
Example #20
0
        internal static long GetIconByAlias(string iconAlias)
        {
            long iconId;

            using (DatabaseContext.GetContext(true))
            {
                iconId = Entity.Get(iconAlias).Id;
            }
            Assert.IsTrue(iconId > 0, "We have icon id of {0}", iconId);
            return(iconId);
        }
Example #21
0
        internal static long GetEntityIdByAlias(string entityAlias)
        {
            long entityId;

            using (DatabaseContext.GetContext(true))
            {
                entityId = Entity.Get(entityAlias).Id;
            }
            Assert.IsTrue(entityId > 0, "We have icon id of {0}", entityId);
            return(entityId);
        }
        /// <summary>
        /// Get test report Id from alias
        /// </summary>
        private static long GetReportByAlias(string reportAlias)
        {
            long reportId;

            using (DatabaseContext.GetContext(true))
            {
                reportId = Entity.Get(reportAlias).Id;
            }
            Assert.IsTrue(reportId > 0, "We have report id of {0}", reportId);
            return(reportId);
        }
        public void Test_CheckAccess_TypelessEntity()
        {
            IDictionary <long, bool> result;
            long testId = EntityId.Max;

            result = new EntityAccessControlChecker().CheckAccess(new[] { new EntityRef(testId) },
                                                                  new[] { Permissions.Read },
                                                                  Entity.Get <UserAccount>(RequestContext.GetContext().Identity.Id));

            Assert.That(result, Has.Count.EqualTo(1));
            Assert.That(result[testId], Is.True);
        }
        public void Test_AddMultiplePermissions()
        {
            EntityType securableEntityType1;
            EntityType securableEntityType2;
            Entity     entity1;
            Entity     entity2;
            Subject    subject;
            IDictionary <long, bool> result;

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType1 = Entity.Create <EntityType>();
                securableEntityType1.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType1.Save();
                securableEntityType2 = Entity.Create <EntityType>();
                securableEntityType2.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType2.Save();
                entity1 = Entity.Create(securableEntityType1).As <Entity>();
                entity1.SetField("core:alias", "entity1__test");
                entity1.Save();
                entity2 = Entity.Create(securableEntityType2).As <Entity>();
                entity2.SetField("core:alias", "entity2__test");
                entity2.Save();
                subject = Entity.Create <UserAccount>().As <Subject>();
                subject.Save();

                new AccessRuleFactory().AddAllowReadQuery(subject, securableEntityType1.As <SecurableEntity>(), TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllowReadQuery(subject, securableEntityType2.As <SecurableEntity>(), TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllowModifyQuery(subject, securableEntityType2.As <SecurableEntity>(), TestQueries.Entities().ToReport());

                result = new EntityAccessControlChecker().CheckAccess(new EntityRef[] { entity1, entity2 },
                                                                      new[] { Permissions.Read }, subject);
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity1.Id).And.Property("Value").True, "Allow read");
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity2.Id).And.Property("Value").True, "Allow read");

                result = new EntityAccessControlChecker().CheckAccess(new EntityRef[] { entity1, entity2 },
                                                                      new[] { Permissions.Modify }, subject);
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity1.Id).And.Property("Value").False, "Allow modify");
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity2.Id).And.Property("Value").True, "Allow modify");

                result = new EntityAccessControlChecker().CheckAccess(new EntityRef[] { entity1, entity2 },
                                                                      new[] { Permissions.Read, Permissions.Modify }, subject);
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity1.Id).And.Property("Value").False, "Allow read and modify");
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity2.Id).And.Property("Value").True, "Allow read and modify");
            }
        }
Example #25
0
        public void HobbleAdministratorsRole()
        {
            IAccessRuleFactory       accessRuleFactory;
            IAccessRuleReportFactory accessRuleReportFactory;
            Subject administratorsRole;

            accessRuleReportFactory = new AccessRuleDisplayReportFactory();
            accessRuleFactory       = new AccessRuleFactory();
            using (DatabaseContext databaseContext = DatabaseContext.GetContext(true))
                using (new SecurityBypassContext())
                {
                    administratorsRole = Entity.Get <Subject>("core:administratorRole", true);

                    // Allow the test to be rerun by re-enabling the allow all Administrators access rule
                    EnableAdministratorAccessAllRule();

                    // Create full control access rules
                    DeleteAccessRules(FullControlTypeNames, AdministratorsFullControlAccessRuleNameTemplate);
                    CreateAccessRules(
                        accessRuleFactory,
                        accessRuleReportFactory,
                        administratorsRole,
                        FullControlTypeNames,
                        new[] { Permissions.Create, Permissions.Read, Permissions.Modify, Permissions.Delete },
                        AdministratorsFullControlAccessRuleNameTemplate);

                    // Create read modify access rules
                    DeleteAccessRules(ReadModifyTypeNames, AdministratorsReadModifyAccessRuleNameTemplate);
                    CreateAccessRules(
                        accessRuleFactory,
                        accessRuleReportFactory,
                        administratorsRole,
                        ReadModifyTypeNames,
                        new[] { Permissions.Read, Permissions.Modify },
                        AdministratorsReadModifyAccessRuleNameTemplate);

                    // Create read only access rules
                    DeleteAccessRules(ReadOnlyTypeNames, AdministratorsReadOnlyAccessRuleNameTemplate);
                    CreateAccessRules(
                        accessRuleFactory,
                        accessRuleReportFactory,
                        administratorsRole,
                        ReadOnlyTypeNames,
                        new[] { Permissions.Read },
                        AdministratorsReadOnlyAccessRuleNameTemplate);

                    // Disable the "allow all" administrator access rule
                    DisableAdministratorAccessAllRule();

                    databaseContext.CommitTransaction();
                }
        }
        public void Test_CopyReport_CorrectEntityType()
        {
            SecurableEntity entityType;
            Report          report;

            entityType = Entity.Get <SecurableEntity>("core:report");
            report     = new AccessRuleDisplayReportFactory().GetDisplayReportForSecurableEntity(entityType);

            Assert.That(report.RootNode.As <ResourceReportNode>(),
                        Has.Property("ResourceReportNodeType").Property("Alias").EqualTo(entityType.Alias));
            Assert.That(report,
                        Has.Property("ReportUsesDefinition").Property("Alias").EqualTo(entityType.Alias));
        }
Example #27
0
        public void AddMissingAccessRules()
        {
            IAccessRuleFactory       accessRuleFactory;
            IAccessRuleReportFactory accessRuleReportFactory;
            Subject  administratorsRole;
            Subject  everyoneRole;
            Solution coreDataSolution;

            accessRuleReportFactory = new AccessRuleDisplayReportFactory();
            accessRuleFactory       = new AccessRuleFactory();
            using (DatabaseContext databaseContext = DatabaseContext.GetContext(true))
                using (new SecurityBypassContext())
                {
                    administratorsRole = Entity.Get <Subject>("core:administratorRole", true);
                    everyoneRole       = Entity.Get <Subject>("core:everyoneRole", true);
                    coreDataSolution   = CodeNameResolver.GetInstance("ReadiNow Core Data", "Application").As <Solution>();

                    Console.WriteLine("Create access rule in solution {0}", coreDataSolution.Id);

                    CreateAccessRules(
                        accessRuleFactory,
                        accessRuleReportFactory,
                        administratorsRole,
                        new [] { "core:importConfig" },
                        new [] { Permissions.Create, Permissions.Read, Permissions.Modify, Permissions.Delete },
                        AdministratorsFullControlAccessRuleNameTemplate,
                        coreDataSolution);

                    CreateAccessRules(
                        accessRuleFactory,
                        accessRuleReportFactory,
                        administratorsRole,
                        new [] { "core:importRun" },
                        new [] { Permissions.Read, Permissions.Modify },
                        AdministratorsReadModifyAccessRuleNameTemplate,
                        coreDataSolution);

                    //var types = new[] { "core:board", "core:boardDimension" };
                    //DeleteAccessRules(types, EveryoneReadModifyControlAccessRuleNameTemplate);
                    //CreateAccessRules(
                    //    accessRuleFactory,
                    //    accessRuleReportFactory,
                    //    everyoneRole,
                    //    types,
                    //    new[] { Permissions.Create, Permissions.Read, Permissions.Modify },
                    //    EveryoneReadModifyControlAccessRuleNameTemplate,
                    //    coreDataSolution);

                    databaseContext.CommitTransaction();
                }
        }
        public void Test_CopyReport_CorrectNameDescriptionAndColumnNames()
        {
            SecurableEntity entityType;
            Report          report;

            entityType = Entity.Get <SecurableEntity>("core:report");
            report     = new AccessRuleDisplayReportFactory().GetDisplayReportForSecurableEntity(entityType);

            Assert.That(report, Has.Property("Name").EqualTo(entityType.Name));
            Assert.That(report, Has.Property("Description").EqualTo(string.Empty));
            Assert.That(report.ReportColumns.Select(rc => rc.Name),
                        Is.EquivalentTo(new [] { "Id", entityType.Name, "Description" }),
                        "Incorrect column names");
        }
Example #29
0
        internal static void ApplyColumnFormat(ReportColumn reportColumn, ReportColumnValueFormat format)
        {
            DisplayFormat columnDisplayFormat = reportColumn.ColumnDisplayFormat != null?reportColumn.ColumnDisplayFormat.AsWritable <DisplayFormat>() : new DisplayFormat();

            columnDisplayFormat.ColumnShowText       = !format.HideDisplayValue;
            columnDisplayFormat.DisableDefaultFormat = format.DisableDefaultFormat;
            columnDisplayFormat.FormatPrefix         = format.Prefix;
            columnDisplayFormat.FormatSuffix         = format.Suffix;
            columnDisplayFormat.FormatDecimalPlaces  = format.DecimalPlaces > 0 ? Convert.ToInt32(format.DecimalPlaces) : new int?();
            if (reportColumn.ColumnExpression != null && reportColumn.ColumnExpression.ReportExpressionResultType != null)
            {
                if (reportColumn.ColumnExpression.ReportExpressionResultType.Is <DateArgument>())
                {
                    DateColFmtEnum dateColFmtEnum = Entity.Get <DateColFmtEnum>(new EntityRef(format.DateTimeFormat));
                    columnDisplayFormat.DateColumnFormat = dateColFmtEnum;
                }
                else if (reportColumn.ColumnExpression.ReportExpressionResultType.Is <TimeArgument>())
                {
                    TimeColFmtEnum timeColFmtEnum = Entity.Get <TimeColFmtEnum>(new EntityRef(format.DateTimeFormat));
                    columnDisplayFormat.TimeColumnFormat = timeColFmtEnum;
                }
                else if (reportColumn.ColumnExpression.ReportExpressionResultType.Is <DateTimeArgument>())
                {
                    DateTimeColFmtEnum dateTimeColFmtEnum = Entity.Get <DateTimeColFmtEnum>(new EntityRef(format.DateTimeFormat));
                    columnDisplayFormat.DateTimeColumnFormat = dateTimeColFmtEnum;
                }
            }
            columnDisplayFormat.MaxLineCount = format.NumberOfLines > 0 ? Convert.ToInt32(format.NumberOfLines) : new int?();
            if (format.ImageScaleId != null)
            {
                columnDisplayFormat.FormatImageScale = Entity.Get <ImageScaleEnum>(format.ImageScaleId);
            }
            if (format.ImageSizeId != null)
            {
                columnDisplayFormat.FormatImageSize = Entity.Get <ThumbnailSizeEnum>(format.ImageSizeId);
            }

            if (format.Alignment != null)
            {
                columnDisplayFormat.FormatAlignment = Entity.Get <AlignEnum>(new EntityRef(format.Alignment));
            }

            if (format.EntityListColumnFormat != null)
            {
                columnDisplayFormat.EntityListColumnFormat = Entity.Get <EntityListColFmtEnum>(new EntityRef(format.EntityListColumnFormat));
            }

            columnDisplayFormat.Save();
            reportColumn.ColumnDisplayFormat = columnDisplayFormat;
        }
Example #30
0
        private static ReportCondition ReportConditionFromRule(ReportConditionalFormatRule rule, ReportColumn column)
        {
            ReportCondition reportCondition = new ReportCondition();

            if (rule.Operator.HasValue && rule.Operator != ConditionType.Unspecified)
            {
                string alias = "oper" + rule.Operator.ToString();
                reportCondition.Operator = Entity.Get <OperatorEnum>(new EntityRef(alias));
            }

            Parameter parameter = reportCondition.ConditionParameter != null?reportCondition.ConditionParameter.AsWritable <Parameter>() : new Parameter();

            // Clear the old parameter
            if (parameter.ParamTypeAndDefault != null)
            {
                parameter.ParamTypeAndDefault.AsWritable().Delete();
            }
            // Force entity resource list for argument if we have entities
            ActivityArgument activityArgument = null;

            if (rule.Values != null && rule.Values.Count > 0)
            {
                ResourceListArgument resourceList = new ResourceListArgument();
                foreach (KeyValuePair <long, string> valuePair in rule.Values)
                {
                    Resource resource = Entity.Get <Resource>(valuePair.Key);
                    if (resource != null)
                    {
                        resourceList.ResourceListParameterValues.Add(resource);
                    }
                }
                TypedArgument argumentType = column.ColumnExpression.ReportExpressionResultType.As <TypedArgument>();
                resourceList.ConformsToType = argumentType.ConformsToType;
                activityArgument            = resourceList.As <ActivityArgument>();
                activityArgument.Save();
            }
            else if (rule.Operator.HasValue)
            {
                int operatorCount = ConditionTypeHelper.GetArgumentCount(rule.Operator.Value);
                if (operatorCount > 0)
                {
                    activityArgument = ReportConditionHelper.ArgumentForConditionType(column.ColumnExpression.ReportExpressionResultType, rule.Operator.Value, rule.Value);
                    activityArgument.Save();
                }
            }
            parameter.ParamTypeAndDefault = activityArgument;
            parameter.Save();
            reportCondition.ConditionParameter = parameter;
            return(reportCondition);
        }