Esempio n. 1
0
 /// <summary>
 /// Removes all explicit entries from the current content.
 /// If AclEditor passed, the modification is executed in it
 /// else executed immediately.
 /// </summary>
 public void RemoveExplicitEntries(SnAclEditor aclEditor = null)
 {
     if (aclEditor == null)
     {
         _securityHandler.CreateAclEditor()
         .RemoveExplicitEntries(_node.Id)
         .Apply();
         return;
     }
     if (aclEditor.EntryType != EntryType.Normal)
     {
         throw new InvalidOperationException(
                   "EntryType mismatch int the passed AclEditor. Only the EntryType.Normal category is allowed in this context.");
     }
     aclEditor.RemoveExplicitEntries(_node.Id);
 }
Esempio n. 2
0
        public static void SetAcl(Node node, SnAccessControlList acl)
        {
            node.Security.Assert(PermissionType.SetPermissions);

            // no need to fire permission changed events here, because Acl apply does that below
            ApplyAclModifications(SecurityHandler.CreateAclEditor(), node.Security.GetAcl(), acl.ConvertToAccessControlList());
        }
Esempio n. 3
0
        public void Delete_Trash_WithoutAddNewPermission()
        {
            Test(true, () =>
            {
                var originalUser = AccessProvider.Current.GetCurrentUser();

                File file;
                using (new SystemAccount())
                {
                    file = CreateTestFile();

                    // give Visitor Delete permission to the file, but not AddNew
                    // (workaround: add permissions for Visitor to the user content and to the Trash to make this test work)
                    SecurityHandler.CreateAclEditor()
                    .Allow(file.Id, Identifiers.VisitorUserId, false,
                           PermissionType.OpenMinor, PermissionType.Delete)
                    .Allow(TrashBin.Instance.Id, Identifiers.VisitorUserId, false, PermissionType.Open)
                    .Allow(Identifiers.VisitorUserId, Identifiers.VisitorUserId, false, PermissionType.Open)
                    .Apply();
                }

                try
                {
                    AccessProvider.Current.SetCurrentUser(User.Visitor);

                    // action: try to trash the file as Visitor - it should succeed
                    TrashBin.DeleteNode(file);
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);
                }
            });
        }
Esempio n. 4
0
        private static void CopyPermissions(Node source, Node target)
        {
            if (source == null || source.ParentId == 0 || target == null)
            {
                return;
            }

            // copy permissions from the source content, without reseting the permission system
            SecurityHandler.CopyPermissionsFrom(source.Id, target.Id, CopyPermissionMode.BreakAndClear);

            // If there were any permission settings for the Creators group on the source content, we
            // need to place an explicite entry with the same permissions onto the target for the creator
            // user, as the creator of the trashbag (the user who deletes the content) may be different
            // than the creator of the original document.
            var aces = SecurityHandler.GetEffectiveEntriesAsSystemUser(source.Id, new[] { Identifiers.OwnersGroupId }, EntryType.Normal);

            foreach (var ace in aces)
            {
                SecurityHandler.CreateAclEditor().Set(target.Id, ace.IdentityId, ace.LocalOnly, ace.AllowBits, ace.DenyBits);
            }

            aces = SecurityHandler.GetEffectiveEntriesAsSystemUser(source.Id, new[] { Identifiers.OwnersGroupId }, EntryType.Sharing);
            foreach (var ace in aces)
            {
                SnAclEditor.Create(SecurityHandler.SecurityContext, EntryType.Sharing).Set(target.Id, ace.IdentityId, ace.LocalOnly, ace.AllowBits, ace.DenyBits);
            }
        }
