예제 #1
0
        public void BasicTest(InvalidationCause invalidationCause)
        {
            CachingReportToQueryConverter cachingReportToQueryConverter;
            Report          report;
            StructuredQuery structuredQuery;
            ItemsRemovedEventHandler <CachingReportToQueryConverterKey> itemsRemovedEventHandler;
            List <long> itemsRemoved;

            using (var ctx = EDC.ReadiNow.Database.DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
            {
                report = TestQueries.Entities().ToReport();
                report.Save();
                ctx.CommitTransaction();
            }

            cachingReportToQueryConverter = Factory.Current.Resolve <CachingReportToQueryConverter>();
            Assert.That(cachingReportToQueryConverter, Is.Not.Null,
                        "Not report to query converter cache found");
            Assert.That(cachingReportToQueryConverter, Is.Not.Null,
                        "Not report to query converter cache found");

            itemsRemoved             = new List <long>();
            itemsRemovedEventHandler = (sender, args) => itemsRemoved.AddRange(args.Items.Select(key => key.ReportId));

            structuredQuery = cachingReportToQueryConverter.Convert(report, null);
            try
            {
                cachingReportToQueryConverter.Cache.ItemsRemoved += itemsRemovedEventHandler;
                Assert.That(cachingReportToQueryConverter.Cache,
                            Has.Exactly(1).Property("Key").Property("ReportId").EqualTo(report.Id));
                Assert.That(cachingReportToQueryConverter.Cache,
                            Has.Exactly(1).Property("Value").Property("StructuredQuery").SameAs(structuredQuery));

                using (var ctx = EDC.ReadiNow.Database.DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
                {
                    if (invalidationCause == InvalidationCause.Save)
                    {
                        report.Save();
                    }
                    else if (invalidationCause == InvalidationCause.Delete)
                    {
                        report.Delete();
                    }
                    else
                    {
                        Assert.Fail("Unknown invalidation cause");
                    }
                    ctx.CommitTransaction();
                }

                Assert.That(cachingReportToQueryConverter.Cache,
                            Has.Exactly(0).Property("Key").EqualTo(report.Id));
                Assert.That(itemsRemoved,
                            Has.Exactly(1).EqualTo(report.Id));
            }
            finally
            {
                cachingReportToQueryConverter.Cache.ItemsRemoved -= itemsRemovedEventHandler;
            }
        }
예제 #2
0
        public void Test_QuickSearchFilterCaseInsensitive(bool includeFilter)
        {
            StructuredQuery structuredQuery;
            QuerySettings   querySettings;
            QueryBuild      queryResult;

            structuredQuery = TestQueries.Entities( );
            structuredQuery.SelectColumns.Add(new SelectColumn
            {
                Expression = new ResourceDataColumn(structuredQuery.RootEntity, new EntityRef("core:name"))
            });
            querySettings = new QuerySettings( )
            {
                SecureQuery        = false,
                SupportQuickSearch = includeFilter
            };

            queryResult = BuildSql(structuredQuery, querySettings);
            if (includeFilter)
            {
                Assert.That(queryResult.Sql,
                            Contains.Substring("COLLATE Latin1_General_CI_AI"));
            }
            else
            {
                Assert.That(queryResult.Sql,
                            Is.Not.ContainsSubstring("COLLATE Latin1_General_CI_AI"));
            }
        }
예제 #3
0
        public void RunReportSomeAccess()
        {
            var nameDescList = new List <Tuple <string, string> >
            {
                new Tuple <string, string>("Name1", "Description1"),
                new Tuple <string, string>("Name2", "Description2")
            };
            SecurityTestData testData = SetupSecurityTest(nameDescList);

            var reportingInterface = new ReportingInterface();

            // Create an access rule only for entity with Name1
            new AccessRuleFactory().AddAllowReadQuery(testData.UserAccount.As <EntityModel.Subject>(), testData.EntityType.As <EntityModel.SecurableEntity>(),
                                                      TestQueries.EntitiesWithName(testData.EntityType, "Name1").ToReport());

            ReportResult reportResult;

            using (new SetUser(testData.UserAccount))
            {
                reportResult = reportingInterface.RunReport(testData.Report, null);
            }

            foreach (var nameDesc in nameDescList)
            {
                Assert.AreEqual(nameDesc.Item1 == "Name1" ? 1 : 0, reportResult.GridData.Count(gd => gd.Values[1].Value == nameDesc.Item1 && gd.Values[2].Value == nameDesc.Item2));
            }
            Assert.AreEqual(1, reportResult.GridData.Count);
        }
예제 #4
0
        public void Test_SimpleReport()
        {
            UserAccount userAccount = null;
            EntityType  reportType;
            EntityType  conditionalFormatIcon;

            ReadiNow.Model.Report report;
            HttpWebResponse       response;

            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();

                reportType            = Entity.Get <EntityType>("core:report");
                conditionalFormatIcon = Entity.Get <EntityType>("core:conditionalFormatIcon");

                report = Entity.Get <ReadiNow.Model.Report>("k:reportsReport");
                Assert.That(report, Is.Not.Null, "Test report not found");
                Assert.That(report, Has.Property("RootNode").Not.Null, "Test report not converted");

                new AccessRuleFactory().AddAllowReadQuery(userAccount.As <Subject>(), reportType.As <SecurableEntity>(),
                                                          TestQueries.Entities().ToReport());

                new AccessRuleFactory().AddAllowReadQuery(userAccount.As <Subject>(), conditionalFormatIcon.As <SecurableEntity>(),
                                                          TestQueries.Entities().ToReport());

                // Sanity check
                using (new SetUser(userAccount))
                {
                    IDictionary <long, bool> checkResult = Factory.EntityAccessControlService.Check(
                        new[] { new EntityRef(report), },
                        new[] { Permissions.Read });

                    Assert.That(checkResult, Has.Exactly(1).Property("Key").EqualTo(report.Id).And.Property("Value").True);
                }

                // Load the first row of the report
                using (var request = new PlatformHttpRequest(@"data/v1/report/" + report.Id + "?page=0,1", PlatformHttpMethod.Get, userAccount))
                {
                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.OK),
                                "Web service call failed");
                }
            }
            finally
            {
                if (userAccount != null)
                {
                    // Will cascade delete and remove the access rule
                    try { userAccount.Delete(); }
                    catch (Exception) { }
                }
            }
        }
        public void Security_CheckInstancesSecurity(bool grant)
        {
            IEntityXmlExporter exporter = Factory.EntityXmlExporter;
            IEntityXmlImporter importer = Factory.EntityXmlImporter;
            string             xml;

            Definition type = new Definition( );

            type.Inherits.Add(UserResource.UserResource_Type);
            type.Name = Guid.NewGuid( ).ToString( );
            type.Save( );

            Resource instance = Entity.Create(type.Id).As <Resource>( );

            instance.Name = "Mordor";
            instance.Save( );

            // Generate the XML as admin
            using (RunAsImportExportRole( ))
            {
                xml = exporter.GenerateXml(instance.Id, EntityXmlExportSettings.Default);
            }

            // Create a user that can create the types, but not modify the instance
            var user = Entity.Create <UserAccount>( );

            user.Name = "Frodo";
            user.UserHasRole.Add(Entity.Get <Role>("core:importExportRole"));
            user.Save( );

            new AccessRuleFactory( ).AddAllowCreate(user.As <Subject>( ), type.As <SecurableEntity>( )).Save( );
            if (grant)
            {
                new AccessRuleFactory( ).AddAllowByQuery(user.As <Subject>( ),
                                                         type.As <SecurableEntity>( ),
                                                         new[] { Permissions.Read, Permissions.Modify },
                                                         TestQueries.Entities(new EntityRef(type.Id)).ToReport( )).Save( );
            }

            var res = new EntityAccessControlChecker( ).CheckTypeAccess(new[] { type.As <EntityType>() }, Permissions.Create, user);

            // Try to reimport as non-priv user
            using (new SetUser(user))
            {
                Action run = () => importer.ImportXml(xml, EntityXmlImportSettings.Default);

                if (grant)
                {
                    run( );
                }
                else
                {
                    Assert.That(Assert.Throws <PlatformSecurityException>(() => run( )).Message, Is.StringStarting("Frodo does not have edit access to Mordor"));
                }
            }
        }
