public ActionResult <PublicAccess> GetPublicAccess(int contentId)
        {
            IContent content = _contentService.GetById(contentId);

            if (content == null)
            {
                return(NotFound());
            }

            PublicAccessEntry entry = _publicAccessService.GetEntryForContent(content);

            if (entry == null || entry.ProtectedNodeId != content.Id)
            {
                return(Ok());
            }

            var nodes = _entityService
                        .GetAll(UmbracoObjectTypes.Document, entry.LoginNodeId, entry.NoAccessNodeId)
                        .ToDictionary(x => x.Id);

            if (!nodes.TryGetValue(entry.LoginNodeId, out IEntitySlim loginPageEntity))
            {
                throw new InvalidOperationException($"Login node with id ${entry.LoginNodeId} was not found");
            }

            if (!nodes.TryGetValue(entry.NoAccessNodeId, out IEntitySlim errorPageEntity))
            {
                throw new InvalidOperationException($"Error node with id ${entry.LoginNodeId} was not found");
            }

            // unwrap the current public access setup for the client
            // - this API method is the single point of entry for both "modes" of public access (single user and role based)
            var usernames = entry.Rules
                            .Where(rule => rule.RuleType == Constants.Conventions.PublicAccess.MemberUsernameRuleType)
                            .Select(rule => rule.RuleValue)
                            .ToArray();

            MemberDisplay[] members = usernames
                                      .Select(username => _memberService.GetByUsername(username))
                                      .Where(member => member != null)
                                      .Select(_umbracoMapper.Map <MemberDisplay>)
                                      .ToArray();

            var allGroups = _memberRoleManager.Roles.ToDictionary(x => x.Name);

            MemberGroupDisplay[] groups = entry.Rules
                                          .Where(rule => rule.RuleType == Constants.Conventions.PublicAccess.MemberRoleRuleType)
                                          .Select(rule => allGroups.TryGetValue(rule.RuleValue, out UmbracoIdentityRole memberRole) ? memberRole : null)
                                          .Where(x => x != null)
                                          .Select(_umbracoMapper.Map <MemberGroupDisplay>)
                                          .ToArray();

            return(new PublicAccess
            {
                Members = members,
                Groups = groups,
                LoginPage = loginPageEntity != null?_umbracoMapper.Map <EntityBasic>(loginPageEntity) : null,
                                ErrorPage = errorPageEntity != null?_umbracoMapper.Map <EntityBasic>(errorPageEntity) : null
            });
        }
        public void Can_Add_New_Entry()
        {
            // Arrange
            PublicAccessRule[] rules = new[]
            {
                new PublicAccessRule()
                {
                    RuleType  = "TestType",
                    RuleValue = "TestVal"
                },
            };
            var entry = new PublicAccessEntry(_content, _content, _content, rules);

            // Act
            Attempt <OperationResult> result = PublicAccessService.Save(entry);

            // Assert
            Assert.IsTrue(result.Success);
            Assert.AreEqual(OperationResultType.Success, result.Result.Result);
            Assert.IsTrue(entry.HasIdentity);
            Assert.AreNotEqual(entry.Key, Guid.Empty);
            Assert.AreEqual(_content.Id, entry.LoginNodeId);
            Assert.AreEqual(_content.Id, entry.NoAccessNodeId);
            Assert.AreEqual(_content.Id, entry.ProtectedNodeId);
        }
示例#3
0
        public void Can_Add_Rule()
        {
            // Arrange
            var contentService     = ServiceContext.ContentService;
            var contentTypeService = ServiceContext.ContentTypeService;
            var ct = MockedContentTypes.CreateSimpleContentType("blah", "Blah");

            ServiceContext.FileService.SaveTemplate(ct.DefaultTemplate);
            contentTypeService.Save(ct);
            var c = MockedContent.CreateSimpleContent(ct, "Test", -1);

            contentService.Save(c);
            var publicAccessService = ServiceContext.PublicAccessService;
            var entry = new PublicAccessEntry(c, c, c, new[]
            {
                new PublicAccessRule()
                {
                    RuleType  = "TestType",
                    RuleValue = "TestVal"
                },
            });

            publicAccessService.Save(entry);

            // Act
            var updated = publicAccessService.AddRule(c, "TestType2", "AnotherVal");

            //re-get
            entry = publicAccessService.GetEntryForContent(c);

            // Assert
            Assert.IsTrue(updated.Success);
            Assert.AreEqual(OperationResultType.Success, updated.Result.Result);
            Assert.AreEqual(2, entry.Rules.Count());
        }
示例#4
0
        public void Get_All_With_Id()
        {
            var content = CreateTestData(3).ToArray();

            var provider   = new PetaPocoUnitOfWorkProvider(Logger);
            var unitOfWork = provider.GetUnitOfWork();

            using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
            {
                var entry1 = new PublicAccessEntry(content[0], content[1], content[2], new[]
                {
                    new PublicAccessRule
                    {
                        RuleValue = "test",
                        RuleType  = "RoleName"
                    },
                });
                repo.AddOrUpdate(entry1);

                var entry2 = new PublicAccessEntry(content[1], content[0], content[2], new[]
                {
                    new PublicAccessRule
                    {
                        RuleValue = "test",
                        RuleType  = "RoleName"
                    },
                });
                repo.AddOrUpdate(entry2);

                unitOfWork.Commit();

                var found = repo.GetAll(entry1.Key).ToArray();
                Assert.AreEqual(1, found.Count());
            }
        }