Esempio n. 5
0
        public void OD_MBO_BuiltIn_TakeLockOver()
        {
            IsolatedODataTest(() =>
            {
                var user = CreateUser("*****@*****.**");
                SecurityHandler.CreateAclEditor()
                .Allow(2, user.Id, false, PermissionType.PermissionTypes)
                .Apply();

                File file;
                using (new CurrentUserBlock(user))
                {
                    file = new File(CreateTestRoot("TestFiles"))
                    {
                        Name = "File-1"
                    };
                    file.Save();
                    file.CheckOut();
                }

                Assert.AreEqual(user.Id, file.LockedById);

                var url      = ODataTools.GetODataUrl(Content.Create(file));
                var response = ODataPostAsync($"{url}/TakeLockOver", "",
                                              "models=[{'user':'******'}]")
                               .ConfigureAwait(false).GetAwaiter().GetResult();

                Assert.AreEqual(200, response.StatusCode);
                Assert.AreEqual("Ok", response.Result);
                file = Node.Load <File>(file.Id);
                Assert.AreEqual(Identifiers.AdministratorUserId, file.LockedById);
            });
        }
Esempio n. 6
0
        public static void InitializeRepositoryInstance(TestContext context)
        {
            Cache.Reset();
            ContentTypeManager.Reset();
            var portalContextAcc = new PrivateType(typeof(PortalContext));

            portalContextAcc.SetStaticField("_sites", new Dictionary <string, Site>());

            var builder = CreateRepositoryBuilderForTest();

            Indexing.IsOuterSearchEngineEnabled = true;

            _repository = Repository.Start(builder);

            Cache.Reset();
            ContentTypeManager.Reset();

            using (new SystemAccount())
            {
                SecurityHandler.CreateAclEditor()
                .Allow(Identifiers.PortalRootId, Identifiers.AdministratorsGroupId, false, PermissionType.BuiltInPermissionTypes)
                .Allow(Identifiers.PortalRootId, Identifiers.AdministratorUserId, false, PermissionType.BuiltInPermissionTypes)
                .Apply();
            }
        }
Esempio n. 7
0
        public override void Execute(ExecutionContext context)
        {
            context.AssertRepositoryStarted();

            CheckParameters();

            using (new SystemAccount())
            {
                var path    = (string)context.ResolveVariable(Path);
                var content = Content.Load(path);
                if (content == null)
                {
                    Logger.LogWarningMessage("Content not found: " + path);
                    return;
                }

                var identity = Node.LoadNode(Identity) as ISecurityMember;
                if (identity == null)
                {
                    Logger.LogWarningMessage("Identity not found: " + Identity);
                    return;
                }

                var aclEditor          = SecurityHandler.CreateAclEditor();
                var permissionBitMmask = new PermissionBitMask
                {
                    AllowBits = SecurityHandler.GetPermissionMask(GetPermissionTypes(Allow)),
                    DenyBits  = SecurityHandler.GetPermissionMask(GetPermissionTypes(Deny))
                };

                ChangePermissions(content.Id, identity.Id, aclEditor, permissionBitMmask);

                aclEditor.Apply();
            }
        }
Esempio n. 8
0
        private void InitialDataTestPrivate(Action callback, bool withSecurity)
        {
            Cache.Reset();
            ContentTypeManager.Reset();
            Providers.Instance.ResetBlobProviders();

            var builder = CreateRepositoryBuilderForTest();

            Indexing.IsOuterSearchEngineEnabled = true;

            Cache.Reset();
            ContentTypeManager.Reset();

            using (Repository.Start(builder))
            {
                using (new SystemAccount())
                {
                    if (withSecurity)
                    {
                        var sdbp = new PrivateType(typeof(MemoryDataProvider));
                        var db   = (DatabaseStorage)sdbp.GetStaticFieldOrProperty("Storage");
                        db.Aces.Clear();

                        SecurityHandler.CreateAclEditor()
                        .Allow(Identifiers.PortalRootId, Identifiers.AdministratorsGroupId, false,
                               PermissionType.BuiltInPermissionTypes)
                        .Allow(Identifiers.PortalRootId, Identifiers.AdministratorUserId, false,
                               PermissionType.BuiltInPermissionTypes)
                        .Apply();
                    }

                    callback();
                }
            }
        }
