示例#1
0
        public void ShouldWork()
        {
            IAclProvider categories = new MemoryProvider();
            IAclProvider widgets    = new MemoryProvider();
            IAclProvider urls       = new MemoryProvider();

            widgets.SetAcls(
                new Deny("/", "read", "*"),
                new Allow("/", "read", "g1")
                );
            urls.SetAcls(
                new Allow("/c", "read", "g2"),
                new Deny("/c", "read", "g3"),
                new Allow("/d", "read", "g3"),
                new Deny("/d", "read", "*"),
                new Deny("/", "read", "g2")
                );

            RouterProvider router = new RouterProvider();

            router.Register("/a", widgets);
            router.Register("/a/b", urls);
            AclManager.DefaultProvider = router;

            Assert.AreEqual(5, router.GetAcls("/a/b/c", "read").Count());
            Assert.AreEqual(5, router.GetAcls("/a/b/d", "read").Count());

            Assert.IsTrue(AclManager.IsAllowed("/a/b/c", "read", "g1", "g2"));
            Assert.IsFalse(AclManager.IsAllowed("/a/b/c", "read", "g1", "g3"));
            Assert.IsTrue(AclManager.IsAllowed("/a/b/d", "read", "g3"));

            Assert.IsTrue(AclManager.IsAllowed("/a/b/d", "read", "g1", "g3"));
            Assert.IsFalse(AclManager.IsAllowed("/a/b/d", "read", "g1", "g2"));
            Assert.IsFalse(AclManager.IsAllowed("/a/b/c", "read", "g3"));
        }
示例#2
0
        public void ShouldDenyNotAuthorized()
        {
            AclManager.DefaultProvider = new MemoryProvider();

            AclManager.Allow("/travel", "read", "s.ros");

            ShouldDenyNotAuthorizedByConfiguration();
        }
示例#3
0
 public void ShouldDenyNotAuthorizedByConfiguration()
 {
     Assert.IsTrue(AclManager.IsAllowed("/travel", "read", "s.ros"));
     Assert.IsTrue(AclManager.IsAllowed("/travel/asshole", "read", "s.ros"));
     Assert.IsFalse(AclManager.IsAllowed("/", "read", "s.ros"));
     Assert.IsFalse(AclManager.IsAllowed("/", "read", "peter"));
     Assert.IsFalse(AclManager.IsAllowed("/travel", "read", "peter"));
     Assert.IsFalse(AclManager.IsAllowed("/travel/asshole", "read", "peter"));
 }
示例#4
0
        public void ShouldNotifyOnAclRuleChange()
        {
            var router = new RouterProvider();

            AclManager.DefaultProvider = router;
            router.Register("/travel", new MemoryProvider());
            AclManager.RegisterForRuleChange("/travel", s => TestContext.WriteLine("'{0}' has changed", s));
            AclManager.AclChanged += new Action <string>(s => TestContext.WriteLine("* '{0}' has changed", s));
            AclManager.Allow("/", "read", "*");
            AclManager.Deny("/travel", "read", "s.ros");
            AclManager.Deny("/travel/asshole", "read", "s.ros");
        }
示例#5
0
        public void Bug()
        {
            AclManager.DefaultProvider = new MemoryProvider();
            AclManager.Allow("/", "read", "*");
            AclManager.Deny("/travel", "read", "s.ros");

            Assert.IsFalse(AclManager.IsAllowed("/travel", "read", "s.ros"));
            Assert.IsFalse(AclManager.IsAllowed("/travel/asshole", "read", "s.ros"));
            Assert.IsTrue(AclManager.IsAllowed("/", "read", "s.ros"));
            Assert.IsTrue(AclManager.IsAllowed("/", "read", "peter"));
            Assert.IsTrue(AclManager.IsAllowed("/travel", "read", "peter"));
            Assert.IsTrue(AclManager.IsAllowed("/travel/asshole", "read", "peter"));
        }