示例#5
0
    public void Can_Update()
    {
        var content = CreateTestData(3).ToArray();

        var provider = ScopeProvider;

        using (var scope = provider.CreateScope())
        {
            var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger <PublicAccessRepository>());

            PublicAccessRule[] rules = { new PublicAccessRule {
                                             RuleValue = "test", RuleType = "RoleName"
                                         } };
            var entry = new PublicAccessEntry(content[0], content[1], content[2], rules);
            repo.Save(entry);

            // re-get
            entry = repo.Get(entry.Key);

            entry.Rules.First().RuleValue = "blah";
            entry.Rules.First().RuleType  = "asdf";
            repo.Save(entry);

            // re-get
            entry = repo.Get(entry.Key);

            Assert.AreEqual("blah", entry.Rules.First().RuleValue);
            Assert.AreEqual("asdf", entry.Rules.First().RuleType);
        }
    }
示例#6
0
    public void Get_All_With_Id()
    {
        var content = CreateTestData(3).ToArray();

        var provider = ScopeProvider;

        using (var scope = provider.CreateScope())
        {
            var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger <PublicAccessRepository>());

            PublicAccessRule[] rules1 = { new PublicAccessRule {
                                              RuleValue = "test", RuleType = "RoleName"
                                          } };
            var entry1 = new PublicAccessEntry(content[0], content[1], content[2], rules1);
            repo.Save(entry1);

            PublicAccessRule[] rules2 = { new PublicAccessRule {
                                              RuleValue = "test", RuleType = "RoleName"
                                          } };
            var entry2 = new PublicAccessEntry(content[1], content[0], content[2], rules2);
            repo.Save(entry2);

            var found = repo.GetMany(entry1.Key).ToArray();
            Assert.AreEqual(1, found.Count());
        }
    }
        public void Can_Add_Rule()
        {
            // Arrange
            PublicAccessRule[] rules = new[]
            {
                new PublicAccessRule()
                {
                    RuleType  = "TestType",
                    RuleValue = "TestVal"
                },
            };
            var entry = new PublicAccessEntry(_content, _content, _content, rules);

            PublicAccessService.Save(entry);

            // Act
            Attempt <OperationResult <OperationResultType, PublicAccessEntry> > updated = PublicAccessService.AddRule(_content, "TestType2", "AnotherVal");

            // re-get
            entry = PublicAccessService.GetEntryForContent(_content);

            // Assert
            Assert.IsTrue(updated.Success);
            Assert.AreEqual(OperationResultType.Success, updated.Result.Result);
            Assert.AreEqual(2, entry.Rules.Count());
        }
示例#8
0
        public void Can_Add_New_Entry()
        {
            // Arrange
            var contentService     = ServiceContext.ContentService;
            var contentTypeService = ServiceContext.ContentTypeService;
            var ct = MockedContentTypes.CreateSimpleContentType("blah", "Blah");

            ServiceContext.FileService.SaveTemplate(ct.DefaultTemplate);
            contentTypeService.Save(ct);
            var c = MockedContent.CreateSimpleContent(ct, "Test", -1);

            contentService.Save(c);
            var publicAccessService = ServiceContext.PublicAccessService;


            // Act
            var entry = new PublicAccessEntry(c, c, c, new[]
            {
                new PublicAccessRule()
                {
                    RuleType  = "TestType",
                    RuleValue = "TestVal"
                },
            });
            var result = publicAccessService.Save(entry);

            // Assert
            Assert.IsTrue(result.Success);
            Assert.AreEqual(OperationResultType.Success, result.Result.Result);
            Assert.IsTrue(entry.HasIdentity);
            Assert.AreNotEqual(entry.Key, Guid.Empty);
            Assert.AreEqual(c.Id, entry.LoginNodeId);
            Assert.AreEqual(c.Id, entry.NoAccessNodeId);
            Assert.AreEqual(c.Id, entry.ProtectedNodeId);
        }
示例#9
0
        public void Can_Delete()
        {
            var content = CreateTestData(3).ToArray();

            var provider   = new PetaPocoUnitOfWorkProvider(Logger);
            var unitOfWork = provider.GetUnitOfWork();

            using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
            {
                var entry = new PublicAccessEntry(content[0], content[1], content[2], new[]
                {
                    new PublicAccessRule
                    {
                        RuleValue = "test",
                        RuleType  = "RoleName"
                    },
                });
                repo.AddOrUpdate(entry);
                unitOfWork.Commit();

                repo.Delete(entry);
                unitOfWork.Commit();

                entry = repo.Get(entry.Key);
                Assert.IsNull(entry);
            }
        }
示例#10
0
        public void Can_Delete()
        {
            IContent[] content = CreateTestData(3).ToArray();

            IScopeProvider provider = ScopeProvider;

            using (IScope scope = provider.CreateScope())
            {
                var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger <PublicAccessRepository>());

                PublicAccessRule[] rules = new[]
                {
                    new PublicAccessRule
                    {
                        RuleValue = "test",
                        RuleType  = "RoleName"
                    },
                };
                var entry = new PublicAccessEntry(content[0], content[1], content[2], rules);
                repo.Save(entry);

                repo.Delete(entry);

                entry = repo.Get(entry.Key);
                Assert.IsNull(entry);
            }
        }