Esempio n. 9
0
        public void NodeMove_2_SourceIsLockedByAnother()
        {
            MoveTest(testRoot =>
            {
                SecurityHandler.SecurityContext.CreateAclEditor()
                .Allow(Identifiers.PortalRootId, Identifiers.AdministratorUserId, false, PermissionType.PermissionTypes)
                .Allow(Identifiers.VisitorUserId, Identifiers.VisitorUserId, false, PermissionType.PermissionTypes)
                .Allow(testRoot.Id, Identifiers.VisitorUserId, false, PermissionType.PermissionTypes)
                .Apply();

                IUser originalUser = AccessProvider.Current.GetCurrentUser();
                IUser visitor      = Node.LoadNode(Identifiers.VisitorUserId) as IUser;
                SecurityHandler.CreateAclEditor().Allow(testRoot.Id, visitor.Id, false, PermissionType.Save, PermissionType.Delete).Apply();

                EnsureNode(testRoot, "Source/N1");
                EnsureNode(testRoot, "Source/N2");
                EnsureNode(testRoot, "Target");
                var lockedNode = (GenericContent)LoadNode(testRoot, "Source");

                AccessProvider.Current.SetCurrentUser(visitor);
                try
                {
                    lockedNode.CheckOut();
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);
                }

                AccessProvider.Current.SetCurrentUser(User.Administrator);
                bool expectedExceptionWasThrown = false;
                Exception thrownException       = null;
                try
                {
                    MoveNode("Source", "Target", testRoot);
                }
                catch (Exception e)
                {
                    if (e is LockedNodeException || e.InnerException is LockedNodeException)
                    {
                        expectedExceptionWasThrown = true;
                    }
                    else
                    {
                        thrownException = e;
                    }
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);
                }

                lockedNode.Reload();
                AccessProvider.Current.SetCurrentUser(visitor);
                lockedNode.UndoCheckOut();
                AccessProvider.Current.SetCurrentUser(originalUser);

                Assert.IsTrue(expectedExceptionWasThrown, "The expected exception was not thrown.");
            });
        }
Esempio n. 10
0
        public void NodeMove_2_MinimalPermissions()
        {
            MoveTest(testRoot =>
            {
                IUser visitor = Node.LoadNode(RepositoryConfiguration.VisitorUserId) as IUser;
                EnsureNode(testRoot, "Source");
                EnsureNode(testRoot, "TargetFolder");
                Node sourceNode = LoadNode(testRoot, "Source");
                Node targetNode = LoadNode(testRoot, "TargetFolder");
                SecurityHandler.CreateAclEditor()
                .Allow(sourceNode.Id, visitor.Id, false, PermissionType.OpenMinor, PermissionType.Delete)
                .Allow(targetNode.Id, visitor.Id, false, PermissionType.AddNew)
                .Apply();

                IUser originalUser = AccessProvider.Current.GetCurrentUser();
                try
                {
                    AccessProvider.Current.SetCurrentUser(visitor);
                    MoveNode("Source", "TargetFolder", testRoot);
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);
                }
            });
        }
Esempio n. 11
0
        private void InitialDataTestPrivate(Action callback, bool withSecurity)
        {
            Cache.Reset();
            ContentTypeManager.Reset();

            var builder = CreateRepositoryBuilderForTest();

            Indexing.IsOuterSearchEngineEnabled = true;

            Cache.Reset();
            ContentTypeManager.Reset();

            using (Repository.Start(builder))
            {
                using (new SystemAccount())
                {
                    if (withSecurity)
                    {
                        SecurityHandler.CreateAclEditor()
                        .Allow(Identifiers.PortalRootId, Identifiers.AdministratorsGroupId, false,
                               PermissionType.BuiltInPermissionTypes)
                        .Allow(Identifiers.PortalRootId, Identifiers.AdministratorUserId, false,
                               PermissionType.BuiltInPermissionTypes)
                        .Apply();
                    }

                    new SnMaintenance().Shutdown();

                    callback();
                }
            }
        }
