Exemplo n.º 1
0
 private void CreateProfileTemplate()
 {
     RepositoryTools.CreateStructure("/Root/ContentTemplates/UserProfile", "SystemFolder");
     RepositoryTools.CreateStructure("/Root/ContentTemplates/UserProfile/UserProfile", "UserProfile");
     RepositoryTools.CreateStructure("/Root/ContentTemplates/UserProfile/UserProfile/DocLib", "DocumentLibrary");
     RepositoryTools.CreateStructure("/Root/ContentTemplates/UserProfile/UserProfile/DocLib/f1/f2", "Folder");
 }
        protected async Task <User> CreateUser(string nameCandidate, string loginName, string email, string fullName,
                                               Action <Content> setProperties, CancellationToken cancellationToken)
        {
            var parentPath = string.IsNullOrEmpty(_options.ParentPath) ? "/Root/IMS/Public" : _options.ParentPath;
            var userType   = string.IsNullOrEmpty(_options.UserType) ? "User" : _options.UserType;

            var parent = RepositoryTools.CreateStructure(parentPath, "Domain") ??
                         await Content.LoadAsync(parentPath, cancellationToken).ConfigureAwait(false);

            // If a user with the same name exists, make sure we create
            // a new one and let the application deal with merging them later.
            var name = ContentNamingProvider.GetNameFromDisplayName(nameCandidate);

            if (Node.Exists(RepositoryPath.Combine(parent.Path, name)))
            {
                name = ContentNamingProvider.IncrementNameSuffixToLastName(name, parent.Id);
            }

            var user = Content.CreateNew(userType, parent.ContentHandler, name);

            user["LoginName"] = loginName;
            user["Email"]     = email;
            user["FullName"]  = string.IsNullOrEmpty(fullName) ? name : fullName;
            user.DisplayName  = string.IsNullOrEmpty(fullName) ? name : fullName;
            user["Enabled"]   = true;

            setProperties?.Invoke(user);

            user.Save();

            await AddUserToDefaultGroupsAsync(user.ContentHandler as User, cancellationToken).ConfigureAwait(false);

            return(user.ContentHandler as User);
        }
Exemplo n.º 3
0
        public override void Initialize(Content context, string backUri, Application application, object parameters)
        {
            base.Initialize(context, backUri, application, parameters);

            if (context == null)
            {
                this.Visible = false;
                return;
            }

            // if the Views folder does not exist, we have to create it
            // (but only in case of a content list)
            var cl = ContentList.GetContentListByParentWalk(context.ContentHandler);

            if (cl != null)
            {
                var viewsFolderPath = RepositoryPath.Combine(cl.Path, ViewManager.VIEWSFOLDERNAME);
                if (!Node.Exists(viewsFolderPath))
                {
                    using (new SystemAccount())
                    {
                        RepositoryTools.CreateStructure(viewsFolderPath, "SystemFolder");
                    }
                }
            }
        }
Exemplo n.º 4
0
        public void Search_ReferenceField()
        {
            IntegrationTest(() =>
            {
                ContentTypeInstaller.InstallContentType(CtdSearchTestReference);

                var parent  = RepositoryTools.CreateStructure("/Root/" + Guid.NewGuid(), "SystemFolder");
                var folder1 = Content.CreateNew("Folder", parent.ContentHandler, "f1");
                folder1.SaveSameVersion();
                var folder2 = Content.CreateNew("Folder", parent.ContentHandler, "f2");
                folder2.SaveSameVersion();
                var folder3 = Content.CreateNew("Folder", parent.ContentHandler, "f3");
                folder3.SaveSameVersion();

                var content1 = Content.CreateNew("GenericContentWithReferenceTest", parent.ContentHandler, "content1");

                content1["SearchTestReference"] = new[]
                {
                    folder1.ContentHandler, folder2.ContentHandler, folder3.ContentHandler
                };
                content1.SaveSameVersion();

                // find content by the reference field
                var result1 = CreateSafeContentQuery($"+SearchTestReference:{folder1.Id}").Execute().Nodes.FirstOrDefault();
                var result2 = CreateSafeContentQuery($"+SearchTestReference:{folder2.Id}").Execute().Nodes.FirstOrDefault();
                var result3 = CreateSafeContentQuery($"+SearchTestReference:{folder3.Id}").Execute().Nodes.FirstOrDefault();

                Assert.IsNotNull(result1);
                Assert.IsNotNull(result2);
                Assert.IsNotNull(result3);
                Assert.AreEqual(content1.Id, result1.Id);
                Assert.AreEqual(content1.Id, result2.Id);
                Assert.AreEqual(content1.Id, result3.Id);
            });
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            var builder = CreateWebHostBuilder(args);
            var host    = builder.Build();

            SnTrace.EnableAll();

            using (InMemoryExtensions.StartInMemoryRepository(repositoryBuilder =>
            {
                repositoryBuilder
                .UseAccessProvider(new UserAccessProvider())
                .UseLogger(new SnFileSystemEventLogger())
                .UseTracer(new SnFileSystemTracer());
            }))
            {
                using (new SystemAccount())
                {
                    // FOR TESTING PURPOSES: create a default user with a well-known password
                    // login:    [email protected]
                    // password: Edvin123%

                    var parentPath = "/Root/IMS/BuiltIn/Temp";
                    var parent     = RepositoryTools.CreateStructure(parentPath, "OrganizationalUnit");

                    var user = new User(parent.ContentHandler)
                    {
                        Name         = "edvin-example.com",
                        LoginName    = "*****@*****.**",
                        PasswordHash =
                            "AQAAAAEAACcQAAAAEKEsynr6baKE5rYqS4Rn6pjqckl+NG4W9UQqqGh4g23zlJQpQvnaZnzx44+z78FVsg==",
                        Email = "*****@*****.**"
                    };
                    user.Save();

                    // set the new user as administrator
                    Group.Administrators.AddMember(user);

                    // create a container for test content
                    parent = RepositoryTools.CreateStructure("/Root/MyContent", "SystemFolder");

                    // create a doclib that contains a file
                    var docLib = RepositoryTools.CreateStructure("/Root/MyContent/MyFiles", "DocumentLibrary");
                    ((GenericContent)docLib.ContentHandler).AllowChildType("Image", save: true);

                    var file = new File(docLib.ContentHandler)
                    {
                        Name = "testfile.txt"
                    };
                    file.Binary.SetStream(RepositoryTools.GetStreamFromString($"temp text data {DateTime.UtcNow}"));
                    file.Save();

                    //var installer = new Installer();
                    //installer.Import("C:\\temp\\import\\Root");
                }

                SnTrace.EnableAll();
                host.Run();
            }
        }
Exemplo n.º 6
0
        private static Node LoadOrCreateUserParent(string providerName)
        {
            // E.g. /Root/IMS/Public/facebook
            var userDomain = Settings.GetValue(SettingsName, DomainSettingName, null, "Public");
            var domainPath = RepositoryPath.Combine(RepositoryStructure.ImsFolderPath, userDomain);
            var dummy      = Node.LoadNode(domainPath) ??
                             RepositoryTools.CreateStructure(domainPath, "Domain")?.ContentHandler;
            var orgUnitPath = RepositoryPath.Combine(domainPath, providerName);
            var orgUnit     = Node.LoadNode(orgUnitPath) ??
                              RepositoryTools.CreateStructure(orgUnitPath, "OrganizationalUnit")?.ContentHandler;

            return(orgUnit);
        }
        private File CreateFile(VersioningType versioningType = VersioningType.Inherited, ApprovingType approvingType = ApprovingType.False)
        {
            var parent = (RepositoryTools.CreateStructure("/Root/Content/Docs", "DocumentLibrary")
                          ?? Content.Load("/Root/Content/Docs")).ContentHandler;
            var file = new File(parent)
            {
                VersioningMode = versioningType,
                ApprovingMode  = approvingType
            };

            file.Save();

            return(file);
        }
        protected override Node GetContextNode()
        {
            var node = GetBindingRoot();

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

            node = AncestorIndex == 0 ? node : node.GetAncestor(AncestorIndex);

            if (!string.IsNullOrEmpty(RelativeContentPath))
            {
                var fullRelativePath = RepositoryPath.Combine(node.Path, RelativeContentPath);

                if (!fullRelativePath.EndsWith("/(apps)") && !fullRelativePath.Contains("/(apps)/"))
                {
                    try
                    {
                        node = Node.LoadNode(fullRelativePath);
                        if (node != null)
                        {
                            return(node);
                        }

                        if (CreateRelativePath)
                        {
                            using (new SystemAccount())
                            {
                                var container = RepositoryTools.CreateStructure(fullRelativePath, string.IsNullOrEmpty(RelativeContentTypeName) ? "Folder" : this.RelativeContentTypeName);
                                if (container != null)
                                {
                                    return(container.ContentHandler);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        SnLog.WriteException(ex);
                        node = null;
                    }
                }
            }

            return(node);
        }
Exemplo n.º 9
0
        public static Handlers.ViewBase CopyViewLocal(string listPath, string viewPath, bool setAsDefault)
        {
            if (string.IsNullOrEmpty(listPath))
            {
                throw new ArgumentNullException("listPath");
            }
            if (string.IsNullOrEmpty(viewPath))
            {
                throw new ArgumentNullException("viewPath");
            }

            var viewName        = RepositoryPath.GetFileNameSafe(viewPath);
            var viewsFolderPath = RepositoryPath.Combine(listPath, ViewManager.VIEWSFOLDERNAME);
            var views           = Content.Load(viewsFolderPath) ?? RepositoryTools.CreateStructure(viewsFolderPath, "SystemFolder");
            var viewsGc         = views != null ? views.ContentHandler as GenericContent : null;

            // set at least the ListView type as allowed content type
            if (viewsGc != null && viewsGc.GetAllowedChildTypes().Count() == 0)
            {
                using (new SystemAccount())
                {
                    viewsGc.AllowedChildTypes = new[] { ContentType.GetByName("ListView") };
                    viewsGc.Save(SavingMode.KeepVersion);
                }
            }

            Node.Copy(viewPath, viewsFolderPath);

            var localView = Node.Load <Handlers.ViewBase>(RepositoryPath.Combine(viewsFolderPath, viewName));

            if (setAsDefault)
            {
                var cl = Node.Load <ContentList>(listPath);
                if (cl != null)
                {
                    cl.DefaultView = viewName;
                    cl.Save();
                }
            }

            return(localView);
        }
Exemplo n.º 10
0
        private Task <WebHookSubscription> CreateWebHookSubscriptionAsync(string filter, string headers = null, string payload = null)
        {
            var container = RepositoryTools.CreateStructure("/Root/System/WebHooks", "SystemFolder") ??
                            Content.Load("/Root/System/WebHooks");

            var wh = new WebHookSubscription(container.ContentHandler)
            {
                Url    = "https://localhost:44393/webhooks/test",
                Filter = filter,
                //Filter = "{ \"Path\": \"/Root/Content\", \"ContentTypes\": [ { \"Name\": \"Folder\", \"Events\": [ \"Create\", \"Publish\" ] } ] }",
                Headers = headers,
                //Headers = "{ \"h1-custom\": \"value1\", \"h2-custom\": \"value2\" }",
                Payload = payload,
                AllowIncrementalNaming = true
            };

            wh.Save();

            return(Node.LoadAsync <WebHookSubscription>(wh.Id, CancellationToken.None));
        }
Exemplo n.º 11
0
        private static void CreateWebHooksContainer()
        {
            var webHooks = Node.Load <GenericContent>(WebHooksPath);

            if (webHooks != null && !webHooks.NodeType.IsInstaceOfOrDerivedFrom("ItemList"))
            {
                webHooks.ForceDelete();
                webHooks = null;
            }

            if (webHooks == null)
            {
                webHooks = (GenericContent)RepositoryTools.CreateStructure(WebHooksPath, "ItemList")
                           .ContentHandler;
            }

            if (!webHooks.IsAllowedChildType(nameof(WebHookSubscription)))
            {
                webHooks.AllowChildType(nameof(WebHookSubscription), save: true);
            }
        }
        public async Task <User> CreateProviderUserAsync(Content content, HttpContext context, string provider, string userId,
                                                         ClaimInfo[] claims, CancellationToken cancellationToken)
        {
            var parentPath = string.IsNullOrEmpty(DefaultParentPath) ? "/Root/IMS/Public" : DefaultParentPath;
            var userType   = string.IsNullOrEmpty(DefaultUserType) ? "User" : DefaultUserType;

            var parent = RepositoryTools.CreateStructure(parentPath, "Domain") ??
                         await Content.LoadAsync(parentPath, cancellationToken).ConfigureAwait(false);

            var fullName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value ?? string.Empty;
            var email    = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value ?? string.Empty;

            // Fill the field with an initial JSON data containing a single provider data.
            // Later, if the user already exists, this field needs to be edited: the new id
            // should be inserted instead of overwriting the current value.
            var external = $"{{ \"{provider}\": {{ \"Id\": \"{userId}\", \"Completed\": false }} }}";

            // User content name will be the email.
            // Current behavior: if a user with the same name exists, make sure we create
            // a new one and let the application deal with merging them later.
            var name = ContentNamingProvider.GetNameFromDisplayName(email);

            if (Node.Exists(RepositoryPath.Combine(parent.Path, name)))
            {
                name = ContentNamingProvider.IncrementNameSuffixToLastName(name, parent.Id);
            }

            var user = Content.CreateNew(userType, parent.ContentHandler, name);

            user["ExternalUserProviders"] = external;
            user["Email"]    = email;
            user["FullName"] = fullName;
            user.DisplayName = fullName;

            user.Save();

            await AddUserToDefaultGroupsAsync(user.ContentHandler as User, cancellationToken).ConfigureAwait(false);

            return(user.ContentHandler as User);
        }
Exemplo n.º 13
0
        private static void InstallStringResource(string resourceContentName)
        {
            var assembly       = typeof(WebHookComponent).Assembly;
            var resourcePrefix = assembly.GetName().Name;

            // install a string resource stored as an embedded resource
            var          resourcePath = resourcePrefix + ".import.Localization." + resourceContentName;
            const string parentPath   = "/Root/Localization";

            using (var resourceStream = assembly.GetManifestResourceStream(resourcePath))
            {
                var parent = RepositoryTools.CreateStructure(parentPath, "Resources") ??
                             Content.Load(parentPath);
                var whResourcePath = RepositoryPath.Combine(parentPath, resourceContentName);
                var whResource     = Node.Load <Resource>(whResourcePath) ??
                                     new Resource(parent.ContentHandler)
                {
                    Name = resourceContentName
                };
                whResource.Binary = UploadHelper.CreateBinaryData(resourceContentName, resourceStream);
                whResource.Save(SavingMode.KeepVersion);
            }
        }
Exemplo n.º 14
0
        public void User_CreateByRegularUser()
        {
            Test(true, () =>
            {
                var parentPath   = "/Root/IMS/BuiltIn/Temp-" + Guid.NewGuid();
                var originalUser = AccessProvider.Current.GetOriginalUser();

                try
                {
                    User user1;
                    Content parent;

                    using (new SystemAccount())
                    {
                        // create a test container
                        parent = RepositoryTools.CreateStructure(parentPath, "OrganizationalUnit");

                        // create a test user
                        user1 = new User(parent.ContentHandler)
                        {
                            Name      = "sample-sam",
                            LoginName = "*****@*****.**",
                            Email     = "*****@*****.**"
                        };
                        user1.Save();

                        // add permissions for this test user (local Add, but not TakeOwnership) and for Owners (everything)
                        var editor = SnSecurityContext.Create().CreateAclEditor();
                        editor
                        .Allow(parent.Id, user1.Id, true, PermissionType.AddNew)
                        .Allow(parent.Id, Identifiers.OwnersGroupId, false, PermissionType.BuiltInPermissionTypes)
                        // technical permission for content types
                        .Allow(Identifiers.PortalRootId, user1.Id, false, PermissionType.See);
                        editor.Apply();
                    }

                    AccessProvider.Current.SetCurrentUser(user1);

                    // create a new user in the name of the test user
                    var user2 = new User(parent.ContentHandler)
                    {
                        Name      = "newser",
                        LoginName = "*****@*****.**",
                        Email     = "*****@*****.**"
                    };

                    //ACTION
                    user2.Save();

                    using (new SystemAccount())
                    {
                        // user1 could create user2, but cannot open or modify it, because he only has AddNew permission on the parent
                        Assert.IsFalse(user2.Security.HasPermission(user1, PermissionType.Open));

                        // the new user should have permissions for herself because she is the owner
                        Assert.IsTrue(user2.Security.HasPermission(user2, PermissionType.Save));
                    }
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);

                    using (new SystemAccount())
                        if (Node.Exists(parentPath))
                        {
                            Node.ForceDelete(parentPath);
                        }
                }
            });
        }