示例#11
0
    public void Can_Add()
    {
        var content = CreateTestData(3).ToArray();

        var provider = ScopeProvider;

        using (var scope = provider.CreateScope())
        {
            ScopeAccessor.AmbientScope.Database.AsUmbracoDatabase().EnableSqlTrace = true;
            var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger <PublicAccessRepository>());

            PublicAccessRule[] rules = { new PublicAccessRule {
                                             RuleValue = "test", RuleType = "RoleName"
                                         } };
            var entry = new PublicAccessEntry(content[0], content[1], content[2], rules);
            repo.Save(entry);

            var found = repo.GetMany().ToArray();

            Assert.AreEqual(1, found.Length);
            Assert.AreEqual(content[0].Id, found[0].ProtectedNodeId);
            Assert.AreEqual(content[1].Id, found[0].LoginNodeId);
            Assert.AreEqual(content[2].Id, found[0].NoAccessNodeId);
            Assert.IsTrue(found[0].HasIdentity);
            Assert.AreNotEqual(default(DateTime), found[0].CreateDate);
            Assert.AreNotEqual(default(DateTime), found[0].UpdateDate);
            Assert.AreEqual(1, found[0].Rules.Count());
            Assert.AreEqual("test", found[0].Rules.First().RuleValue);
            Assert.AreEqual("RoleName", found[0].Rules.First().RuleType);
            Assert.AreNotEqual(default(DateTime), found[0].Rules.First().CreateDate);
            Assert.AreNotEqual(default(DateTime), found[0].Rules.First().UpdateDate);
            Assert.IsTrue(found[0].Rules.First().HasIdentity);
        }
    }
示例#12
0
        private static void SetPublicAccessToHomePage()
        {
            var umbracoHelper  = new UmbracoHelper(UmbracoContext.Current);
            var contentService = AirFlowServiceContainer.Instance.GetInstance <IContentService>();

            IContent GetNodeByAlias(string alias)
            {
                IPublishedContent homeContent = umbracoHelper.TypedContentSingleAtXPath("//" + alias);

                return(contentService.GetById(homeContent.Id));
            }

            IContent homeNode            = GetNodeByAlias("home");
            var      publicAccessService = AirFlowServiceContainer.Instance.GetInstance <IPublicAccessService>();

            if (publicAccessService.IsProtected(homeNode))
            {
                return;
            }

            IContent loginNode = GetNodeByAlias("login");
            IContent errorNode = GetNodeByAlias("error");

            var entry = new PublicAccessEntry(homeNode, loginNode, errorNode, new List <PublicAccessRule>());

            publicAccessService.Save(entry);
            publicAccessService.AddRule(homeNode, Constants.Conventions.PublicAccess.MemberRoleRuleType, UserRoleType.Regular.ToString());
        }
    public void Can_Remove_Rule()
    {
        // Arrange
        PublicAccessRule[] rules =
        {
            new PublicAccessRule {
                RuleType = "TestType", RuleValue = "TestValue1"
            },
            new PublicAccessRule {
                RuleType = "TestType", RuleValue = "TestValue2"
            }
        };
        var entry = new PublicAccessEntry(_content, _content, _content, rules);

        PublicAccessService.Save(entry);

        // Act
        var removed = PublicAccessService.RemoveRule(_content, "TestType", "TestValue1");

        // re-get
        entry = PublicAccessService.GetEntryForContent(_content);

        // Assert
        Assert.IsTrue(removed.Success);
        Assert.AreEqual(OperationResultType.Success, removed.Result.Result);
        Assert.AreEqual(1, entry.Rules.Count());
        Assert.AreEqual("TestValue2", entry.Rules.ElementAt(0).RuleValue);
    }
示例#14
0
        public void Get_All()
        {
            var content = CreateTestData(30).ToArray();

            var provider   = new PetaPocoUnitOfWorkProvider(Logger);
            var unitOfWork = provider.GetUnitOfWork();

            using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
            {
                var allEntries = new List <PublicAccessEntry>();
                for (int i = 0; i < 10; i++)
                {
                    var rules = new List <PublicAccessRule>();
                    for (int j = 0; j < 50; j++)
                    {
                        rules.Add(new PublicAccessRule
                        {
                            RuleValue = "test" + j,
                            RuleType  = "RoleName" + j
                        });
                    }
                    var entry1 = new PublicAccessEntry(content[i], content[i + 1], content[i + 2], rules);
                    repo.AddOrUpdate(entry1);
                    unitOfWork.Commit();
                    allEntries.Add(entry1);
                }

                //now remove a few rules from a few of the items and then add some more, this will put things 'out of order' which
                //we need to verify our sort order is working for the relator
                for (int i = 0; i < allEntries.Count; i++)
                {
                    //all the even ones
                    if (i % 2 == 0)
                    {
                        var rules = allEntries[i].Rules.ToArray();
                        for (int j = 0; j < rules.Length; j++)
                        {
                            //all the even ones
                            if (j % 2 == 0)
                            {
                                allEntries[i].RemoveRule(rules[j]);
                            }
                        }
                        allEntries[i].AddRule("newrule" + i, "newrule" + i);
                        repo.AddOrUpdate(allEntries[i]);
                        unitOfWork.Commit();
                    }
                }

                var found = repo.GetAll().ToArray();
                Assert.AreEqual(10, found.Length);

                foreach (var publicAccessEntry in found)
                {
                    var matched = allEntries.First(x => x.Key == publicAccessEntry.Key);

                    Assert.AreEqual(matched.Rules.Count(), publicAccessEntry.Rules.Count());
                }
            }
        }
 private static bool HasAccess(PublicAccessEntry entry, string username, IEnumerable <string> roles)
 {
     return(entry.Rules.Any(x =>
                            (x.RuleType == Constants.Conventions.PublicAccess.MemberUsernameRuleType && username.Equals(x.RuleValue, StringComparison.OrdinalIgnoreCase)) ||
                            (x.RuleType == Constants.Conventions.PublicAccess.MemberRoleRuleType && roles.Contains(x.RuleValue))
                            ));
 }
        public void Can_Delete()
        {
            var content = CreateTestData(3).ToArray();

            var provider = TestObjects.GetScopeProvider(Logger);

            using (var scope = provider.CreateScope())
            {
                var repo = new PublicAccessRepository((IScopeAccessor)provider, CacheHelper, Logger);

                var entry = new PublicAccessEntry(content[0], content[1], content[2], new[]
                {
                    new PublicAccessRule
                    {
                        RuleValue = "test",
                        RuleType  = "RoleName"
                    },
                });
                repo.Save(entry);


                repo.Delete(entry);


                entry = repo.Get(entry.Key);
                Assert.IsNull(entry);
            }
        }