Esempio n. 12
0
        public void Node_Reference_SetReference_Simple_Invisible()
        {
            Test(() =>
            {
                var root    = CreateTestRoot();
                var u1      = CreateUser("U1");
                var target0 = new Folder(root)
                {
                    Name = "folder1"
                };
                target0.Save();
                var target1 = new Folder(root)
                {
                    Name = "folder2"
                };
                target1.Save();
                var link = new ContentLink(root)
                {
                    Name = "Link1", Link = target0
                };
                link.Save();

                SecurityHandler.CreateAclEditor()
                .Allow(target1.Id, u1.Id, false, PermissionType.See)
                .Allow(link.Id, u1.Id, false, PermissionType.Save)
                .Apply();

                Assert.IsFalse(target0.Security.HasPermission(u1, PermissionType.See));
                Assert.IsTrue(target1.Security.HasPermission(u1, PermissionType.See));
                Assert.IsTrue(link.Security.HasPermission(u1, PermissionType.Save));

                // ACTION
                using (new CurrentUserBlock(u1))
                {
                    var loadedLink = Node.Load <ContentLink>(link.Id);

                    // Restrictive user cannot access the current target.
                    //Assert.IsNull(loadedLink.Link);
                    try
                    {
                        var currentLint = loadedLink.Link;
                        Assert.Fail("The expected AccessDeniedException was not thrown.");
                    }
                    catch (SenseNetSecurityException)
                    {
                        // expected exception
                    }

                    // Set new target
                    var loadedTarget = Node.LoadNode(target1.Id);
                    loadedLink.Link  = loadedTarget;
                    loadedLink.Save();
                }

                // ASSERT
                var reloaded = Node.Load <ContentLink>(link.Id);
                Assert.AreEqual(reloaded.Link.Id, target1.Id);
            });
        }
Esempio n. 13
0
        public static object SetPermissions(Content content, SetPermissionsRequest r)
        {
            var request = r;
            var editor  = SecurityHandler.CreateAclEditor();

            SetPermissions(content, request, editor);
            editor.Apply();
            return(null);
        }
Esempio n. 14
0
        public void SetPermission(IUser user, PermissionType permissionType, PermissionValue permissionValue)
        {
            var node = Node.LoadNode(Path);

            if (node != null)
            {
                SecurityHandler.CreateAclEditor().SetPermission(node.Id, user.Id, false, permissionType, permissionValue).Apply();
            }
        }
Esempio n. 15
0
            public AllowPermissionBlock(int entityId, int identityId, bool localOnly, params PermissionType[] permissions)
            {
                _entityId    = entityId;
                _identityId  = identityId;
                _localOnly   = localOnly;
                _permissions = permissions;

                SecurityHandler.CreateAclEditor()
                .Allow(entityId, identityId, localOnly, permissions)
                .Apply();
            }
Esempio n. 16
0
        /* ================================================== Helper methods */

        private void AddRootAccessibilityToAdmin()
        {
            using (new SystemAccount())
            {
                SecurityHandler.CreateAclEditor()
                // ReSharper disable once CoVariantArrayConversion
                .Allow(Identifiers.PortalRootId, User.Administrator.Id, false, PermissionType.PermissionTypes)
                .Apply();
                User.Administrator.CreationDate = new DateTime(2001, 01, 01);
            }
        }
