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);
            }
        }
        public void TestTempDeletedChildItemIgnored( )
        {
            var svc = new EntityInfoService( );

            EntityRef orgRef = null;

            try
            {
                var o = new Report
                {
                    Name  = "org rpt",
                    Alias = "shared:a" + Guid.NewGuid( )
                };

                var b = new ReportColumn
                {
                    Name            = "bob",
                    Alias           = "shared:a" + Guid.NewGuid( ),
                    ColumnForReport = o
                };

                EntityData result = svc.GetEntityData(b, EntityRequestHelper.BuildRequest("name, columnForReport.name"));

                result.Relationships[0].Instances[0].DataState = DataState.Delete;

                orgRef = svc.CreateEntity(result);
            }
            finally
            {
                if (orgRef != null)
                {
                    Entity.Delete(orgRef);
                }
            }
        }
Пример #3
0
        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);
            }
        }
        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);
        }
Пример #5
0
        public void Test_GetQueries_NullSecurableEntityType()
        {
            Role                     testSubject;
            EntityType               testSecurableEntityType;
            AccessRule               accessRule;
            SecurableEntity          securableEntityType;
            ICollection <AccessRule> result;
            IEntityRepository        entityRepository = Factory.EntityRepository;

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

                accessRule = Entity.Create <AccessRule>( );
                accessRule.AccessRuleEnabled = true;
                accessRule.PermissionAccess.Add(Permissions.Read.Entity.As <Permission>( ));
                accessRule.Save( );

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

                testSecurableEntityType = Entity.Create <EntityType>();
                testSecurableEntityType.Save();

                result = null;
                Assert.That(() => result = new RuleRepository(entityRepository).GetAccessRules(testSubject.Id, Permissions.Read, null),
                            Throws.Nothing);
                Assert.That(result, Is.Not.Null);
                Assert.That(result, Has.Count.EqualTo(1));
                Assert.That(result.First( ).Id, Is.EqualTo(accessRule.Id));
            }
        }
        public void Test_CheckAccess_SecurityBypassContext()
        {
            EntityRef[] entityIds;
            IDictionary <long, bool> result;
            UserAccount userAccount;
            EntityAccessControlChecker entityAccessControlChecker;
            MockRepository             mockRepository;

            entityIds = new EntityRef[] { 1, 2, 3 };

            mockRepository = new MockRepository(MockBehavior.Strict);

            entityAccessControlChecker = new EntityAccessControlChecker(
                mockRepository.Create <IUserRoleRepository>().Object,
                mockRepository.Create <IQueryRepository>().Object,
                mockRepository.Create <IEntityTypeRepository>().Object
                );

            userAccount = Entity.Create <UserAccount>();
            userAccount.Save();

            using (new SecurityBypassContext())
            {
                result = entityAccessControlChecker.CheckAccess(entityIds,
                                                                new[] { Permissions.Read },
                                                                userAccount);
            }

            Assert.That(result, Has.Count.EqualTo(entityIds.Count()));
            Assert.That(result, Has.All.Property("Value").True);

            mockRepository.VerifyAll();
        }
Пример #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);
            }
        }
Пример #8
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);
        }
Пример #9
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( );
                }
        }
Пример #10
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.");
                    }
                }
            }
        }
Пример #12
0
        public void Test_MaxCols_Returns_Grouped_Columns()
        {
            using (new SecurityBypassContext())
            {
                var report = Entity.GetByName <Report>("Temperature").First(r => r.InSolution != null && r.InSolution.Name == "Foster University");

                ReportSettings settings = new ReportSettings
                {
                    ColumnCount         = 3,
                    RequireFullMetadata = true
                };

                var          reportInterface = new ReportingInterface();
                ReportResult result          = reportInterface.RunReport(report.Id, settings);

                Assert.That(result, Is.Not.Null);
                Assert.That(result.GridData, Has.Count.GreaterThan(0));
                Assert.That(result.GridData[0].Values, Has.Count.EqualTo(4));
                Assert.That(result.Metadata.ReportColumns, Has.Count.EqualTo(4));
                Assert.That(result.AggregateMetadata.Groups, Has.Count.EqualTo(1));
                Assert.That(result.AggregateMetadata.Groups[0], Has.Count.EqualTo(1));
                long groupColumnId = result.AggregateMetadata.Groups[0].Keys.First();
                Assert.IsTrue(result.Metadata.ReportColumns.ContainsKey(groupColumnId.ToString(CultureInfo.InvariantCulture)));
            }
        }