示例#17
0
        public static void ProtectPage(bool Simple, int DocumentId, int LoginDocumentId, int ErrorDocumentId)
        {
            var doc = new Document(DocumentId);
            var e   = new AddProtectionEventArgs();

            new Access().FireBeforeAddProtection(doc, e);

            if (e.Cancel)
            {
                return;
            }

            var loginContent = ApplicationContext.Current.Services.ContentService.GetById(LoginDocumentId);

            if (loginContent == null)
            {
                throw new NullReferenceException("No content item found with id " + LoginDocumentId);
            }
            var noAccessContent = ApplicationContext.Current.Services.ContentService.GetById(ErrorDocumentId);

            if (noAccessContent == null)
            {
                throw new NullReferenceException("No content item found with id " + ErrorDocumentId);
            }

            var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(doc.ContentEntity.Id.ToString());

            if (entry != null)
            {
                if (Simple)
                {
                    // if using simple mode, make sure that all existing groups are removed
                    entry.ClearRules();
                }

                //ensure the correct ids are applied
                entry.LoginNodeId    = loginContent.Id;
                entry.NoAccessNodeId = noAccessContent.Id;
            }
            else
            {
                entry = new PublicAccessEntry(doc.ContentEntity,
                                              ApplicationContext.Current.Services.ContentService.GetById(LoginDocumentId),
                                              ApplicationContext.Current.Services.ContentService.GetById(ErrorDocumentId),
                                              new List <PublicAccessRule>());
            }

            if (ApplicationContext.Current.Services.PublicAccessService.Save(entry))
            {
                Save();
                new Access().FireAfterAddProtection(new Document(DocumentId), e);
            }
        }
        public void Can_Add2()
        {
            var content = CreateTestData(3).ToArray();

            var provider = TestObjects.GetScopeProvider(Logger);

            using (var scope = provider.CreateScope())
            {
                scope.Database.AsUmbracoDatabase().EnableSqlTrace = true;
                var repo = new PublicAccessRepository((IScopeAccessor)provider, CacheHelper, Logger);

                var entry = new PublicAccessEntry(content[0], content[1], content[2], new[]
                {
                    new PublicAccessRule
                    {
                        RuleValue = "test",
                        RuleType  = "RoleName"
                    },
                    new PublicAccessRule
                    {
                        RuleValue = "test2",
                        RuleType  = "RoleName2"
                    },
                });
                repo.Save(entry);


                var found = repo.GetMany().ToArray();

                Assert.AreEqual(1, found.Length);
                Assert.AreEqual(content[0].Id, found[0].ProtectedNodeId);
                Assert.AreEqual(content[1].Id, found[0].LoginNodeId);
                Assert.AreEqual(content[2].Id, found[0].NoAccessNodeId);
                Assert.IsTrue(found[0].HasIdentity);
                Assert.AreNotEqual(default(DateTime), found[0].CreateDate);
                Assert.AreNotEqual(default(DateTime), found[0].UpdateDate);
                Assert.AreEqual(2, found[0].Rules.Count());
                Assert.AreEqual("test", found[0].Rules.First().RuleValue);
                Assert.AreEqual("RoleName", found[0].Rules.First().RuleType);
                Assert.AreNotEqual(default(DateTime), found[0].Rules.First().CreateDate);
                Assert.AreNotEqual(default(DateTime), found[0].Rules.First().UpdateDate);
                Assert.IsTrue(found[0].Rules.First().HasIdentity);
                Assert.AreEqual("test2", found[0].Rules.Skip(1).First().RuleValue);
            }
        }