Esempio n. 17
0
        public void User_sensenet393_BugReproduction()
        {
            Test(true, () =>
            {
                Providers.Instance.CacheProvider = new SnMemoryCache();

                Group group;
                User user;
                using (new SystemAccount())
                {
                    var ed = SecurityHandler.CreateAclEditor();
                    ed.Set(Repository.Root.Id, User.Administrator.Id, false, PermissionBitMask.AllAllowed);
                    ed.Set(Repository.Root.Id, Group.Administrators.Id, false, PermissionBitMask.AllAllowed);
                    ed.Apply();

                    var portal = Node.LoadNode("/Root/IMS/BuiltIn/Portal");

                    group = new Group(portal)
                    {
                        Name = "TestGroup"
                    };
                    group.Save();

                    user = new User(portal)
                    {
                        Name        = "TestUser",
                        Enabled     = true,
                        Email       = "*****@*****.**",
                        DisplayName = "User_sensenet393_BugReproduction"
                    };
                    user.Save();

                    Group.Administrators.AddMember(user);
                    User.Current = user;
                }

                Providers.Instance.MembershipExtender = new TestMembershipExtender();

                var simulatedOutput        = new StringWriter();
                var simulatedWorkerRequest = new SimulatedHttpRequest(@"\", @"C:\Inetpub\wwwroot", user.Path, "",
                                                                      simulatedOutput, "localhost_forms");
                var simulatedHttpContext = new HttpContext(simulatedWorkerRequest);
                var portalContext        = PortalContext.Create(simulatedHttpContext);
                HttpContext.Current      = simulatedHttpContext;

                // This line caused StackOverflowException
                var additionalGroups = user.GetDynamicGroups(2);

                // The bug is fixed if the code can run up to this point
                // but we test the full feature.
                Assert.AreEqual(group.Id, additionalGroups.First());
            });
        }
Esempio n. 18
0
        [TestMethod, TestCategory("NODE, REFERENCE, FIX")] //Fix1291_SetMembersDoNotRemovesHiddenItems
        public void Node_Reference_SetReference_Multiple_Invisible()
        {
            Test(() =>
            {
                var root  = CreateTestRoot();
                var u1    = CreateUser("U1");
                var u2    = CreateUser("U2");
                var u3    = CreateUser("U3");
                var u4    = CreateUser("U4");
                var group = new Group(Node.LoadNode("/Root/IMS/Public"))
                {
                    Name    = "Group1",
                    Members = new[] { u2, u3 }
                };
                group.Save();

                SecurityHandler.CreateAclEditor()
                .Allow(u3.Id, u1.Id, false, PermissionType.See)
                .Allow(u4.Id, u1.Id, false, PermissionType.See)
                .Allow(group.Id, u1.Id, false, PermissionType.Save)
                .Apply();

                Assert.IsFalse(u2.Security.HasPermission(u1, PermissionType.See));
                Assert.IsTrue(u3.Security.HasPermission(u1, PermissionType.See));
                Assert.IsTrue(u4.Security.HasPermission(u1, PermissionType.See));
                Assert.IsTrue(group.Security.HasPermission(u1, PermissionType.Save));

                // ACTION
                using (new CurrentUserBlock(u1))
                {
                    var loadedGroup = Node.Load <Group>(group.Id);

                    // Restrictive user does not see the user "U2".
                    var loadedGroupMembers = loadedGroup.Members.ToArray();
                    Assert.AreEqual(1, loadedGroupMembers.Length);
                    Assert.AreEqual(u3.Id, loadedGroupMembers[0].Id);

                    // Set new membership
                    var loadedUser      = Node.Load <User>(u4.Id);
                    loadedGroup.Members = new[] { u4 };
                    loadedGroup.Save();
                }

                // ASSERT
                var reloaded = Node.Load <Group>(group.Id);
                var actual   = string.Join(", ", reloaded.Members.Select(x => x.Name));
                Assert.AreEqual("U2, U4", actual);
            });
        }