示例#6
0
        public void SqlAclShouldWork()
        {
            AclManager.DefaultProvider = new SqlAclProvider();

            AclManager.Allow("/", "read", "*");
            AclManager.Deny("/travel", "read", "s.ros");

            Assert.IsFalse(AclManager.IsAllowed("/travel", "read", "s.ros"));
            Assert.IsFalse(AclManager.IsAllowed("/travel/asshole", "read", "s.ros"));
            Assert.IsTrue(AclManager.IsAllowed("/", "read", "s.ros"));
            Assert.IsTrue(AclManager.IsAllowed("/", "read", "peter"));
            Assert.IsTrue(AclManager.IsAllowed("/travel", "read", "peter"));
            Assert.IsTrue(AclManager.IsAllowed("/travel/asshole", "read", "peter"));
        }
示例#7
0
        void context_AuthorizeRequest(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;

            if (!context.SkipAuthorization)
            {
                if (!AclManager.IsAllowed(context.Request.Url.AbsolutePath, context.Request.HttpMethod, Roles.GetRolesForUser()))
                {
                    context.Response.StatusCode = 401;
                    WriteErrorMessage(context);
                    ((HttpApplication)sender).CompleteRequest();
                }
            }
        }
示例#8
0
 public void Install()
 {
     if (!Globals.InPortableMode)
     {
         Uninstall();
     }
     UpdateStatus("Updating folder permissions...");
     // Create the folder
     if (Directory.Exists(installOptions.DestinationDirectory) == false)
     {
         Directory.CreateDirectory(installOptions.DestinationDirectory);
     }
     if (!Globals.InPortableMode)
     {
         // Set the folder permissions
         AclManager Acl = new AclManager(installOptions.DestinationDirectory, AclManager.GetNormalUsersGroupName(), "F");
         Acl.SetAcl();
     }
     // Time to download the installation file...
     Net.FileDownloader downloader = new Net.FileDownloader();
     // First let's subscribe to the events
     downloader.DownloadUpdate += delegate(object sender, Net.FileDownloadingEventArgs e)
     {
         // Display the progress of the download
         UpdateStatus("Downloading latest installation files... [" + e.Percent + "% complete]");
         UpdateProgress(e.Percent);
     };
     downloader.DownloadComplete += delegate(object sender, Net.FileDownloadingEventArgs e)
     {
         // The installation files have been downloaded, so we can continue installing them
         InstallationFilesDownloaded();
     };
     downloader.DownloadFailed += delegate(object sender, Net.FileDownloadErrorEventArgs e)
     {
         // Uh oh! The download failed!
     };
     // Now we actually download the file
     if (File.Exists(installOptions.DestinationDirectory + "\\InstallationFiles-MapEditor.zip"))
     {
         InstallationFilesDownloaded();
     }
     else
     {
         downloader.DownloadFile(installOptions.DownloadURL, installOptions.DestinationDirectory + "\\InstallationFiles-MapEditor.zip");
     }
     //if (InstallComplete != null)
     //    InstallComplete(this, EventArgs.Empty);
 }
示例#9
0
文件: Acls.cs 项目: spcooney/NAcl
        private static void HandleAclRefreshedForFrameworkElement(DependencyObject target, string resourceKey, string[] subjects)
        {
            FrameworkElement targetFrameworkElement = target as FrameworkElement;

            if (targetFrameworkElement != null)
            {
                targetFrameworkElement.Visibility = AclManager.IsAllowed(resourceKey, Verbs.Visible.ToString(), subjects) ? Visibility.Visible : Visibility.Collapsed;

                Control targetControl = target as Control;

                if (targetControl != null)
                {
                    targetControl.IsEnabled = AclManager.IsAllowed(resourceKey, Verbs.Enabled.ToString(), subjects);
                }
            }
        }