示例#19
0
        /// <summary>
        /// Deletes the entry and all associated rules
        /// </summary>
        /// <param name="entry"></param>
        public Attempt <OperationStatus> Delete(PublicAccessEntry entry)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var uow = UowProvider.GetUnitOfWork())
            {
                if (uow.Events.DispatchCancelable(Deleting, this, new DeleteEventArgs <PublicAccessEntry>(entry, evtMsgs)))
                {
                    uow.Commit();
                    return(OperationStatus.Cancelled(evtMsgs));
                }

                var repo = RepositoryFactory.CreatePublicAccessRepository(uow);
                repo.Delete(entry);
                uow.Commit();
                uow.Events.Dispatch(Deleted, this, new DeleteEventArgs <PublicAccessEntry>(entry, false, evtMsgs));
                return(OperationStatus.Success(evtMsgs));
            }
        }
        public static PublicAccessEntry BuildEntity(AccessDto dto)
        {
            var entity = new PublicAccessEntry(dto.Id, dto.NodeId, dto.LoginNodeId, dto.NoAccessNodeId,
                                               dto.Rules.Select(x => new PublicAccessRule(x.Id, x.AccessId)
            {
                RuleValue  = x.RuleValue,
                RuleType   = x.RuleType,
                CreateDate = x.CreateDate,
                UpdateDate = x.UpdateDate
            }))
            {
                CreateDate = dto.CreateDate,
                UpdateDate = dto.UpdateDate
            };

            // reset dirty initial properties (U4-1946)
            entity.ResetDirtyProperties(false);
            return(entity);
        }
示例#21
0
        public PublicAccessEntry BuildEntity(AccessDto dto)
        {
            var entity = new PublicAccessEntry(dto.Id, dto.NodeId, dto.LoginNodeId, dto.NoAccessNodeId,
                                               dto.Rules.Select(x => new PublicAccessRule(x.Id, x.AccessId)
            {
                RuleValue  = x.RuleValue,
                RuleType   = x.RuleType,
                CreateDate = x.CreateDate,
                UpdateDate = x.UpdateDate
            }))
            {
                CreateDate = dto.CreateDate,
                UpdateDate = dto.UpdateDate
            };

            //on initial construction we don't want to have dirty properties tracked
            // http://issues.umbraco.org/issue/U4-1946
            entity.ResetDirtyProperties(false);
            return(entity);
        }
        /// <summary>
        /// Saves the entry
        /// </summary>
        /// <param name="entry"></param>
        public Attempt <OperationStatus> Save(PublicAccessEntry entry)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var uow = UowProvider.GetUnitOfWork())
            {
                var saveEventArgs = new SaveEventArgs <PublicAccessEntry>(entry, evtMsgs);
                if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs))
                {
                    uow.Commit();
                    return(OperationStatus.Cancelled(evtMsgs));
                }

                var repo = RepositoryFactory.CreatePublicAccessRepository(uow);
                repo.AddOrUpdate(entry);
                uow.Commit();
                saveEventArgs.CanCancel = false;
                uow.Events.Dispatch(Saved, this, saveEventArgs);
                return(OperationStatus.Success(evtMsgs));
            }
        }
示例#23
0
        /// <summary>
        /// Deletes the entry and all associated rules
        /// </summary>
        /// <param name="entry"></param>
        public Attempt <OperationResult> Delete(PublicAccessEntry entry)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateScope())
            {
                var deletingNotification = new PublicAccessEntryDeletingNotification(entry, evtMsgs);
                if (scope.Notifications.PublishCancelable(deletingNotification))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(evtMsgs));
                }

                _publicAccessRepository.Delete(entry);
                scope.Complete();

                scope.Notifications.Publish(new PublicAccessEntryDeletedNotification(entry, evtMsgs).WithStateFrom(deletingNotification));
            }

            return(OperationResult.Attempt.Succeed(evtMsgs));
        }
        public void Can_Remove_Rule()
        {
            // Arrange
            var contentService     = ServiceContext.ContentService;
            var contentTypeService = ServiceContext.ContentTypeService;
            var ct = MockedContentTypes.CreateSimpleContentType("blah", "Blah");

            contentTypeService.Save(ct);
            var c = MockedContent.CreateSimpleContent(ct, "Test", -1);

            contentService.Save(c);
            var publicAccessService = ServiceContext.PublicAccessService;
            var entry = new PublicAccessEntry(c, c, c, new[]
            {
                new PublicAccessRule()
                {
                    RuleType  = "TestType",
                    RuleValue = "TestValue1"
                },
                new PublicAccessRule()
                {
                    RuleType  = "TestType",
                    RuleValue = "TestValue2"
                },
            });

            publicAccessService.Save(entry);

            // Act
            var removed = publicAccessService.RemoveRule(c, "TestType", "TestValue1");

            //re-get
            entry = publicAccessService.GetEntryForContent(c);

            // Assert
            Assert.IsTrue(removed.Success);
            Assert.AreEqual(OperationStatusType.Success, removed.Result.StatusType);
            Assert.AreEqual(1, entry.Rules.Count());
            Assert.AreEqual("TestValue2", entry.Rules.ElementAt(0).RuleValue);
        }
示例#25
0
        /// <summary>
        /// Deletes the entry and all associated rules
        /// </summary>
        /// <param name="entry"></param>
        public Attempt <OperationResult> Delete(PublicAccessEntry entry)
        {
            var evtMsgs = EventMessagesFactory.Get();

            using (var scope = ScopeProvider.CreateScope())
            {
                var deleteEventArgs = new DeleteEventArgs <PublicAccessEntry>(entry, evtMsgs);
                if (scope.Events.DispatchCancelable(Deleting, this, deleteEventArgs))
                {
                    scope.Complete();
                    return(OperationResult.Attempt.Cancel(evtMsgs));
                }

                _publicAccessRepository.Delete(entry);
                scope.Complete();

                deleteEventArgs.CanCancel = false;
                scope.Events.Dispatch(Deleted, this, deleteEventArgs);
            }

            return(OperationResult.Attempt.Succeed(evtMsgs));
        }