Esempio n. 19
0
        public void InitialData_FW_Permissions_Apply()
        {
            var initialData = new InitialData
            {
                Permissions = new List <string>
                {
                    "+6|Normal|-6:_______________________________________________________________+",
                    "-1000|Normal|+6:_______________________________________________________________+",
                }
            };

            InitialSecurityDataTest(() =>
            {
                var mask = PermissionType.GetPermissionMask(PermissionType.BuiltInPermissionTypes);
                SecurityHandler.CreateAclEditor()
                .RemoveExplicitEntries(2)
                .RemoveExplicitEntries(6)
                .RemoveExplicitEntries(1000)
                .Set(2, 7, false, mask, 0UL)
                .Apply();

                // PRECHECKS
                // Administrators group has 1 entry on the Root.
                Assert.AreEqual(1, SecurityHandler.GetExplicitEntries(2, new[] { 7 }).Count);
                // Visitor has no any permission.
                Assert.IsFalse(SecurityHandler.HasPermission(User.Visitor, 6, PermissionType.See));
                Assert.IsFalse(SecurityHandler.HasPermission(User.Visitor, 1000, PermissionType.See));
                // There is no break.
                Assert.IsTrue(SecurityHandler.IsEntityInherited(6));
                Assert.IsTrue(SecurityHandler.IsEntityInherited(1000));

                // ACTION
                SecurityHandler.SecurityInstaller.InstallDefaultSecurityStructure(initialData);

                // ASSERT
                // Administrators group has an entry on the Root.
                Assert.AreEqual(1, SecurityHandler.GetExplicitEntries(2, new[] { 7 }).Count);
                // Visitor has See permission on both contents.
                Assert.IsTrue(SecurityHandler.HasPermission(User.Visitor, 6, PermissionType.See));
                Assert.IsTrue(SecurityHandler.HasPermission(User.Visitor, 1000, PermissionType.See));
                // The second content is not inherited.
                Assert.IsTrue(SecurityHandler.IsEntityInherited(6));
                Assert.IsFalse(SecurityHandler.IsEntityInherited(1000));
            });
        }
        public async Task OD_FIX_ModifyWithInvisibleParent()
        {
            await IsolatedODataTestAsync(
                builder => { builder.AddAllTestPolicies(); },
                async() =>
            {
                var testRoot = CreateTestRoot("ODataTestRoot");
                var root     = new Folder(testRoot)
                {
                    Name = Guid.NewGuid().ToString()
                };
                root.Save();
                var node = new Folder(root)
                {
                    Name = Guid.NewGuid().ToString()
                };
                node.Save();

                SecurityHandler.CreateAclEditor()
                .BreakInheritance(root.Id, new[] { EntryType.Normal })
                .ClearPermission(root.Id, User.Visitor.Id, false, PermissionType.See)
                .Allow(node.Id, User.Visitor.Id, false, PermissionType.Save)
                .Apply();

                var savedUser = User.Current;

                try
                {
                    User.Current = User.Visitor;

                    var json     = @"models=[{""Index"": 42}]";
                    var response = await ODataPatchAsync("/OData.svc" + node.Path, "", json).ConfigureAwait(false);;

                    AssertNoError(response);
                    var entity = GetEntity(response);
                    node       = Node.Load <Folder>(node.Id);
                    Assert.AreEqual(42, entity.Index);
                    Assert.AreEqual(42, node.Index);
                }
                finally
                {
                    User.Current = savedUser;
                }
            }).ConfigureAwait(false);;
        }
Esempio n. 21
0
        public override object Execute(Content content, params object[] parameters)
        {
            var request = (SetPermissionsRequest)parameters[0];

            var editor = SecurityHandler.CreateAclEditor();

            if (request.inheritance != null)
            {
                SetInheritance(content, request, editor);
            }
            else
            {
                SetPermissions(content, request, editor);
            }
            editor.Apply();

            return(null);
        }
Esempio n. 22
0
        public void Delete_Trash_WithoutDeletePermission()
        {
            Test(true, () =>
            {
                var originalUser = AccessProvider.Current.GetCurrentUser();

                File file;
                using (new SystemAccount())
                {
                    file = CreateTestFile();

                    // give Visitor only Open permission, not Delete
                    // (workaround: add permissions for Visitor to the user content and to the Trash to make this test work)
                    SecurityHandler.CreateAclEditor()
                    .Allow(file.Id, Identifiers.VisitorUserId, false, PermissionType.OpenMinor)
                    .Allow(TrashBin.Instance.Id, Identifiers.VisitorUserId, false, PermissionType.Open)
                    .Allow(Identifiers.VisitorUserId, Identifiers.VisitorUserId, false, PermissionType.Open)
                    .Apply();
                }

                var thrown = false;

                try
                {
                    AccessProvider.Current.SetCurrentUser(User.Visitor);

                    // action: try to trash the file as Visitor
                    TrashBin.DeleteNode(file);
                }
                catch (InvalidOperationException ex)
                {
                    if (ex.Message.Contains("You do not have enough permissions to delete this content"))
                    {
                        thrown = true;
                    }
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);
                }

                Assert.IsTrue(thrown, "The expected exception was not thrown.");
            });
        }
Esempio n. 23
0
        public static void InitializeRepositoryInstance(TestContext context)
        {
            DistributedApplication.Cache.Reset();
            ContentTypeManager.Reset();

            var builder = CreateRepositoryBuilderForTest();

            Indexing.IsOuterSearchEngineEnabled = true;

            _repository = Repository.Start(builder);

            using (new SystemAccount())
            {
                SecurityHandler.CreateAclEditor()
                .Allow(Identifiers.PortalRootId, Identifiers.AdministratorsGroupId, false, PermissionType.BuiltInPermissionTypes)
                .Allow(Identifiers.PortalRootId, Identifiers.AdministratorUserId, false, PermissionType.BuiltInPermissionTypes)
                .Apply();
            }
        }
Esempio n. 24
0
        public override void Execute(ExecutionContext context)
        {
            context.AssertRepositoryStarted();

            if (string.IsNullOrEmpty(Path))
            {
                throw new PackagingException(SR.Errors.InvalidParameters);
            }

            using (new SystemAccount())
            {
                var path      = (string)context.ResolveVariable(Path);
                var content   = Content.Load(path);
                var aclEditor = SecurityHandler.CreateAclEditor();
                if (content == null)
                {
                    Logger.LogWarningMessage("Content not found: " + path);
                    return;
                }

                if (string.IsNullOrEmpty(Identity))
                {
                    aclEditor.RemoveExplicitEntries(content.Id);
                }
                else
                {
                    var identity = Node.LoadNode(Identity) as ISecurityMember;
                    if (identity == null)
                    {
                        Logger.LogWarningMessage("Identity not found: " + Identity);
                        return;
                    }
                    var pbitmask = PermissionBitMask.All;
                    aclEditor.Reset(content.Id, identity.Id, false, pbitmask);
                    aclEditor.Reset(content.Id, identity.Id, true, pbitmask);
                }
                aclEditor.Apply();
            }
        }
Esempio n. 25
0
        public static object SetPermissions(Content content, string inheritance)
        {
            var editor = SecurityHandler.CreateAclEditor();

            switch (inheritance.ToLower())
            {
            default:
                throw new ArgumentException("The value of the 'inheritance' must be 'break' or 'unbreak'.");

            case "break":
                editor.BreakInheritance(content.Id, new[] { EntryType.Normal });
                break;

            case "unbreak":
                editor.UnbreakInheritance(content.Id, new[] { EntryType.Normal });
                break;
            }

            editor.Apply();

            return(null);
        }
Esempio n. 26
0
        public static string CopyExplicitEntriesOfEveryoneToVisitor(Content root, string[] exceptList)
        {
            var visitorId  = User.Visitor.Id;
            var everyoneId = Group.Everyone.Id;
            var except     = exceptList.Select(p => p.ToLower()).ToList();
            var ctx        = SecurityHandler.SecurityContext;
            var aclEd      = SecurityHandler.CreateAclEditor(ctx);

            foreach (var path in MissingExplicitEntriesOfVisitorComparedToEveryone(root))
            {
                if (!except.Contains(path.ToLower()))
                {
                    var node = Node.LoadNode(path);
                    var aces = ctx.GetExplicitEntries(node.Id, new[] { everyoneId });
                    foreach (var ace in aces)
                    {
                        aclEd.Set(node.Id, visitorId, ace.LocalOnly, ace.AllowBits, ace.DenyBits);
                    }
                }
            }
            aclEd.Apply();
            return("Ok");
        }