示例#10
0
        /// <summary>
        /// Initializes module's properties
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        private ModuleConfig InternalGetConfig(string filePath, string name)
        {
            if (_IsInitialized.ContainsKey(name) && !HasConfigChanged(name))
            {
                return(_Configs[name]);
            }

            _Dependencies[name] = new CacheDependency(filePath, DateTime.Now);
            XmlDocument doc = new XmlDocument();

            doc.Load(filePath);
            XmlNode section = doc.SelectSingleNode("Configuration");

            if (section == null)
            {
                return(null);
            }

            ModuleConfig config = new ModuleConfig(name);

            XmlNode node = section.SelectSingleNode("Views");

            if (node == null)
            {
                return(null);
            }

            config.Views = ViewManager.CreateViewCollection(config, node);

            XmlNode settingsNode = section.SelectSingleNode("Settings");

            if (settingsNode != null)
            {
                config.Settings = SettingManager.CreateSettingsCollection(settingsNode);
            }

            // Create ACL
            XmlNode aclNode = section.SelectSingleNode("Acl");

            if (aclNode != null)
            {
                config.Acl        = new Acl();
                config.Acl.Groups = AclManager.CreateAclCollection(config, aclNode);
            }

            return(config);
        }
示例#11
0
 public static PrivateData <Dictionary <Guid, AclResponseItem> > PrepareAclFieldItem(Guid guid)
 {
     return(new PrivateData <Dictionary <Guid, AclResponseItem> >(
                (session, test) =>
     {
         return Task.Run(() =>
         {
             var handler = new AclManager();
             var result = handler.ReadAclInfo(guid);
             PrAssume.That(result, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Can not read acl field");
             return result.Result[guid];
         });
     },
                (session, test, res) => Task.Run(() =>
     {
     })));
 }
示例#12
0
        public void ShouldHandleStarVerb()
        {
            RouterProvider router = new RouterProvider();

            AclManager.DefaultProvider = router;
            IAclProvider urls = new MemoryProvider();

            router.Register("/Widget/Rss/Urls", urls);
            IAclProvider actions = new MemoryProvider();

            router.Register("/Widget", actions);
            AclManager.Allow("/Widget", "*", "*");
            AclManager.Deny("/Widget/Rss/Urls", "access", "~/Widgets/ClientRss/ClientRssWidget.ascx");
            AclManager.Allow("/Widget/Rss/Urls/fr/happly", "Access", "~/Widgets/ClientRss/ClientRssWidget.ascx");
            AclManager.Deny("/Widget/Rss/Urls/fr/happly/knowledgebank", "access", "~/Widgets/ClientRss/ClientRssWidget.ascx");

            Assert.IsFalse(AclManager.IsAllowed("/Widget/Rss/Urls", "access", "~/Widgets/ClientRss/ClientRssWidget.ascx"));
            Assert.IsFalse(AclManager.IsAllowed("/Widget/Rss/Urls/fr/happly/knowledgebank", "access", "~/Widgets/ClientRss/ClientRssWidget.ascx"));
            Assert.IsTrue(AclManager.IsAllowed("/Widget/Rss/Urls/fr/happly/knoledgebank", "access", "~/Widgets/ClientRss/ClientRssWidget.ascx"));
            Assert.IsTrue(AclManager.IsAllowed("/Widget", "read", "~/Widgets/ClientRss/ClientRssWidget.ascx"));
            Assert.IsTrue(AclManager.IsAllowed("/Widget/Rss/Urls/fr/happly/knowledgebank", "read", "~/Widgets/ClientRss/ClientRssWidget.ascx"));
        }
 public static PrivateData <Dictionary <ResourceId, int> > PrepareAclFieldItem(Func <Dictionary <ResourceId, Guid> > guidProvider)
 {
     return(new PrivateData <Dictionary <ResourceId, int> >(
                (session, test) =>
     {
         return Task.Run(() =>
         {
             var guids = guidProvider();
             var result = new Dictionary <ResourceId, int>();
             var handler = new AclManager();
             foreach (var resource in Utils.Resources().Cast <ResourceId>())
             {
                 var response = handler.ReadAclInfo(guids[resource]);
                 PrAssume.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Can not read acl field");
                 result.Add(resource, response.Result.First().Value.First().Value.Phases.Keys.First());
             }
             return result;
         });
     },
                (session, test, res) => Task.Run(() =>
     {
     })));
 }
示例#14
0
 public void ShouldDenyEveryoneWhenNoRule()
 {
     AclManager.DefaultProvider = new MemoryProvider();
     Assert.IsFalse(AclManager.IsAllowed("/", "read"));
     Assert.IsFalse(AclManager.IsAllowed("/", "read", "s.ros"));
 }
示例#15
0
 public void Install()
 {
     if (!Globals.InPortableMode) {
         Uninstall();
     }
     UpdateStatus("Updating folder permissions...");
     // Create the folder
     if (Directory.Exists(installOptions.DestinationDirectory) == false) {
         Directory.CreateDirectory(installOptions.DestinationDirectory);
     }
     if (!Globals.InPortableMode) {
         // Set the folder permissions
         AclManager Acl = new AclManager(installOptions.DestinationDirectory, AclManager.GetNormalUsersGroupName(), "F");
         Acl.SetAcl();
     }
     // Time to download the installation file...
     Net.FileDownloader downloader = new Net.FileDownloader();
     // First let's subscribe to the events
     downloader.DownloadUpdate += delegate(object sender, Net.FileDownloadingEventArgs e)
     {
         // Display the progress of the download
         UpdateStatus("Downloading latest installation files... [" + e.Percent + "% complete]");
         UpdateProgress(e.Percent);
     };
     downloader.DownloadComplete += delegate(object sender, Net.FileDownloadingEventArgs e)
     {
         // The installation files have been downloaded, so we can continue installing them
         InstallationFilesDownloaded();
     };
     downloader.DownloadFailed += delegate(object sender, Net.FileDownloadErrorEventArgs e)
     {
         // Uh oh! The download failed!
     };
     // Now we actually download the file
     if (File.Exists(installOptions.DestinationDirectory + "\\InstallationFiles-Client.zip")) {
         InstallationFilesDownloaded();
     } else {
         downloader.DownloadFile(installOptions.DownloadURL, installOptions.DestinationDirectory + "\\InstallationFiles-Client.zip");
     }
 }
示例#16
0
        public void UpdateFieldsTest()
        {
            const string FieldPropertyToModify = "d.label.ja";
            var          resource = ResourceId.Client;
            var          aliases  = new[] { "P_Country", "P_City", "P_Prefecture" };
            var          resetProgrammingCacheField = "P_Memo";
            var          connection     = PrivateApiConnection.GetConnectionForCurrentTest();
            var          fieldHandler   = new FieldManager();
            var          optionHandler  = new OptionManager();
            var          aclHandler     = new AclManager();
            var          recordsHandler = new RecordManager();
            //PHASE1: preparing test data: reading and updating fields/options/acls/records
            var rawFields = fieldHandler.GetFieldGuid(new[] { "P_Country", "P_Phase", "P_PhaseDate" }, new[] { Porters.TestCoreFramework.Enums.ResourceType.Client })
                            .Result.Result;
            var fields     = rawFields.ToDictionary(x => $"{char.ToUpper(x.Resource[0]) + x.Resource.Substring(1)}.{x.Alias}", x => (int)UuidUtil.GetId(x.Id));
            var guidFields = rawFields.ToDictionary(x => $"{char.ToUpper(x.Resource[0]) + x.Resource.Substring(1)}.{x.Alias}", x => x.Id);

            //fields
            fieldHandler.UpdateField(resetProgrammingCacheField, ResourceId.Client, new Dictionary <string, object> {
                ["d.label.ja"] = "MEMO"
            });

            var originalFieldValues = aliases.ToDictionary(x => x, x => fieldHandler.GetFieldDetails($"{resource}.{x}").Result.Values.Single().Value);

            foreach (var alias in aliases)
            {
                fieldHandler.UpdateField(alias, ResourceId.Client, new Dictionary <string, object> {
                    [FieldPropertyToModify] = $"UPDATE_{alias.ToUpper()}_1"
                });
            }

            //options
            var data = optionHandler.SearchOption("Option.P_LanguageAbility");
            var originalOptionValues = data.Result.Single().Children;

            foreach (var child in data.Result.Single().Children)
            {
                optionHandler.UpdateOption(child.Id, new Dictionary <string, object> {
                    ["name"] = child.Alias
                });
            }

            //acl
            var aclInfo         = aclHandler.ReadAclInfo(guidFields["Client.P_Country"]);
            var originalAclInfo = aclInfo.Result[guidFields["Client.P_Country"]].Last().Value.Phases.ToDictionary(x => x.Key, x => new AclHandlingComponent.DataContract.AclResponseItem.PermissionItem {
                Permission = x.Value.Permission
            });

            aclInfo.Result[guidFields["Client.P_Country"]].Last().Value.Phases.Select(x => x.Value.Permission = 20).ToArray();
            aclHandler.SetFieldAcl(aclInfo.Result);

            //records
            var originalRecordData = recordsHandler.ReadRecords(
                RecordRequestComposer.ComposeReadRequest()
                .ForResource(Porters.TestCoreFramework.Enums.ResourceType.Client)
                .WithIds(new[] { 10001 })
                .Fields("Client.P_Country", "Client.P_Phase", "Client.P_PhaseDate")
                .Result);

            recordsHandler.UpdateRecords(
                RecordRequestComposer.ComposeUpdateRequest().Append(item => item.ForResource(Porters.TestCoreFramework.Enums.ResourceType.Client)
                                                                    .Append(x => x.WithId(10001).AppendField(fields["Client.P_Country"], "TestValue")
                                                                            .AppendField(fields["Client.P_Phase"], originalRecordData.Result.Items.Single()["Client.P_Phase"])
                                                                            .AppendField(fields["Client.P_PhaseDate"], originalRecordData.Result.Items.Single()["Client.P_PhaseDate"]))).Result);

            connection.DeAuthenticate();
            connection.DeleteAllCookies();
            //MANUAL PART: switch DB, restart memcache
            System.Threading.Thread.Sleep(new TimeSpan(0, 5, 5));

            connection.Authenticate();
            //PART3: reading from new DB, making sure that all of values are default
            fieldHandler.UpdateField(resetProgrammingCacheField, ResourceId.Client, new Dictionary <string, object> {
                ["d.label.ja"] = "MEMO"
            });

            // fields check
            var updatedValues = aliases.ToDictionary(x => x, x => fieldHandler.GetFieldDetails($"{resource}.{x}").Result.Values.Single().Value);

            foreach (var alias in aliases)
            {
                PrAssert.That(originalFieldValues[alias].Properties[FieldPropertyToModify], PrIs.EqualTo(updatedValues[alias].Properties[FieldPropertyToModify]));
            }
            //options check
            data = optionHandler.SearchOption("Option.P_LanguageAbility");
            foreach (var child in data.Result.Single().Children)
            {
                PrAssert.That(child.Name, Is.EqualTo(originalOptionValues.Single(x => x.Id == child.Id).Name));
            }
            //acl check
            aclInfo = aclHandler.ReadAclInfo(guidFields["Client.P_Country"]);
            foreach (var aclItem in originalAclInfo)
            {
                PrAssert.That(aclInfo.Result[guidFields["Client.P_Country"]].Last().Value.Phases[aclItem.Key].Permission, Is.EqualTo(aclItem.Value.Permission));
            }
            //records check
            var recordsData = recordsHandler.ReadRecords(
                RecordRequestComposer.ComposeReadRequest()
                .ForResource(Porters.TestCoreFramework.Enums.ResourceType.Client)
                .WithIds(new[] { 10001 })
                .Fields("Client.P_Country", "Client.P_Phase", "Client.P_PhaseDate")
                .Result);

            PrAssert.That(recordsData.Result.Items.Single()["Client.P_Country"], Is.EqualTo(originalRecordData.Result.Items.Single()["Client.P_Country"]));
        }