示例#26
0
    public void Get_By_Id()
    {
        var content = CreateTestData(3).ToArray();

        var provider = ScopeProvider;

        using (var scope = provider.CreateScope())
        {
            var repo = new PublicAccessRepository((IScopeAccessor)provider, AppCaches, LoggerFactory.CreateLogger <PublicAccessRepository>());

            PublicAccessRule[] rules = { new PublicAccessRule {
                                             RuleValue = "test", RuleType = "RoleName"
                                         } };
            var entry = new PublicAccessEntry(content[0], content[1], content[2], rules);
            repo.Save(entry);

            // re-get
            entry = repo.Get(entry.Key);

            Assert.IsNotNull(entry);
        }
    }
    private static bool HasAccess(PublicAccessEntry entry, string username, IEnumerable <string> roles)
    {
        if (entry is null)
        {
            throw new ArgumentNullException(nameof(entry));
        }

        if (string.IsNullOrEmpty(username))
        {
            throw new ArgumentException($"'{nameof(username)}' cannot be null or empty.", nameof(username));
        }

        if (roles is null)
        {
            throw new ArgumentNullException(nameof(roles));
        }

        return(entry.Rules.Any(x =>
                               (x.RuleType == Constants.Conventions.PublicAccess.MemberUsernameRuleType &&
                                username.Equals(x.RuleValue, StringComparison.OrdinalIgnoreCase)) ||
                               (x.RuleType == Constants.Conventions.PublicAccess.MemberRoleRuleType && roles.Contains(x.RuleValue))));
    }
示例#28
0
        /// <summary>
        /// Deletes the entry and all associated rules
        /// </summary>
        /// <param name="entry"></param>
        public Attempt <OperationStatus> Delete(PublicAccessEntry entry)
        {
            var evtMsgs = EventMessagesFactory.Get();

            if (Deleting.IsRaisedEventCancelled(
                    new DeleteEventArgs <PublicAccessEntry>(entry, evtMsgs),
                    this))
            {
                return(Attempt.Fail(OperationStatus.Cancelled(evtMsgs)));
            }

            var uow = UowProvider.GetUnitOfWork();

            using (var repo = RepositoryFactory.CreatePublicAccessRepository(uow))
            {
                repo.Delete(entry);
                uow.Commit();
            }

            Deleted.RaiseEvent(new DeleteEventArgs <PublicAccessEntry>(entry, false, evtMsgs), this);
            return(Attempt.Succeed(OperationStatus.Success(evtMsgs)));
        }
示例#29
0
    public static AccessDto BuildDto(PublicAccessEntry entity)
    {
        var dto = new AccessDto
        {
            Id             = entity.Key,
            NoAccessNodeId = entity.NoAccessNodeId,
            LoginNodeId    = entity.LoginNodeId,
            NodeId         = entity.ProtectedNodeId,
            CreateDate     = entity.CreateDate,
            UpdateDate     = entity.UpdateDate,
            Rules          = entity.Rules.Select(x => new AccessRuleDto
            {
                AccessId   = x.AccessEntryId,
                Id         = x.Key,
                RuleValue  = x.RuleValue,
                RuleType   = x.RuleType,
                CreateDate = x.CreateDate,
                UpdateDate = x.UpdateDate,
            }).ToList(),
        };

        return(dto);
    }
        public void Can_Update()
        {
            var content = CreateTestData(3).ToArray();

            var provider = TestObjects.GetScopeProvider(Logger);

            using (var scope = provider.CreateScope())
            {
                var repo = new PublicAccessRepository((IScopeAccessor)provider, CacheHelper, Logger);

                var entry = new PublicAccessEntry(content[0], content[1], content[2], new[]
                {
                    new PublicAccessRule
                    {
                        RuleValue = "test",
                        RuleType  = "RoleName"
                    },
                });
                repo.Save(entry);


                //re-get
                entry = repo.Get(entry.Key);

                entry.Rules.First().RuleValue = "blah";
                entry.Rules.First().RuleType  = "asdf";
                repo.Save(entry);



                //re-get
                entry = repo.Get(entry.Key);

                Assert.AreEqual("blah", entry.Rules.First().RuleValue);
                Assert.AreEqual("asdf", entry.Rules.First().RuleType);
            }
        }