예제 #6
0
        //[TestCase("core:modify", false, true)]  // unsupported
        //[TestCase("core:delete", false, false)] // unsupported
        //[TestCase( "core:modify,core:delete", false, true )] // unsupported
        public void Test_Save(string permissionAliases, bool canGetEntity, bool canSaveEntity)
        {
            UserAccount userAccount = null;
            EntityType  entityType  = null;
            IEntity     entity1     = null;
            IEntity     entity2     = null;
            IEntity     loadedEntity;

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Test user " + Guid.NewGuid().ToString();
            userAccount.Save();

            entityType = new EntityType();
            entityType.Inherits.Add(UserResource.UserResource_Type);
            entityType.Save();

            entity1 = Entity.Create(new EntityRef(entityType));
            entity1.SetField("core:name", "A");
            entity1.Save();

            entity2 = Entity.Create(new EntityRef(entityType));
            entity2.SetField("core:name", "B");
            entity2.Save();

            if (permissionAliases.Length > 0)
            {
                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(), entityType.As <SecurableEntity>(),
                                                        permissionAliases.Split(',').Select(x => new EntityRef(x)),
                                                        TestQueries.EntitiesWithNameA().ToReport());
            }

            using (new SetUser(userAccount))
            {
                // Only check read permission, even when getting a writable version
                loadedEntity = null;
                Assert.That(() => loadedEntity = Entity.Get <IEntity>(new EntityRef(entity1), true),
                            canGetEntity
                        ? (Constraint)Is.EqualTo(entity1).Using(EntityRefComparer.Instance)
                        : (Constraint)Throws.TypeOf <PlatformSecurityException>(), "Entity 1 Get is incorrect");
                Assert.That(() => Entity.Get <IEntity>(new EntityRef(entity2), true),
                            Throws.TypeOf <PlatformSecurityException>(), "Entity 2 access failed");

                if (canGetEntity)
                {
                    // Requires modify permission
                    Assert.That(() => loadedEntity.Save(),
                                canSaveEntity
                            ? (Constraint)Throws.Nothing
                            : (Constraint)Throws.TypeOf <PlatformSecurityException>());
                }
            }
        }
예제 #7
0
        private IEnumerable <TestCaseData> Test_GetReferencedRelationships_Source()
        {
            // Using a Func<StructuredQuery> rather than a straight StructuredQuery to
            // avoid issues with NUnit and using a CallContext in a TestCaseSource method.

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.Entities()), new string[0]));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.AccessRulesWithNamedPermission("read")), new[] { "core:permissionAccess" }));

            // Get multiple relationships form the root entity, including an enum
            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.ActiveUsersInRole("administrators")), new[] { "core:userHasRole", "core:accountStatus" }));

            // Test nested related resource nodes and reverse relationships
            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.TypesSecuredBySubjects("administrators")), new[] { "core:allowAccess", "core:controlAccess" }));
        }
예제 #8
0
        public void SetUp()
        {
            _ratAttrib = new RunAsDefaultTenant();          // Explicitly calling the RunAsDefaultTenant attribute so that we can set up some common objects to speed up the test.

            _ratAttrib.BeforeTest(null);

            _userAccount      = Entity.Create <UserAccount>();
            _userAccount.Name = "Test user " + Guid.NewGuid().ToString();
            _userAccount.Save();


            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Workflow.Workflow_Type.As <SecurableEntity>(),
                Permissions.Read.ToEnumerable(),
                TestQueries.WorkflowWithName("A").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:read").ToEnumerable(),
                TestQueries.EntitiesWithName("Readable").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:modify").ToEnumerable(),
                TestQueries.EntitiesWithName("Writable").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:create").ToEnumerable(),
                TestQueries.EntitiesWithName("Creatable").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:delete").ToEnumerable(),
                TestQueries.EntitiesWithName("Deletable").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:read").ToEnumerable(),
                TestQueries.EntitiesWithName("Deletable").ToReport());
        }
        public void Security_CheckRootInstancesSecurity(bool grant)
        {
            IEntityXmlExporter exporter = Factory.EntityXmlExporter;
            IEntityXmlImporter importer = Factory.EntityXmlImporter;
            string             xml      = null;

            Definition type = new Definition( );

            type.Inherits.Add(UserResource.UserResource_Type);
            type.Name = Guid.NewGuid( ).ToString( );
            type.Save( );

            Resource instance = Entity.Create(type.Id).As <Resource>( );

            instance.Name = "Mordor";
            instance.Save( );

            // Create a user that can create the types, but not modify the instance
            var user = Entity.Create <UserAccount>( );

            user.Name = "Frodo";
            user.UserHasRole.Add(Entity.Get <Role>("core:importExportRole"));
            user.Save( );

            if (grant)
            {
                new AccessRuleFactory( ).AddAllowReadQuery(user.As <Subject>( ),
                                                           type.As <SecurableEntity>( ),
                                                           TestQueries.Entities(new EntityRef(type.Id)).ToReport( )).Save( );
            }

            // Try to reimport as non-priv user
            using (new SetUser(user))
            {
                // Generate the XML as admin
                Func <string> run = () => exporter.GenerateXml(instance.Id, EntityXmlExportSettings.Default);

                if (grant)
                {
                    xml = run( );
                }
                else
                {
                    Assert.That(Assert.Throws <PlatformSecurityException>(() => run( )).Message, Is.StringStarting("Frodo does not have view access to Mordor"));
                }
            }
        }
예제 #10
0
        public void Test_BasicSecurity()
        {
            UserAccount userAccount = null;
            EntityType  entityType  = null;
            IEntity     entity1     = null;
            IEntity     entity2     = null;

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "GetEntitiesOfType test user " + Guid.NewGuid().ToString();
            userAccount.Save();

            entityType = new EntityType();
            entityType.Inherits.Add(UserResource.UserResource_Type);
            entityType.Save();

            entity1 = Entity.Create(new EntityRef(entityType));
            entity1.SetField("core:name", "A");
            entity1.Save();

            entity2 = Entity.Create(new EntityRef(entityType));
            entity2.SetField("core:name", "B");
            entity2.Save();

            new AccessRuleFactory().AddAllowReadQuery(userAccount.As <Subject>(), entityType.As <SecurableEntity>(),
                                                      TestQueries.EntitiesWithNameA().ToReport());

            // Sanity Check. Check directly to avoid any caching or side effect issue.
            IDictionary <long, bool> results = new EntityAccessControlChecker().CheckAccess(
                new[] { new EntityRef(entity1), new EntityRef(entity2) },
                new[] { Permissions.Read },
                new EntityRef(userAccount));

            Assert.That(results, Has.Exactly(1).Property("Key").EqualTo(entity1.Id).And.Property("Value").True,
                        "EntityAccessControlChecker.CheckAccess: No access to Entity ID 1");
            Assert.That(results, Has.Exactly(1).Property("Key").EqualTo(entity2.Id).And.Property("Value").False,
                        "EntityAccessControlChecker.CheckAccess: Access to Entity ID 2");

            using (new SetUser(userAccount))
            {
                IEnumerable <IEntity> entities = Entity.GetInstancesOfType(entityType, true, "name");
                Assert.That(entities.Count(), Is.EqualTo(1),
                            "Entity.GetInstancesOfType: Incorrect count");
                Assert.That(entities, Has.Exactly(1).Property("Id").EqualTo(entity1.Id),
                            "Entity.GetInstancesOfType: Incorrect Id");
            }
        }
        public virtual void TestFixtureSetup()
        {
            EntityType entityType;

            try
            {
                DatabaseContext = DatabaseContext.GetContext(true);

                RunAsDefaultTenant = new RunAsDefaultTenant();
                RunAsDefaultTenant.BeforeTest(null);

                entityType = EDC.ReadiNow.Model.Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();

                Entities = CreateEntities(entityType, MatchingName);

                // Ensure the results are ordered
                Query = TestQueries.Entities(entityType);
                Query.OrderBy.Add(new OrderByItem()
                {
                    Expression = new ColumnReference()
                    {
                        ColumnId = Query.SelectColumns[0].ColumnId
                    },
                    Direction = OrderByDirection.Ascending
                });

                UserAccount = new UserAccount();
                UserAccount.Save();

                new AccessRuleFactory().AddAllowReadQuery(UserAccount.As <Subject>(), entityType.As <SecurableEntity>(),
                                                          TestQueries.EntitiesWithNameA(entityType).ToReport());
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Setup failed: " + ex);
                if (DatabaseContext != null)
                {
                    DatabaseContext.Dispose();
                }
                throw;
            }
        }