Пример #13
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( ));
                }
            }
        }
Пример #14
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();
            }
        }
Пример #15
0
        public void FixCoreRules(string accessRuleName, string reportName, string newAccessRuleName, string newAlias, bool markAsNonReport)
        {
            // Note: you'll need to manually disable .ReadOnly checks (eg in code)

            AccessRule rule;
            //if ( accessRuleName == null )
            //{
            Report report = Entity.GetByName <Report>(reportName).Where(r => r.ReportForAccessRule != null && (r.ReportForAccessRule.Name == accessRuleName || r.ReportForAccessRule.Name == newAccessRuleName)).Single( );

            rule = report.ReportForAccessRule.AsWritable <AccessRule>();
            //}
            //else
            //{
            //    rule = Entity.GetByName<AccessRule>( accessRuleName ).SingleOrDefault( );
            //    if ( rule == null )
            //        throw new Exception( "Rule not found" );
            //}

            rule.Name = newAccessRuleName;
            if (newAlias != null)
            {
                rule.Alias = newAlias;
            }
            if (markAsNonReport)
            {
                rule.AccessRuleIgnoreForReports = true;
                Assert.That(rule.AccessRuleIgnoreForReports, Is.True);
            }
            long id = rule.Id;

            rule.Save( );
        }
Пример #16
0
        /// <summary>
        /// Creates an empty console behavior entity.
        /// </summary>
        /// <returns>The created console behavior entity.</returns>
        public static ConsoleBehavior CreateBehavior()
        {
            var cb = Entity.Create <ConsoleBehavior>();

            cb.BehaviorActionMenu = Entity.Create <ActionMenu>();
            return(cb);
        }
Пример #17
0
        public void EntityGetMatches( )
        {
            // Test to load all instances of a particular entity type that have a field matching a particular value.

            // Test data
            // (Load all nav sections that have name='Home')
            var          type  = new EntityRef("console", "navSection");
            var          field = new EntityRef("core", "name");
            const string value = "Home";

            // Create query
            var query = new StructuredQuery
            {
                RootEntity = new ResourceEntity(type)
            };

            query.Conditions.Add(new QueryCondition
            {
                Expression = new ResourceDataColumn(query.RootEntity, field),
                Operator   = ConditionType.Equal,
                Argument   = new TypedValue(value)
            });

            // Get results
            IEnumerable <NavSection> entities = Entity.GetMatches <NavSection>(query);

            NavSection[] eArr = entities.ToArray( );
            Assert.IsTrue(eArr.Count( ) == 1);
        }
Пример #18
0
        public void Test_GetQueries_SubjectWithAccessRuleButNoControl()
        {
            QueryRepository          queryRepository;
            SecurableEntity          securableEntityType;
            AccessRule               accessRule;
            Role                     subject;
            ICollection <AccessRule> result;
            IEntityRepository        entityRepository = Factory.EntityRepository;

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

                accessRule = Entity.Create <AccessRule>();
                accessRule.AccessRuleEnabled = true;
                accessRule.PermissionAccess.Add(Permissions.Read.Entity.As <Permission>());
                accessRule.Save();

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

                queryRepository = new QueryRepository();
                result          = new RuleRepository(entityRepository).GetAccessRules(subject.Id, Permissions.Read, new [] { securableEntityType.Id });

                Assert.That(result, Is.Not.Null);
                Assert.That(result, Is.Empty);
            }
        }
Пример #19
0
        public void EntityGetMatchesWithRelationship( )
        {
            var query = new StructuredQuery
            {
                RootEntity = new ResourceEntity(Field.Field_Type)
            };

            // Root query type is 'EntityType'

            // Follow 'Fields' relationship
            var relatedResource = new RelatedResource
            {
                RelationshipDirection = RelationshipDirection.Forward,
                RelationshipTypeId    = new EntityRef(Field.FieldIsOnType_Field.Id),
                ResourceMustExist     = false
            };

            query.RootEntity.RelatedEntities.Add(relatedResource);

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

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

            Assert.IsTrue(personFields.Any( ));
        }
        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);
        }
Пример #21
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");
        }
Пример #22
0
        public void Test_GetQueries_SubjectWithAccessRuleButNoPermissions()
        {
            QueryRepository queryRepository;
            SecurableEntity securableEntityType;
            AccessRule      accessRule;
            Role            subject;
            IEnumerable <AccessRuleQuery> result;
            Report authReport;

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

                authReport = Entity.Create <Report>();
                authReport.Save();

                accessRule = Entity.Create <AccessRule>();
                accessRule.AccessRuleEnabled = true;
                accessRule.ControlAccess     = securableEntityType;
                accessRule.AccessRuleReport  = authReport;
                accessRule.Save();

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

                queryRepository = new QueryRepository();
                result          = queryRepository.GetQueries(subject.Id, Permissions.Read, new[] { securableEntityType.Id });

                Assert.That(result, Is.Not.Null);
                Assert.That(result, Is.Empty);
            }
        }
Пример #23
0
        /// <summary>
        /// Given the <paramref name="subject"/> the specified access to <paramref name="securableEntity"/>.
        /// </summary>
        /// <param name="subject">
        /// The subject (user or role). This cannot be null.
        /// </param>
        /// <param name="permissions">
        /// The permission(s) to add. This cannot be null or contain null.
        /// </param>
        /// <param name="securableEntity">
        /// The secured entity (type). This cannot be null.
        /// </param>
        /// <returns>
        /// The <see cref="AccessRule"/> object representing the new query.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// No argument can be null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="permissions"/> cannot contain null.
        /// </exception>
        public AccessRule AddAllow(Subject subject, IEnumerable <EntityRef> permissions, SecurableEntity securableEntity)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (permissions == null)
            {
                throw new ArgumentNullException("permissions");
            }
            if (permissions.Contains(null))
            {
                throw new ArgumentException("Cannot contain null", "permissions");
            }
            if (securableEntity == null)
            {
                throw new ArgumentNullException("securableEntity");
            }

            AccessRule accessRule;

            accessRule      = Entity.Create <AccessRule>();
            accessRule.Name = string.Format("'{0}' accessing '{1}'", subject.Name ?? string.Empty, securableEntity.Name ?? string.Empty);
            accessRule.AccessRuleEnabled = true;
            accessRule.PermissionAccess.AddRange(permissions.Select(x => x.Entity.As <Permission>()));
            accessRule.ControlAccess = securableEntity;
            accessRule.AllowAccessBy = subject;
            accessRule.Save();

            subject.Save();

            return(accessRule);
        }
        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));
            }
        }
        public void TestChangeType( )
        {
            // Note: refer to additional tests directly on Entity.ChangeType.

            var svc = new EntityInfoService( );

            IEntity e = null;

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

                var ed = new EntityData
                {
                    Id = e.Id
                };
                ed.TypeIds.Add(new EntityRef("test:manager"));

                svc.UpdateEntityType(ed);
            }
            catch
            {
                if (e != null)
                {
                    e.Delete( );
                }
            }
        }
        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);
                }
            }
        }
        public void Test_CheckTypeAccess_SingleSpecificType(bool grant)
        {
            var entityType = Entity.Create <EntityType>();

            entityType.Save();

            var userAccount = Entity.Create <UserAccount>();

            userAccount.Save();

            IDictionary <SubjectPermissionTuple, IList <AccessRuleQuery> > rules = new Dictionary <SubjectPermissionTuple, IList <AccessRuleQuery> >();

            if (grant)
            {
                rules.Add(new SubjectPermissionTuple(userAccount.Id, Permissions.Create.Id),
                          new List <AccessRuleQuery> {
                    new AccessRuleQuery(100, 101, entityType.Id, new StructuredQuery(), false)
                });
            }

            var mockRepo = new MockRepository(MockBehavior.Strict);
            var accessQueryFactoryMock = mockRepo.Create <IAccessRuleQueryFactory>();

            accessQueryFactoryMock.Setup(f => f.GetQueries()).Returns(rules);

            var checker = new SystemEntityAccessControlChecker(new UserRoleRepository(), new SystemAccessRuleQueryRepository(accessQueryFactoryMock.Object),
                                                               new EntityTypeRepository());

            var entityTypes = new [] { entityType };

            Assert.AreEqual(grant, checker.CheckTypeAccess(entityTypes, Permissions.Create, userAccount)[entityType.Id], "CheckTypeAccess returned incorrect result");
        }
Пример #28
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);
        }
Пример #29
0
        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));
            }
        }
 public void Test_AddAllowReadQuery_NullReport()
 {
     using (DatabaseContext.GetContext(true))
     {
         Assert.That(() => new AccessRuleFactory().AddAllowReadQuery(Entity.Create <Subject>(), Entity.Create <SecurableEntity>(), null),
                     Throws.TypeOf <ArgumentNullException>().And.Property("ParamName").EqualTo("report"));
     }
 }