示例#31
0
        /// <summary>
        /// Adds the Umbraco content.
        /// </summary>
        /// <returns>
        /// The <see cref="IContent"/>.
        /// </returns>
        private IContent AddUmbracoData()
        {
            #region Store Root

            // Create the store root and add the initial data

            LogHelper.Info<BazaarDataInstaller>("Installing store root node");

            var storeRoot = _services.ContentService.CreateContent("Store", -1, "BazaarStore");

            // Default theme
            storeRoot.SetValue("themePicker", "Sandstone-3");
            storeRoot.SetValue("customerMemberType", "MerchelloCustomer");
            storeRoot.SetValue("storeTitle", "Merchello Bazaar");
            storeRoot.SetValue("overview", @"<p>The Merchello Bazaar is a simple, example store which has been developed to help get you up and running quickly with Merchello. 
                                            It's designed to show you how to implement common features, and <a href=""https://github.com/Merchello/Merchello"" target=""_blank"">
                                            you can grab the source code from here</a>, just fork/clone/download and open up Merchello.Bazaar.sln</p>");
            storeRoot.SetValue("featuredProducts", _collections["collectionFeaturedProducts"].ToString());

            _services.ContentService.SaveAndPublishWithStatus(storeRoot);

            #endregion

            #region Example Categories

            // Add the example categories
            LogHelper.Info<BazaarDataInstaller>("Adding example category page");

            // Create the root T-Shirt category
            var tShirtCategory = _services.ContentService.CreateContent("All T-Shirts", storeRoot.Id, "BazaarProductCollection");

            tShirtCategory.SetValue("products", string.Empty);
            _services.ContentService.SaveAndPublishWithStatus(tShirtCategory);
                
            // Create the sun categories
            var funnyTShirts = _services.ContentService.CreateContent("Funny T-Shirts", tShirtCategory.Id, "BazaarProductCollection");
            funnyTShirts.SetValue("products", _collections[CollectionFunny].ToString());
            funnyTShirts.SetValue("description", @"<p>Pinterest health goth stumptown before they sold out. Locavore banjo typewriter, street art viral XOXO kickstarter retro brooklyn direct trade. 
                                                    Gluten-free taxidermy messenger bag celiac, kinfolk pinterest affogato tattooed echo park chillwave chambray slow-carb freegan. Messenger bag kombucha hammock pabst twee yuccie.</p>");
            _services.ContentService.SaveAndPublishWithStatus(funnyTShirts);

            var geekyTShirts = _services.ContentService.CreateContent("Geeky T-Shirts", tShirtCategory.Id, "BazaarProductCollection");
            geekyTShirts.SetValue("products", _collections[CollectionGeeky].ToString());
            geekyTShirts.SetValue("description", @"<p>Forage master cleanse jean shorts knausgaard sustainable. Kale chips wayfarers pop-up selvage, hashtag tattooed yuccie mlkshk truffaut next level. 
                                                    Street art salvia drinking vinegar brunch kogi, put a bird on it farm-to-table food truck shoreditch next level vegan bespoke portland venmo helvetica.</p>");
            _services.ContentService.SaveAndPublishWithStatus(geekyTShirts);

            var sadTShirts = _services.ContentService.CreateContent("Sad T-Shirts", tShirtCategory.Id, "BazaarProductCollection");
            sadTShirts.SetValue("products", _collections[CollectionSad].ToString());
            sadTShirts.SetValue("description", @"<p>Fingerstache ramps lo-fi schlitz. Microdosing yr keffiyeh, ennui sartorial pork belly meditation polaroid. Tofu tilde occupy, photo booth single-origin coffee hammock gentrify. 
                                                    Farm-to-table PBR&amp;B 90's fashion axe sustainable blue bottle typewriter occupy, twee drinking vinegar yuccie. Pabst yr vegan, truffaut DIY slow-carb tumblr thundercats next level street 
                                                    art biodiesel leggings hella letterpress food truck. Gochujang vice normcore deep v, mustache PBR&amp;B drinking vinegar yr gentrify shoreditch.</p>");
            _services.ContentService.SaveAndPublishWithStatus(sadTShirts);

            #endregion

            #region Required Other Pages

            LogHelper.Info<BazaarDataInstaller>("Adding example eCommerce workflow pages");

            var basket = _services.ContentService.CreateContent("Basket", storeRoot.Id, "BazaarBasket");
            _services.ContentService.SaveAndPublishWithStatus(basket);

            var checkout = _services.ContentService.CreateContent("Checkout", storeRoot.Id, "BazaarCheckout");
            _services.ContentService.SaveAndPublishWithStatus(checkout);

            var checkoutConfirm = _services.ContentService.CreateContent("Confirm Sale", checkout.Id, "BazaarCheckoutConfirm");
            _services.ContentService.SaveAndPublishWithStatus(checkoutConfirm);

            var receipt = _services.ContentService.CreateContent("Receipt", checkout.Id, "BazaarReceipt");
            _services.ContentService.SaveAndPublishWithStatus(receipt);

            var registration = _services.ContentService.CreateContent("Registration / Login", storeRoot.Id, "BazaarRegistration");
            _services.ContentService.SaveAndPublishWithStatus(registration);

            var account = _services.ContentService.CreateContent("Account", storeRoot.Id, "BazaarAccount");
            _services.ContentService.SaveAndPublishWithStatus(account);

            var wishList = _services.ContentService.CreateContent("Wish List", account.Id, "BazaarWishList");
            _services.ContentService.SaveAndPublishWithStatus(wishList);

            var purchaseHistory = _services.ContentService.CreateContent("Purchase History", account.Id, "BazaarAccountHistory");
            _services.ContentService.SaveAndPublishWithStatus(purchaseHistory);

            #endregion

            #region Restrict Access to the Account page

            // Protect the page
            // OLD > Access.ProtectPage(false, account.Id, registration.Id, registration.Id);
            var entry = new PublicAccessEntry(account, registration, registration, new List<PublicAccessRule>());
            ApplicationContext.Current.Services.PublicAccessService.Save(entry);

            // Add the role to the document
            //Old > Access.AddMembershipRoleToDocument(account.Id, "MerchelloCustomers");
            ApplicationContext.Current.Services.PublicAccessService.AddRule(account,
                Umbraco.Core.Constants.Conventions.PublicAccess.MemberRoleRuleType,
                "MerchelloCustomers"); 

            #endregion

            //// TODO figure out why the index does not build on load
            //LogHelper.Info<BazaarDataInstaller>("Rebuilding Product Index");
            //ExamineManager.Instance.IndexProviderCollection["MerchelloProductIndexer"].RebuildIndex();

            return storeRoot;
        }
        /// <summary>
        /// Adds the Umbraco content.
        /// </summary>
        /// <returns>
        /// The <see cref="IContent"/>.
        /// </returns>
        private IContent AddUmbracoData()
        {
            MultiLogHelper.Info<FastTrackDataInstaller>("Install MemberType");

            // Create the store root and add the initial data

            MultiLogHelper.Info<FastTrackDataInstaller>("Installing store root node");

            var storeRoot = _services.ContentService.CreateContent("Store", -1, "store");

            storeRoot.SetValue("storeName", "FastTrack Store");
            storeRoot.SetValue("brief", @"<p>Example store which has been developed to help get you up and running quickly with Merchello.
                                            It's designed to show you how to implement common features, and you can grab the source code from here, just fork/clone/download and open up Merchello.sln</p>");
            storeRoot.SetValue("featuredProducts", _collections["collectionFeaturedProducts"].ToString());

            _services.ContentService.SaveAndPublishWithStatus(storeRoot);

            // Add the example categories
            LogHelper.Info<FastTrackDataInstaller>("Adding example category page");

            // Create the root T-Shirt category
            var catalog = _services.ContentService.CreateContent("Catalog", storeRoot.Id, "catalog");

            catalog.SetValue("categories", _collections[CollectionMainCategories].ToString());
            _services.ContentService.SaveAndPublishWithStatus(catalog);

            // Create the sun categories
            var funnyTShirts = _services.ContentService.CreateContent("Funny T-Shirts", catalog.Id, "category");
            funnyTShirts.SetValue("products", _collections[CollectionFunny].ToString());
            _services.ContentService.SaveAndPublishWithStatus(funnyTShirts);

            var geekyTShirts = _services.ContentService.CreateContent("Geeky T-Shirts", catalog.Id, "category");
            geekyTShirts.SetValue("products", _collections[CollectionGeeky].ToString());
            _services.ContentService.SaveAndPublishWithStatus(geekyTShirts);

            var sadTShirts = _services.ContentService.CreateContent("Sad T-Shirts", catalog.Id, "category");
            sadTShirts.SetValue("products", _collections[CollectionSad].ToString());
            _services.ContentService.SaveAndPublishWithStatus(sadTShirts);

            MultiLogHelper.Info<FastTrackDataInstaller>("Adding example eCommerce workflow pages");

            var basket = _services.ContentService.CreateContent("Basket", storeRoot.Id, "basket");
            _services.ContentService.SaveAndPublishWithStatus(basket);

            var checkout = _services.ContentService.CreateContent("Checkout", storeRoot.Id, "checkout");
            checkout.Template = _templates.FirstOrDefault(x => x.Alias == "BillingAddress");
            checkout.SetValue("checkoutStage", "BillingAddress");
            _services.ContentService.SaveAndPublishWithStatus(checkout);

            var checkoutShipping = _services.ContentService.CreateContent("Shipping Address", checkout.Id, "checkout");
            checkoutShipping.Template = _templates.FirstOrDefault(x => x.Alias == "ShippingAddress");
            checkoutShipping.SetValue("checkoutStage", "ShippingAddress");
            _services.ContentService.SaveAndPublishWithStatus(checkoutShipping);

            var checkoutShipRateQuote = _services.ContentService.CreateContent("Ship Rate Quote", checkout.Id, "checkout");
            checkoutShipRateQuote.Template = _templates.FirstOrDefault(x => x.Alias == "ShipRateQuote");
            checkoutShipRateQuote.SetValue("checkoutStage", "ShipRateQuote");
            _services.ContentService.SaveAndPublishWithStatus(checkoutShipRateQuote);

            var checkoutPaymentMethod = _services.ContentService.CreateContent("Payment Method", checkout.Id, "checkout");
            checkoutPaymentMethod.Template = _templates.FirstOrDefault(x => x.Alias == "PaymentMethod");
            checkoutPaymentMethod.SetValue("checkoutStage", "PaymentMethod");
            _services.ContentService.SaveAndPublishWithStatus(checkoutPaymentMethod);

            var checkoutPayment = _services.ContentService.CreateContent("Payment", checkout.Id, "checkout");
            checkoutPayment.Template = _templates.FirstOrDefault(x => x.Alias == "Payment");
            checkoutPayment.SetValue("checkoutStage", "Payment");
            _services.ContentService.SaveAndPublishWithStatus(checkoutPayment);

            var receipt = _services.ContentService.CreateContent("Receipt", storeRoot.Id, "receipt");
            _services.ContentService.SaveAndPublishWithStatus(receipt);

            var login = _services.ContentService.CreateContent("Login", storeRoot.Id, "login");
            _services.ContentService.SaveAndPublishWithStatus(login);

            var account = _services.ContentService.CreateContent("Account", storeRoot.Id, "account");
            _services.ContentService.SaveAndPublishWithStatus(account);

            //// Protect the page
            var entry = new PublicAccessEntry(account, login, login, new List<PublicAccessRule>());
            ApplicationContext.Current.Services.PublicAccessService.Save(entry);

            //// Add the role to the document
            ApplicationContext.Current.Services.PublicAccessService.AddRule(account, Umbraco.Core.Constants.Conventions.PublicAccess.MemberRoleRuleType, "Customers");

            return storeRoot;
        }