예제 #12
0
        // CANNOT RUN THIS AS A TRANSACTION
        public void WfTriggersAsNonAdmin()
        {
            var myType     = CreateType("CreateTriggerAddsAndRemovesTypeHook_type", UserResource.UserResource_Type);
            var myWorkflow = CreateWorkflow("CreateTriggerAddsAndRemovesTypeHook_workflow");
            var myTrigger  = CreateTrigger("CreateTriggerAddsAndRemovesTypeHook_trigger", myType, myWorkflow);

            using (new WorkflowRunContext {
                RunTriggersInCurrentThread = true
            })
            {
                myType.AsWritable();
                myType.Name = "Creatable";
                myType.IsOfType.Add(Resource.Resource_Type);
                myType.Save();

                var myUser = Entity.Create <UserAccount>();
                myUser.Name = "Bob" + DateTime.Now;
                myUser.Save();
                ToDelete.Add(myUser.Id);

                new AccessRuleFactory().AddAllowByQuery(
                    myUser.As <Subject>(),
                    Resource.Resource_Type.As <SecurableEntity>(),
                    new EntityRef("core:create").ToEnumerable(),
                    TestQueries.EntitiesWithName("Creatable").ToReport());

                using (new SetUser(myUser))
                {
                    var e = Entity.Create(myType).As <Resource>();
                    e.Name          = "MyName";
                    e.CreatedDate   = DateTime.Now;
                    e.CreatedBy     = myUser;
                    e.SecurityOwner = myUser;
                    e.Save();
                    ToDelete.Add(e.Id);
                }
            }

            var wf       = Entity.Get <Workflow>(myWorkflow);
            var failures = wf.RunningInstances.Count(r => r.WorkflowRunStatus_Enum != WorkflowRunState_Enumeration.WorkflowRunCompleted);

            Assert.That(wf.RunningInstances.Count, Is.EqualTo(1), "It ran");
            Assert.That(wf.RunningInstances.First().WorkflowRunStatus_Enum == WorkflowRunState_Enumeration.WorkflowRunCompleted, "It ran without errors");
        }
예제 #13
0
        private IEnumerable <TestCaseData> Test_GetReferencedFields_Source()
        {
            // Using a Func<StructuredQuery> rather than a straight StructuredQuery to
            // avoid issues with NUnit and using a CallContext in a TestCaseSource method.

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.Entities()), new string[0]));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameA()), new[] { "core:name" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithDescription()), new[] { "core:description" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesOrderByDescription()), new[] { "core:description" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameDescription("a", "a")), new[] { "core:name", "core:description" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameAndDescriptionInResults("a")), new [] { "core:name", "core:description" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.AccessRulesWithNamedPermission("read")), new[] { "core:name", "core:accessRuleEnabled" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.ActiveUsersInRole("administrators")), new[] { "core:name", "core:alias" }));
        }
예제 #14
0
        //[TestCase("core:modify", false)] // unsupported
        //[TestCase("core:delete", true)]  // unsupported
        //[TestCase("core:modify,core:delete", true)] // unsupported
        public void Test_Delete(string permissionAliases, bool canDeleteEntity1)
        {
            UserAccount userAccount = null;
            EntityType  entityType  = null;
            IEntity     entity1     = null;
            IEntity     entity2     = null;

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Test user " + Guid.NewGuid().ToString();
            userAccount.Save();

            entityType = new EntityType();
            entityType.Inherits.Add(UserResource.UserResource_Type);
            entityType.Save();

            entity1 = Entity.Create(new EntityRef(entityType));
            entity1.SetField("core:name", "A");
            entity1.Save();

            entity2 = Entity.Create(new EntityRef(entityType));
            entity2.SetField("core:name", "B");
            entity2.Save();

            if (permissionAliases.Length > 0)
            {
                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(), entityType.As <SecurableEntity>(),
                                                        permissionAliases.Split(',').Select(x => new EntityRef(x)),
                                                        TestQueries.EntitiesWithNameA().ToReport());
            }

            using (new SetUser(userAccount))
            {
                Assert.That(() => entity1.Delete(),
                            canDeleteEntity1
                        ? (Constraint)Throws.Nothing
                        : (Constraint)Throws.TypeOf <PlatformSecurityException>());
                Assert.That(() => Entity.Get <IEntity>(new EntityRef(entity2)),
                            Throws.TypeOf <PlatformSecurityException>(), "Entity 2 delete somehow worked");
            }
        }
예제 #15
0
        /// <summary>
        /// Creates a report entity for a given type.
        /// </summary>
        /// <param name="alias">The alias given to the report.</param>
        /// <param name="name">The name given to the report.</param>
        /// <param name="description">The description given to the report.</param>
        /// <param name="type">The type to create the report for.</param>
        /// <param name="isDefault">Whether the report should be the default display report for the type.</param>
        /// <returns>The created report entity.</returns>
        public static Report CreateReport(string alias, string name, string description, EntityType type, bool isDefault)
        {
            var query = TestQueries.Entities(type);

            query.SelectColumns[0].IsHidden = true;
            query.SelectColumns.Add(new SelectColumn
            {
                ColumnName  = "Name",
                DisplayName = "Unit",
                Expression  = new ResourceDataColumn(query.RootEntity, new EntityRef("core:name"))
            });

            var report = query.ToReport();

            report.Alias       = alias;
            report.Name        = name;
            report.Description = description;
            if (isDefault)
            {
                report.IsDefaultDisplayReportForTypes.Add(type);
            }

            return(report);
        }
예제 #16
0
        public void SimplifiedTest()
        {
            // Set up security so we have a user that can save stuff
            var myUser = Entity.Create <UserAccount>();

            myUser.Name = "Bob" + DateTime.Now;
            myUser.Save();

            new AccessRuleFactory().AddAllowByQuery(
                myUser.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:modify").ToEnumerable(),
                TestQueries.EntitiesWithName("Creatable").ToReport());


            // Create a person
            var p = Entity.Create <Person>();

            p.Name = "Creatable";

            p.Save();


            // THIS FAILS
            using (new SetUser(myUser))
            {
                var pw = p.AsWritable <Person>();
                pw.Name = "bob";
                pw.Save();
            }

            // THIS WORKS
            //var pw = p2.AsWritable<Person>();
            //pw.Name = "bob";
            //pw.Save();
        }