Esempio n. 27
0
        private static void SetPermissions(Content content, PermissionModel permissions, List <string> messages, out bool hasUnkownIdentity)
        {
            hasUnkownIdentity = false;
            if (permissions == null)
            {
                return;
            }

            var controller = content.ContentHandler.Security;
            var aclEditor  = SecurityHandler.CreateAclEditor();

            if (controller.IsInherited != permissions.IsInherited)
            {
                if (permissions.IsInherited)
                {
                    aclEditor.UnbreakInheritance(content.Id, new[] { EntryType.Normal });
                }
                else
                {
                    aclEditor.BreakInheritance(content.Id, new[] { EntryType.Normal });
                }
            }

            foreach (var entryModel in permissions.Entries)
            {
                var identity = Node.LoadNode(entryModel.Identity);
                if (identity == null)
                {
                    hasUnkownIdentity = true;
                    //messages.Add($"Unknown identity: {entryModel.Identity}");
                    continue;
                }

                SetPermissions(aclEditor, content.Id, identity.Id, entryModel.LocalOnly, entryModel.Permissions, messages);
            }
            aclEditor.Apply();
        }
        public async Task OD_Security_HasPermission_Administrator()
        {
            await IsolatedODataTestAsync(async() =>
            {
                SecurityHandler.CreateAclEditor()
                .Allow(Repository.Root.Id, Group.Administrators.Id, false, PermissionType.Open)
                .Allow(Repository.Root.Id, Group.Administrators.Id, false, PermissionType.Save)
                .Apply();

                var hasPermission = SecurityHandler.HasPermission(
                    User.Administrator, Group.Administrators, PermissionType.Open, PermissionType.Save);
                Assert.IsTrue(hasPermission);

                // ACTION
                var response = await ODataPostAsync(
                    "/OData.svc/Root/IMS/BuiltIn/Portal('Administrators')/HasPermission",
                    "",
                    $"{{user:\"{User.Administrator.Path}\", permissions:[\"Open\",\"Save\"] }}")
                               .ConfigureAwait(false);

                // ASSERT
                Assert.AreEqual("true", response.Result);
            }).ConfigureAwait(false);
        }
Esempio n. 29
0
 public void Dispose()
 {
     SecurityHandler.CreateAclEditor()
     .ClearPermission(_entityId, _identityId, _localOnly, _permissions)
     .Apply();
 }
Esempio n. 30
0
        /// <summary>
        /// Returns a new <see cref="TrashBag"/> instance that packages the
        /// given <see cref="GenericContent"/> instance.
        /// </summary>
        /// <param name="node">The <see cref="GenericContent"/> instance that will be wrapped.</param>
        public static TrashBag BagThis(GenericContent node)
        {
            var bin = TrashBin.Instance;

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

            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            // creating a bag has nothing to do with user permissions: Move will handle that
            TrashBag bag            = null;
            var      wsId           = 0;
            var      wsRelativePath = string.Empty;
            var      ws             = SystemAccount.Execute(() => node.Workspace);

            if (ws != null)
            {
                wsId           = ws.Id;
                wsRelativePath = node.Path.Substring(ws.Path.Length);
            }

            using (new SystemAccount())
            {
                bag = new TrashBag(bin)
                {
                    KeepUntil             = DateTime.UtcNow.AddDays(bin.MinRetentionTime),
                    OriginalPath          = RepositoryPath.GetParentPath(node.Path),
                    WorkspaceRelativePath = wsRelativePath,
                    WorkspaceId           = wsId,
                    DisplayName           = node.DisplayName,
                    Link  = node,
                    Owner = node.Owner
                };
                bag.Save();

                CopyPermissions(node, bag);

                // add delete permission for the owner
                SecurityHandler.CreateAclEditor()
                .Allow(bag.Id, node.OwnerId, false, PermissionType.Delete)
                .Apply();
            }

            try
            {
                Node.Move(node.Path, bag.Path);
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex);

                bag.Destroy();

                throw new InvalidOperationException("Error moving item to the trash", ex);
            }

            return(bag);
        }