예제 #17
0
        private static void CreateUsersAndSecurity(ref GrandDesign testObject)
        {
            //
            // Users
            //
            var administratorUser = Entity.Get <UserAccount>(new EntityRef("core:administratorUserAccount"), true);

            testObject.Accounts.Add("administrator", administratorUser);

            //
            // Access Rules
            //
            new AccessRuleFactory().AddAllowByQuery(administratorUser.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read", "core:modify", "core:delete", "core:create" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Read
            //
            var reader = Entity.Create <Person>();

            reader.FirstName = "Robbie";
            reader.LastName  = "Reader";

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

            readerAccount.Name          = "reader";
            readerAccount.AccountHolder = reader;
            readerAccount.Save();
            testObject.Accounts.Add("reader", readerAccount);

            new AccessRuleFactory().AddAllowByQuery(readerAccount.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Read + Modify
            //
            var modifier = Entity.Create <Person>();

            modifier.FirstName = "Margie";
            modifier.LastName  = "Modifier";

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

            modifierAccount.Name          = "modifier";
            modifierAccount.AccountHolder = modifier;
            modifierAccount.Save();
            testObject.Accounts.Add("modifier", modifierAccount);

            new AccessRuleFactory().AddAllowByQuery(modifierAccount.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read", "core:modify" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Read, Modify + Create
            //
            var creator = Entity.Create <Person>();

            creator.FirstName = "Connie";
            creator.LastName  = "Creator";

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

            creatorAccount.Name          = "creator";
            creatorAccount.AccountHolder = creator;
            creatorAccount.Save();
            testObject.Accounts.Add("creator", creatorAccount);

            new AccessRuleFactory().AddAllowByQuery(creatorAccount.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read", "core:modify", "core:create" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Read, Modify + Delete
            //
            var deleter = Entity.Create <Person>();

            deleter.FirstName = "Donnie";
            deleter.LastName  = "Deleter";

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

            deleterAccount.Name          = "deleter";
            deleterAccount.AccountHolder = deleter;
            deleterAccount.Save();
            testObject.Accounts.Add("deleter", deleterAccount);

            new AccessRuleFactory().AddAllowByQuery(deleterAccount.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read", "core:modify", "core:delete" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Folder
            //
            var folder = Entity.Create <Folder>();

            folder.Name = "Get Actions";
            folder.ResourceInFolder.Add(Entity.GetByName <NavSection>("Test Solution").First().As <NavContainer>());
            folder.Save();
            testObject.WorkingFolder = folder;

            //
            // All these accounts should see...
            //
            foreach (var account in testObject.Accounts.Values)
            {
                //
                // ...workflows
                //
                new AccessRuleFactory().AddAllowByQuery(account.As <Subject>(),
                                                        Workflow.Workflow_Type.As <SecurableEntity>(),
                                                        new EntityRef("core:read").ToEnumerable(),
                                                        TestQueries.Entities(new EntityRef("core:workflow")).ToReport());

                //
                // ... report templates
                //
                new AccessRuleFactory().AddAllowByQuery(account.As <Subject>(),
                                                        ReportTemplate.ReportTemplate_Type.As <SecurableEntity>(),
                                                        new EntityRef("core:read").ToEnumerable(),
                                                        TestQueries.Entities(new EntityRef("core:reportTemplate")).ToReport());
            }
        }
예제 #18
0
        public void Test_GetActions_Security_ReadModifyDelete(string permissionAliases)
        {
            ActionRequestExtended actionRequest;
            ActionResponse        response;
            Report                     peopleReport;
            UserAccount                userAccount;
            Person                     person;
            ActionMenuItem             viewActionMenuItem;
            ActionMenuItem             editActionMenuItem;
            ActionMenuItem             deleteActionMenuItem;
            IList <ActionMenuItemInfo> flattenedResults;

            string[] splitPermissionAliases;

            splitPermissionAliases = permissionAliases.Split(',');

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

            person = Entity.Create <Person>();
            person.Save();

            viewActionMenuItem = Entity.Get <ActionMenuItem>("console:viewResourceAction");
            Assert.That(viewActionMenuItem, Is.Not.Null, "No view menu item");
            editActionMenuItem = Entity.Get <ActionMenuItem>("console:editResourceAction");
            Assert.That(editActionMenuItem, Is.Not.Null, "No edit menu item");
            deleteActionMenuItem = Entity.Get <ActionMenuItem>("console:deleteResourceAction");
            Assert.That(deleteActionMenuItem, Is.Not.Null, "No delete menu item");

            if (!string.IsNullOrWhiteSpace(permissionAliases))
            {
                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    Entity.Get <SecurableEntity>(Entity.Get <EntityType>("core:person")),
                    splitPermissionAliases.Select(pa => new EntityRef(pa)),
                    TestQueries.Entities().ToReport());
            }

            peopleReport = Entity.GetByName <Report>("People").FirstOrDefault();
            Assert.That(peopleReport, Is.Not.Null, "No People report");

            actionRequest = new ActionRequestExtended
            {
                SelectedResourceIds    = new[] { person.Id },
                LastSelectedResourceId = person.Id,
                CellSelectedResourceId = -1,
                ReportId             = peopleReport.Id,
                HostResourceIds      = new long[0],
                HostTypeIds          = new List <long>(),
                AdditionalData       = new Dictionary <string, object>(),
                ActionDisplayContext = ActionContext.ActionsMenu
            };

            using (new SetUser(userAccount))
            {
                response = new ActionService().GetActions(actionRequest);
            }

            flattenedResults = response.Actions.SelectMany(Flatten).ToList();

            Assert.That(flattenedResults,
                        Has.Exactly(splitPermissionAliases.Contains("read") ? 1 : 0).Property("Id").EqualTo(viewActionMenuItem.Id),
                        "View menu incorrect");
            Assert.That(flattenedResults,
                        Has.Exactly(splitPermissionAliases.Contains("read") && splitPermissionAliases.Contains("modify") ? 1 : 0).Property("Id").EqualTo(editActionMenuItem.Id),
                        "Edit menu incorrect");
            Assert.That(flattenedResults,
                        Has.Exactly(splitPermissionAliases.Contains("read") && splitPermissionAliases.Contains("delete") ? 1 : 0).Property("Id").EqualTo(deleteActionMenuItem.Id),
                        "Delete menu incorrect");
        }
예제 #19
0
        public void Test_GetActions_Security_MultipleSelection(string entity1Name, string entity2Name, bool expectedResult)
        {
            ActionRequestExtended actionRequest;
            ActionResponse        response;
            Report                     report;
            UserAccount                userAccount;
            ActionMenuItem             deleteActionMenuItem;
            IList <ActionMenuItemInfo> flattenedResults;
            EntityType                 entityType;
            IEntity                    entity1;
            IEntity                    entity2;

            entityType = Entity.Create <EntityType>();
            entityType.Inherits.Add(UserResource.UserResource_Type);
            entityType.Save();

            entity1 = Entity.Create(entityType);
            entity1.SetField("core:name", entity1Name);
            entity1.Save();

            entity2 = Entity.Create(entityType);
            entity2.SetField("core:name", entity2Name);
            entity2.Save();

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Action service test " + Guid.NewGuid( ).ToString( );
            userAccount.Save();

            new AccessRuleFactory( ).AddAllowReadQuery(
                userAccount.As <Subject>( ),
                Entity.Get <SecurableEntity>(Entity.Get <EntityType>("core:report")),
                TestQueries.Entities(new EntityRef("core:report")).ToReport( ));

            deleteActionMenuItem = Entity.Get <ActionMenuItem>("console:deleteResourceAction");
            Assert.That(deleteActionMenuItem, Is.Not.Null, "No delete menu item");

            new AccessRuleFactory().AddAllowByQuery(
                userAccount.As <Subject>(),
                entityType.As <SecurableEntity>(),
                new [] { Permissions.Read, Permissions.Delete },
                TestQueries.EntitiesWithNameA(entityType).ToReport());

            report = TestQueries.EntitiesWithNameA(entityType).ToReport();
            report.Save();

            actionRequest = new ActionRequestExtended
            {
                SelectedResourceIds    = new[] { entity1.Id, entity2.Id },
                LastSelectedResourceId = entity1.Id,
                CellSelectedResourceId = -1,
                ReportId             = report.Id,
                HostResourceIds      = new long[0],
                HostTypeIds          = new List <long>(),
                AdditionalData       = new Dictionary <string, object>(),
                ActionDisplayContext = ActionContext.ContextMenu
            };

            using (new SetUser(userAccount))
            {
                response = new ActionService().GetActions(actionRequest);
            }

            flattenedResults = response.Actions.SelectMany(Flatten).ToList();

            Assert.That(flattenedResults,
                        Has.Exactly(expectedResult ? 1 : 0).Property("Id").EqualTo(deleteActionMenuItem.Id),
                        "Delete menu incorrect");
        }
예제 #20
0
        [TestCase("API Endpoints", "API Resource Endpoint,API Spreadsheet Endpoint", true)] //#27489
        public void Test_GetActions_Security_Create(string reportName, string typeNames, bool admin)
        {
            ActionRequestExtended actionRequest;
            ActionResponse        response;
            Report      report;
            UserAccount userAccount;
            IList <ActionMenuItemInfo> flattenedResults;

            string[]        splitTypeNames;
            SecurableEntity securableEntity;

            splitTypeNames = typeNames.Split(',');

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Action service test " + Guid.NewGuid( ).ToString( );
            userAccount.Save();

            new AccessRuleFactory( ).AddAllowReadQuery(
                userAccount.As <Subject>( ),
                Entity.Get <SecurableEntity>(Entity.Get <EntityType>("core:report")),
                TestQueries.Entities(new EntityRef("core:report")).ToReport( ));

            if (!string.IsNullOrWhiteSpace(typeNames))
            {
                foreach (string typeName in splitTypeNames)
                {
                    securableEntity = Entity.GetByName <SecurableEntity>(typeName).FirstOrDefault();
                    Assert.That(securableEntity, Is.Not.Null,
                                string.Format("{0} is not a type", typeName));

                    new AccessRuleFactory().AddAllowCreate(
                        userAccount.As <Subject>(),
                        securableEntity);
                }
            }

            report = Entity.GetByName <Report>(reportName).FirstOrDefault();
            Assert.That(report, Is.Not.Null, string.Format("{0} is not a report", reportName));

            actionRequest = new ActionRequestExtended
            {
                SelectedResourceIds    = new long[0],
                LastSelectedResourceId = 0,
                CellSelectedResourceId = -1,
                ReportId             = report.Id,
                HostResourceIds      = new long[0],
                HostTypeIds          = new List <long>(),
                AdditionalData       = new Dictionary <string, object>(),
                ActionDisplayContext = ActionContext.ActionsMenu
            };

            if (admin)
            {
                response = new ActionService( ).GetActions(actionRequest);
            }
            else
            {
                using (new SetUser(userAccount))
                {
                    response = new ActionService( ).GetActions(actionRequest);
                }
            }

            flattenedResults = response.Actions.SelectMany(Flatten).ToList();

            if (!string.IsNullOrWhiteSpace(typeNames))
            {
                foreach (string typeName in splitTypeNames)
                {
                    string expectState = typeName == "API Resource Endpoint" ? "resourceEndpointNew" : ActionService.CreateMenuItemActionState;

                    Assert.That(flattenedResults,
                                Has.Exactly(1).Property("HtmlActionState").EqualTo(expectState)
                                .And.Property("Name").EqualTo(typeName));
                }
            }
            else
            {
                Assert.That(flattenedResults,
                            Has.Exactly(0).Property("HtmlActionState").EqualTo(ActionService.CreateMenuItemActionState));
            }
        }
예제 #21
0
        public void Test_Post(string entityPermissions, bool expectEntity)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;

            string[]             splitEntityPermissions;
            ReportDataDefinition result;

            splitEntityPermissions = entityPermissions.Split(new[] { ',' },
                                                             StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.SetField("core:name", "A");
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitEntityPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(@"data/v1/entity/query", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonStructuredQuery
                    {
                        Root = new JsonEntityInQuery
                        {
                            Id = entityType.Id.ToString(CultureInfo.InvariantCulture)
                        }
                    });

                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.OK),
                                "Web service call failed");
                    result = request.DeserialiseResponseBody <ReportDataDefinition>();
                    if (expectEntity)
                    {
                        Assert.That(result.ReportDataRows, Has.Count.EqualTo(1));
                        Assert.That(result.ReportDataRows, Has.Exactly(1).Property("Id").EqualTo(entity.Id));
                    }
                    else
                    {
                        Assert.That(result.ReportDataRows, Is.Empty);
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
예제 #22
0
        public void Test_Get(string entityPermissions, HttpStatusCode expectedResult)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;

            string[]              splitEntityPermissions;
            const string          initialName = "foo";
            JsonEntityQueryResult jsonEntityQueryResult;

            splitEntityPermissions = entityPermissions.Split(new[] { ',' },
                                                             StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.SetField("core:name", initialName);
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitEntityPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(string.Format(@"data/v1/entity/{0}?request=name", entity.Id),
                                                             PlatformHttpMethod.Get, userAccount))
                {
                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult),
                                "Web service call failed");
                    jsonEntityQueryResult = request.DeserialiseResponseBody <JsonEntityQueryResult>();
                    if (expectedResult == HttpStatusCode.OK)
                    {
                        Assert.That(jsonEntityQueryResult.Ids, Is.EquivalentTo(new long[] { entity.Id }));
                    }
                    else
                    {
                        Assert.That(jsonEntityQueryResult.Ids, Is.Null);
                        Assert.That(jsonEntityQueryResult.Entities, Is.Empty);
                        Assert.That(jsonEntityQueryResult.EntityRefs, Is.Empty);
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
예제 #23
0
        public void Test_Clone(string entityPermissions, string entityTypePermissions, HttpStatusCode expectedResult)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;
            IEntity         clonedEntity;

            string[]     splitEntityPermissions;
            string[]     splitEntityTypePermissions;
            const string initialName = "foo";
            const string newName     = "bar";
            long         cloneId;

            splitEntityPermissions = entityPermissions.Split(new[] { ',' },
                                                             StringSplitOptions.RemoveEmptyEntries);
            splitEntityTypePermissions = entityTypePermissions.Split(new[] { ',' },
                                                                     StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.SetField("core:name", initialName);
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitEntityPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllow(userAccount.As <Subject>(),
                                                 splitEntityTypePermissions.Select(s => new EntityRef(s)),
                                                 entityType.As <SecurableEntity>());

                using (var request = new PlatformHttpRequest(@"data/v1/entity/clone", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new EntityCloneRequest
                    {
                        Id   = new JsonEntityRef(new EntityRef(entity)),
                        Name = newName
                    });

                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult),
                                "Web service call failed");
                    if (expectedResult == HttpStatusCode.OK)
                    {
                        cloneId = request.DeserialiseResponseBody <long>();
                        entitiesToDelete.Add(cloneId);

                        clonedEntity = Entity.Get(cloneId);
                        Assert.That(clonedEntity, Is.Not.Null, "Entity not found");
                        Assert.That(clonedEntity.GetField("core:name"), Is.EqualTo(newName), "Name incorrect");
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
예제 #24
0
        // CANNOT RUN THIS AS A TRANSACTION
        public void Bug_GrindsToHalt_22822()
        {
            int      createdEntities = 50;
            Workflow myWorkflow;

            using (new WorkflowRunContext()
            {
                RunTriggersInCurrentThread = true
            })
            {
                // **** Note to DQ ******
                // Make sure that WorkflowConfiguration.TriggerSettings.MaxConcurrency is set to 6 (or some number other than one) so that it is running more realistically.
                //

                var myType = CreateType("CreateTriggerAddsAndRemovesTypeHook_type", UserResource.UserResource_Type);
                myWorkflow = CreateWorkflow("CreateTriggerAddsAndRemovesTypeHook_workflow");
                var myTrigger = CreateTrigger("CreateTriggerAddsAndRemovesTypeHook_trigger", myType, myWorkflow);

                ToDelete.Add(myType.Id);
                ToDelete.Add(myWorkflow.Id);
                ToDelete.Add(myTrigger.Id);

                myType.AsWritable();
                myType.Name = "Creatable";
                myType.IsOfType.Add(Resource.Resource_Type);
                myType.Save();

                var myUser = Entity.Create <UserAccount>();
                myUser.Name = "Bob" + DateTime.Now;
                myUser.Save();
                ToDelete.Add(myUser.Id);

                new AccessRuleFactory().AddAllowByQuery(
                    myUser.As <Subject>(),
                    Resource.Resource_Type.As <SecurableEntity>(),
                    new EntityRef("core:create").ToEnumerable(),
                    TestQueries.EntitiesWithName("Creatable").ToReport());

                using (new SetUser(myUser))
                {
                    for (int i = 0; i < createdEntities; i++)
                    {
                        var e = Entity.Create(myType).As <Resource>();
                        e.Name          = "MyName";
                        e.CreatedDate   = DateTime.Now;
                        e.CreatedBy     = myUser;
                        e.SecurityOwner = myUser;
                        e.Save();
                        ToDelete.Add(e.Id);
                    }
                }
            }

            var wf = Entity.Get <Workflow>(myWorkflow);
            var runningInstances = wf.RunningInstances;

            Assert.That(runningInstances.Count(), Is.EqualTo(createdEntities));

            var failures = runningInstances.Count(r => r.WorkflowRunStatus_Enum != WorkflowRunState_Enumeration.WorkflowRunCompleted);

            Assert.That(failures, Is.EqualTo(0), "No runs failed");
        }
예제 #25
0
        public IActionResult Migrate(int id)
        {
            var result = string.Empty;

            var stock       = new ImportStock();
            var feedback    = new ImportFeedback();
            var strategy    = new ImportStrategy();
            var transaction = new ImportTransaction();

            switch (id)
            {
            case 0:     //Erase Database
            {
                PerformanceStats.Reset();
                _modelRepositoryDeletionCoordinator.DeleteAll();
                result = "Deleted data from current application database";
                break;
            }

            case 1:     //Import stocks
            {
                stock.Start();
                result = "Imported stocks";
                new MigrationItemPersister <StockDto>("stock").Set(stock.Items);
                new MigrationItemPersister <StockDto>("dividendstock").Set(stock.DividendItems);
                break;
            }

            case 2:     //Import quotations
            {
                //var quotations = new ImportQuotations();
                //quotations.StockItems = new MigrationItemPersister<StockDto>("stock").Get();
                //quotations.Start();

                result = "Imported quotations";
                break;
            }

            case 3:     //Download quotations
            {
                //var downloadQuotations = new DownloadQuotations();
                //downloadQuotations.Start();
                result = "Downloaded quotations";
                break;
            }

            case 4:     //Import feedbacks
            {
                feedback.Start();
                result = "Imported feedbacks";
                new MigrationItemPersister <FeedbackDto>("feedback").Set(feedback.Items);
                break;
            }

            case 5:     //Import strategies
            {
                strategy.Start();
                result = "Imported strategies";
                new MigrationItemPersister <StrategyDto>("strategy").Set(strategy.Items);
                break;
            }

            case 6:     //Import calculations
            {
                var calculation = new ImportCalculations();
                calculation.Start();
                result = "Imported calculations";
                break;
            }

            case 7:     //Import transactions
            {
                transaction.FeedbackItems      = new MigrationItemPersister <FeedbackDto>("feedback").Get();
                transaction.StockItems         = new MigrationItemPersister <StockDto>("stock").Get();
                transaction.StrategyItems      = new MigrationItemPersister <StrategyDto>("strategy").Get();
                transaction.DividendStockItems = new MigrationItemPersister <StockDto>("dividendstock").Get();

                transaction.Start();
                result = "Imported transactions";
                new MigrationItemPersister <ITransactionDto>("transaction").Set(transaction.Items);
                break;
            }

            case 8:     //Testing queries
            {
                var testing = new TestQueries();
                testing.Start();
                result = "Tested results with queries";
                break;
            }

            case 9:     //Testing performance
            {
                var stats = new TestPerformance(new MigrationItemPersister <ITransactionDto>("transaction").Get());
                stats.Start();
                result = "Finished testing statistics";
                break;
            }

            case 10:     //Testing open positions
            {
                var openPositions = new TestOpenPositions(new MigrationItemPersister <StockDto>("stock").Get(), new MigrationItemPersister <ITransactionDto>("transaction").Get());
                openPositions.Start();
                result = "Finished testing open positions";
                break;
            }

            case 11:     //Statistics
            {
                PerformanceStats.WriteToConsole();
                result = "Flushed performance statistis";
                break;
            }

            default:
            {
                break;
            }
            }


            return(Json(result));
        }
예제 #26
0
        public void Test_Delete(string permissions, HttpStatusCode expectedResult)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;
            IEntity         modifiedEntity;

            string[] splitPermissions;

            splitPermissions = permissions.Split(new[] { ',' },
                                                 StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(@"data/v1/entity?id=" + entity.Id, PlatformHttpMethod.Delete, userAccount))
                {
                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult), "Web service call failed");

                    if (expectedResult != HttpStatusCode.OK)
                    {
                        return;
                    }

                    EntityCache.Instance.Remove(entity.Id);
                    modifiedEntity = Entity.Get(entity.Id);
                    Assert.That(modifiedEntity, Is.Null, "Entity not deleted");
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
예제 #27
0
        public void Test_Filter_ActionRequiresParentModifyAccess(string parentEntityPermissions, string childEntityPermissions)
        {
            SecurityActionMenuItemFilter securityActionMenuItemFilter;
            UserAccount userAccount;
            EntityType  parentEntityType;
            EntityType  childEntityType;
            IEntity     parentEntity;
            IEntity     childEntity;

            const string viewResourceActionAlias       = "console:viewResourceAction";
            const string editResourceActionAlias       = "console:editResourceAction";
            const string deleteResourceActionAlias     = "console:deleteResourceAction";
            const string addRelationshipActionAlias    = "console:addRelationshipAction";
            const string removeRelationshipActionAlias = "console:removeRelationshipAction";

            var splitParentEntityPermissions = parentEntityPermissions.Split(new[] { ',' },
                                                                             StringSplitOptions.RemoveEmptyEntries);

            var splitChildEntityPermissions = childEntityPermissions.Split(new[] { ',' },
                                                                           StringSplitOptions.RemoveEmptyEntries);


            userAccount      = new UserAccount();
            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.Save();

            // parent
            parentEntityType = new EntityType();
            parentEntityType.Inherits.Add(UserResource.UserResource_Type);
            parentEntityType.Save();

            parentEntity = Entity.Create(new EntityRef(parentEntityType));
            parentEntity.SetField("core:name", "A"); // "A" so it will match the access rule
            parentEntity.Save();

            // related child entity
            childEntityType = new EntityType();
            childEntityType.Inherits.Add(UserResource.UserResource_Type);
            childEntityType.Save();

            childEntity = Entity.Create(new EntityRef(childEntityType));
            childEntity.SetField("core:name", "B"); // "B" so it will match the access rule
            childEntity.Save();

            // grant accesses
            // parent entity
            new AccessRuleFactory().AddAllowByQuery(
                userAccount.As <Subject>(),
                parentEntityType.As <SecurableEntity>(),
                splitParentEntityPermissions.Select(s => new EntityRef(s)),
                TestQueries.EntitiesWithNameA().ToReport());

            // child entity
            new AccessRuleFactory().AddAllowByQuery(
                userAccount.As <Subject>(),
                childEntityType.As <SecurableEntity>(),
                splitChildEntityPermissions.Select(s => new EntityRef(s)),
                TestQueries.EntitiesWithNameB().ToReport());

            // actions
            var dummyRequest = new ActionRequestExtended();
            Func <ActionRequestExtended, ActionMenuItem, ActionTargetInfo> dummyHandler = (a, i) => new ActionTargetInfo();
            var actions = new List <ActionMenuItemInfo>();

            foreach (string menuItemAlias in new[]
            {
                viewResourceActionAlias,
                editResourceActionAlias,
                addRelationshipActionAlias,
                removeRelationshipActionAlias,
                deleteResourceActionAlias,
            })
            {
                actions.Add(Entity.Get <ActionMenuItem>(menuItemAlias).ToInfo(dummyRequest, null, dummyHandler));
            }

            actions.Add(new ActionMenuItemInfo
            {
                EntityId        = childEntityType.Id,
                HtmlActionState = "createForm",
                IsNew           = true
            });

            // filter actions
            using (new SetUser(userAccount))
            {
                securityActionMenuItemFilter = new SecurityActionMenuItemFilter();
                securityActionMenuItemFilter.Filter(parentEntity.Id, new[] { childEntity.Id }, actions);
            }

            // checks
            if (splitParentEntityPermissions.Contains("core:read") && splitParentEntityPermissions.Contains("core:modify"))
            {
                Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(addRelationshipActionAlias), "Missing add relationship resource action");
                Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(removeRelationshipActionAlias), "Missing remove relationship resource action");

                // child create
                if (splitChildEntityPermissions.Contains("core:create"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("HtmlActionState").EqualTo("createForm"), "Missing create resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("HtmlActionState").EqualTo("createForm"), "Create resource action should not be available");
                }

                // child read
                if (splitChildEntityPermissions.Contains("core:read"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(viewResourceActionAlias), "Missing view resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(viewResourceActionAlias), "View resource action should not be available");
                }

                // child modify
                if (splitChildEntityPermissions.Contains("core:modify"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(editResourceActionAlias), "Missing edit resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(editResourceActionAlias), "Edit resource action should not be available");
                }

                // child delete
                if (splitChildEntityPermissions.Contains("core:delete"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(deleteResourceActionAlias), "Missing delete resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(deleteResourceActionAlias), "Delete resource action should not be available");
                }
            }
            else if (splitParentEntityPermissions.Contains("core:read") && !splitParentEntityPermissions.Contains("core:modify"))
            {
                Assert.That(actions, Has.None.Property("Alias").EqualTo(addRelationshipActionAlias), "Add relationship action should not be available");
                Assert.That(actions, Has.None.Property("Alias").EqualTo(removeRelationshipActionAlias), "Remove relationship action should not be available");

                // child create
                Assert.That(actions, Has.None.Property("HtmlActionState").EqualTo("createForm"), "Create resource action should not be available");

                // child read
                if (splitChildEntityPermissions.Contains("core:read"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(viewResourceActionAlias), "Missing view resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(viewResourceActionAlias), "View resource action should not be available");
                }

                // child modify
                if (splitChildEntityPermissions.Contains("core:modify"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(editResourceActionAlias), "Missing edit resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(editResourceActionAlias), "Edit resource action should not be available");
                }

                // child delete
                Assert.That(actions, Has.None.Property("Alias").EqualTo(deleteResourceActionAlias), "Delete resource action should not be available");
            }
        }
예제 #28
0
        public void Test_ModifyField(string permissions, HttpStatusCode expectedResult)
        {
            EntityType      entityType;
            StringField     field;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;
            IEntity         modifiedEntity;
            const string    initialFieldValue = "foo";
            const string    newFieldValue     = "bar";

            string[] splitPermissions;

            splitPermissions = permissions.Split(new [] { ',' },
                                                 StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                field      = Entity.Create <StringField>();
                field.Name = "Test field " + Guid.NewGuid();
                field.Save();
                entitiesToDelete.Add(field.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Fields.Add(field.As <Field>());
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.SetField(field, initialFieldValue);
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(@"data/v1/entity", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonEntityQueryResult
                    {
                        Ids = new List <long> {
                            entity.Id
                        },
                        Entities = new List <JsonEntity>
                        {
                            new JsonEntity
                            {
                                Id      = entity.Id,
                                TypeIds = new List <long> {
                                    entityType.Id
                                },
                                Fields = new List <JsonFieldData>
                                {
                                    new JsonFieldData
                                    {
                                        FieldId  = field.Id,
                                        Value    = newFieldValue,
                                        TypeName = "String"
                                    }
                                },
                                Relationships = new List <JsonRelationshipData>(),
                                DataState     = DataState.Update
                            }
                        },
                        EntityRefs = new List <JsonEntityRef>
                        {
                            new JsonEntityRef(new EntityRef(entity.Id)),
                            new JsonEntityRef(new EntityRef(entityType)),
                            new JsonEntityRef(new EntityRef(field))
                        }
                    });

                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult),
                                "Web service call failed");

                    if (expectedResult == HttpStatusCode.OK)
                    {
                        modifiedEntity = Entity.Get(entity.Id);
                        Assert.That(modifiedEntity, Is.Not.Null, "Entity not found");
                        Assert.That(modifiedEntity.GetField(field), Is.EqualTo(newFieldValue),
                                    "Field value incorrect");
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
예제 #29
0
        public void LowAccessUserPausedPriorNestedWorkflow_bug_27863()
        {
            using (new WorkflowRunContext {
                RunTriggersInCurrentThread = true
            })
            {
                Workflow       myParentWorkflow = null;
                Workflow       myChildWorkflow  = null;
                UserAccount    myUser           = null;
                Person         myPerson         = null;
                PromptUserTask userInputTask    = null;

                try
                {
                    myChildWorkflow = Entity.Create <Workflow>()
                                      .AddDefaultExitPoint()
                                      .AddInput <BoolArgument>("InputChild")
                                      .AddLog("Child Log", "Child Log");

                    myChildWorkflow.Name = "Child Workflow 27863 " + DateTime.Now;
                    myChildWorkflow.WorkflowRunAsOwner = true;
                    myChildWorkflow.Save();

                    myParentWorkflow = Entity.Create <Workflow>()
                                       .AddDefaultExitPoint()
                                       .AddInput <BoolArgument>("InputParent")
                                       .AddPromptUser("User Input")
                                       .AddWorkflowProxy("Child Workflow", myChildWorkflow)
                                       .AddLog("Parent Log", "Parent Log");

                    var childWorkflowActivity = myParentWorkflow.ContainedActivities.FirstOrDefault(a => a.Name == "Child Workflow");

                    ActivityTestHelper.AddExpressionToActivityArgument(myParentWorkflow, childWorkflowActivity, "InputChild", "[InputParent]");

                    myParentWorkflow.Name = "Parent Workflow 27863 " + DateTime.Now;
                    myParentWorkflow.WorkflowRunAsOwner = true;
                    myParentWorkflow.Save();

                    myPerson             = Entity.Create <Person>();
                    myPerson.FirstName   = "Billy";
                    myPerson.LastName    = "Bob";
                    myUser               = Entity.Create <UserAccount>();
                    myUser.Name          = "bb" + DateTime.Now;
                    myUser.AccountHolder = myPerson;
                    myUser.Save();

                    new AccessRuleFactory().AddAllowByQuery(myUser.As <Subject>(),
                                                            Workflow.Workflow_Type.As <SecurableEntity>(),
                                                            new EntityRef("core:read").ToEnumerable(),
                                                            TestQueries.Entities(new EntityRef("core:workflow")).ToReport());

                    WorkflowRun run;

                    using (new SetUser(myUser))
                        using (new WorkflowRunContext(true)
                        {
                            RunTriggersInCurrentThread = true
                        })
                        {
                            run = RunWorkflow(myParentWorkflow);
                        }

                    run.WorkflowRunStatus_Enum.Should().Be(WorkflowRunState_Enumeration.WorkflowRunPaused);
                    run.PendingActivity.Should().NotBeNull();
                    run.PendingActivity.Name.Should().Be("User Input");
                    run.TaskWithinWorkflowRun.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(1);

                    userInputTask = run.TaskWithinWorkflowRun.First().AsWritable <PromptUserTask>();
                    userInputTask.Should().NotBeNull();

                    userInputTask.PromptForTaskStateInfo.Should().NotBeNull().And.HaveCount(1);
                    userInputTask.PromptForTaskStateInfo.Select(si => si.StateInfoArgument.Name).Should().Contain("InputParent");

                    var value = userInputTask.PromptForTaskStateInfo.First(si => si.StateInfoArgument.Name == "InputParent");
                    var param = value.StateInfoValue.AsWritable <BoolArgument>();
                    param.BoolParameterValue = true;
                    param.Save();

                    userInputTask.TaskStatus_Enum    = TaskStatusEnum_Enumeration.TaskStatusCompleted;
                    userInputTask.UserTaskIsComplete = true;

                    using (new SetUser(myUser))
                        using (new WorkflowRunContext(true)
                        {
                            RunTriggersInCurrentThread = true
                        })
                        {
                            userInputTask.Save();
                        }

                    var wf = Entity.Get <Workflow>(myParentWorkflow.Id, Workflow.RunningInstances_Field);

                    wf.RunningInstances.Count().Should().Be(1);
                    var runResume = wf.RunningInstances.First();

                    Assert.IsTrue(WaitForWorkflowToStop(runResume), "Workflow run should have completed.");

                    runResume = Entity.Get <WorkflowRun>(runResume.Id, WorkflowRun.WorkflowRunStatus_Field);
                    runResume.Should().NotBeNull();
                    runResume.WorkflowRunStatus_Enum.Should().Be(WorkflowRunState_Enumeration.WorkflowRunCompleted);
                    runResume.RunLog.Should().NotBeNull().And.NotBeEmpty();
                }
                finally
                {
                    if (userInputTask != null)
                    {
                        ToDelete.Add(userInputTask.Id);
                    }
                    if (myParentWorkflow != null)
                    {
                        ToDelete.Add(myParentWorkflow.Id);
                    }
                    if (myChildWorkflow != null)
                    {
                        ToDelete.Add(myChildWorkflow.Id);
                    }
                    if (myUser != null)
                    {
                        ToDelete.Add(myUser.Id);
                    }
                    if (myPerson != null)
                    {
                        ToDelete.Add(myPerson.Id);
                    }
                }
            }
        }
예제 #30
0
        public void Test_ModifyRelationship(string entity1Permissions,
                                            string entity2Permissions, bool forward, HttpStatusCode expectedResult)
        {
            EntityType      entityType1;
            EntityType      entityType2;
            Relationship    relationship;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity1;
            IEntity         entity2;
            long            newId;
            IEntity         newEntity;

            string[] splitEntity1Permissions;
            string[] splitEntity2Permissions;

            splitEntity1Permissions = entity1Permissions.Split(new[] { ',' },
                                                               StringSplitOptions.RemoveEmptyEntries);
            splitEntity2Permissions = entity2Permissions.Split(new[] { ',' },
                                                               StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType1 = Entity.Create <EntityType>();
                entityType1.Inherits.Add(UserResource.UserResource_Type);
                entityType1.Save();
                entitiesToDelete.Add(entityType1.Id);

                entity1 = Entity.Create(entityType1);
                entity1.Save();
                entitiesToDelete.Add(entity1.Id);

                entityType2 = Entity.Create <EntityType>();
                entityType2.Inherits.Add(UserResource.UserResource_Type);
                entityType2.Save();
                entitiesToDelete.Add(entityType2.Id);

                entity2 = Entity.Create(entityType2);
                entity2.Save();
                entitiesToDelete.Add(entity2.Id);

                relationship          = Entity.Create <Relationship>();
                relationship.FromType = entityType1;
                relationship.ToType   = entityType2;
                relationship.RelType  = Entity.Get <RelTypeEnum>("core:relManyToMany");
                relationship.Save();
                entitiesToDelete.Add(relationship.Id);

                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    entityType1.As <SecurableEntity>(),
                    splitEntity1Permissions.Select(p => new EntityRef(p)),
                    TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    entityType2.As <SecurableEntity>(),
                    splitEntity2Permissions.Select(p => new EntityRef(p)),
                    TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(@"data/v1/entity", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonEntityQueryResult
                    {
                        Ids = new List <long> {
                            entity1.Id
                        },
                        Entities = new List <JsonEntity>
                        {
                            new JsonEntity
                            {
                                Id      = entity1.Id,
                                TypeIds = new List <long> {
                                    entityType1.Id
                                },
                                Fields        = new List <JsonFieldData>(),
                                Relationships = new List <JsonRelationshipData>
                                {
                                    new JsonRelationshipData
                                    {
                                        RelTypeId = new JsonEntityRef(relationship),
                                        Instances = new List <JsonRelationshipInstanceData>
                                        {
                                            new JsonRelationshipInstanceData
                                            {
                                                Entity    = entity2.Id,
                                                RelEntity = 0,
                                                DataState = DataState.Create
                                            }
                                        },
                                        IsReverse = !forward
                                    }
                                },
                                DataState = DataState.Create
                            }
                        },
                        EntityRefs = new List <JsonEntityRef>
                        {
                            new JsonEntityRef(new EntityRef(entity1)),
                            new JsonEntityRef(new EntityRef(entity2)),
                            new JsonEntityRef(new EntityRef(entityType1)),
                            new JsonEntityRef(new EntityRef(entityType2)),
                            new JsonEntityRef(new EntityRef(relationship))
                        }
                    });

                    response = request.GetResponse();
                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult),
                                "Web service call failed");

                    if (expectedResult == HttpStatusCode.OK)
                    {
                        newId = request.DeserialiseResponseBody <long>();
                        entitiesToDelete.Add(newId);

                        newEntity = Entity.Get(newId);
                        Assert.That(newEntity, Is.Not.Null, "New entity does not exist");
                        Assert.That(newEntity, Has.Property("TypeIds").Contains(entityType1.Id),
                                    "New entity missing correct type");
                        if (forward)
                        {
                            Assert.That(newEntity.GetRelationships(relationship), Has.Count.EqualTo(1),
                                        "Relationship count incorrect");
                        }
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }