Exemplo n.º 1
0
 /// <inheritdoc />
 public IRelationType?GetRelationTypeById(Guid id)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_relationTypeRepository.Get(id));
     }
 }
Exemplo n.º 2
0
 /// <inheritdoc />
 public IEnumerable <IScript> GetScripts(params string[] names)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_scriptRepository.GetMany(names));
     }
 }
Exemplo n.º 3
0
        /// <inheritdoc />
        public void SaveScript(IScript?script, int?userId)
        {
            if (userId is null)
            {
                userId = Constants.Security.SuperUserId;
            }
            if (script is null)
            {
                return;
            }

            using (ICoreScope scope = ScopeProvider.CreateCoreScope())

            {
                EventMessages eventMessages      = EventMessagesFactory.Get();
                var           savingNotification = new ScriptSavingNotification(script, eventMessages);
                if (scope.Notifications.PublishCancelable(savingNotification))
                {
                    scope.Complete();
                    return;
                }

                _scriptRepository.Save(script);
                scope.Notifications.Publish(new ScriptSavedNotification(script, eventMessages).WithStateFrom(savingNotification));

                Audit(AuditType.Save, userId.Value, -1, "Script");
                scope.Complete();
            }
        }
Exemplo n.º 4
0
 /// <inheritdoc />
 public long GetPartialViewMacroFileSize(string filepath)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_partialViewMacroRepository.GetFileSize(filepath));
     }
 }
Exemplo n.º 5
0
 /// <inheritdoc />
 public Stream?GetStylesheetFileContentStream(string filepath)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_stylesheetRepository.GetFileContentStream(filepath));
     }
 }
Exemplo n.º 6
0
 /// <inheritdoc />
 public IStylesheet?GetStylesheet(string?path)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_stylesheetRepository.Get(path));
     }
 }
Exemplo n.º 7
0
    private Attempt <IPartialView?> SavePartialView(IPartialView partialView, PartialViewType partialViewType, int?userId = null)
    {
        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            EventMessages eventMessages      = EventMessagesFactory.Get();
            var           savingNotification = new PartialViewSavingNotification(partialView, eventMessages);
            if (scope.Notifications.PublishCancelable(savingNotification))
            {
                scope.Complete();
                return(Attempt <IPartialView?> .Fail());
            }

            userId ??= Constants.Security.SuperUserId;
            IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
            repository.Save(partialView);

            Audit(AuditType.Save, userId.Value, -1, partialViewType.ToString());
            scope.Notifications.Publish(
                new PartialViewSavedNotification(partialView, eventMessages).WithStateFrom(savingNotification));

            scope.Complete();
        }

        return(Attempt.Succeed(partialView));
    }
        public void Validate_Login_Session()
        {
            // Arrange
            ICoreScopeProvider provider = ScopeProvider;
            User user = UserBuilder.CreateUser();

            using (ICoreScope scope = provider.CreateCoreScope(autoComplete: true))
            {
                UserRepository repository = CreateRepository(provider);
                repository.Save(user);
            }

            using (ICoreScope scope = provider.CreateCoreScope(autoComplete: true))
            {
                UserRepository repository = CreateRepository(provider);
                Guid           sessionId  = repository.CreateLoginSession(user.Id, "1.2.3.4");

                // manually update this record to be in the past
                ScopeAccessor.AmbientScope.Database.Execute(ScopeAccessor.AmbientScope.SqlContext.Sql()
                                                            .Update <UserLoginDto>(u => u.Set(x => x.LoggedOutUtc, DateTime.UtcNow.AddDays(-100)))
                                                            .Where <UserLoginDto>(x => x.SessionId == sessionId));

                bool isValid = repository.ValidateLoginSession(user.Id, sessionId);
                Assert.IsFalse(isValid);

                // create a new one
                sessionId = repository.CreateLoginSession(user.Id, "1.2.3.4");
                isValid   = repository.ValidateLoginSession(user.Id, sessionId);
                Assert.IsTrue(isValid);
            }
        }
Exemplo n.º 9
0
 /// <summary>
 ///     Gets a list of all <see cref="ITemplate" /> objects
 /// </summary>
 /// <returns>An enumerable list of <see cref="ITemplate" /> objects</returns>
 public IEnumerable <ITemplate> GetTemplates(params string[] aliases)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_templateRepository.GetAll(aliases).OrderBy(x => x.Name));
     }
 }
        public void Can_Perform_Delete_On_UserRepository()
        {
            // Arrange
            ICoreScopeProvider provider = ScopeProvider;

            using (ICoreScope scope = provider.CreateCoreScope())
            {
                UserRepository repository = CreateRepository(provider);

                User user = UserBuilderInstance.Build();

                // Act
                repository.Save(user);

                int id = user.Id;

                Mock <IRuntimeState> mockRuntimeState = CreateMockRuntimeState(RuntimeLevel.Run);

                var repository2 = new UserRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger <UserRepository>(), Mock.Of <IMapperCollection>(), Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer(), mockRuntimeState.Object);

                repository2.Delete(user);

                IUser resolved = repository2.Get((int)id);

                // Assert
                Assert.That(resolved, Is.Null);
            }
        }
        public void Can_Invalidate_SecurityStamp_On_Username_Change()
        {
            // Arrange
            ICoreScopeProvider provider = ScopeProvider;

            using (ICoreScope scope = provider.CreateCoreScope())
            {
                UserRepository      repository          = CreateRepository(provider);
                UserGroupRepository userGroupRepository = CreateUserGroupRepository(provider);

                User   user = CreateAndCommitUserWithGroup(repository, userGroupRepository);
                string originalSecurityStamp = user.SecurityStamp;

                // Ensure when user generated a security stamp is present
                Assert.That(user.SecurityStamp, Is.Not.Null);
                Assert.That(user.SecurityStamp, Is.Not.Empty);

                // Update username
                user.Username += "UPDATED";
                repository.Save(user);

                // Get the user
                IUser updatedUser = repository.Get(user.Id);

                // Ensure the Security Stamp is invalidated & no longer the same
                Assert.AreNotEqual(originalSecurityStamp, updatedUser.SecurityStamp);
            }
        }
Exemplo n.º 12
0
        /// <inheritdoc />
        public void DeleteRelationsOfType(IRelationType relationType)
        {
            var relations = new List <IRelation>();

            using (ICoreScope scope = ScopeProvider.CreateCoreScope())
            {
                IQuery <IRelation>?query = Query <IRelation>().Where(x => x.RelationTypeId == relationType.Id);
                var allRelations         = _relationRepository.Get(query)?.ToList();
                if (allRelations is not null)
                {
                    relations.AddRange(allRelations);
                }

                //TODO: N+1, we should be able to do this in a single call

                foreach (IRelation relation in relations)
                {
                    _relationRepository.Delete(relation);
                }

                scope.Complete();

                scope.Notifications.Publish(new RelationDeletedNotification(relations, EventMessagesFactory.Get()));
            }
        }
Exemplo n.º 13
0
        /// <inheritdoc />
        public IRelation Relate(int parentId, int childId, IRelationType relationType)
        {
            // Ensure that the RelationType has an identity before using it to relate two entities
            if (relationType.HasIdentity == false)
            {
                Save(relationType);
            }

            //TODO: We don't check if this exists first, it will throw some sort of data integrity exception if it already exists, is that ok?

            var relation = new Relation(parentId, childId, relationType);

            using (ICoreScope scope = ScopeProvider.CreateCoreScope())
            {
                EventMessages eventMessages      = EventMessagesFactory.Get();
                var           savingNotification = new RelationSavingNotification(relation, eventMessages);
                if (scope.Notifications.PublishCancelable(savingNotification))
                {
                    scope.Complete();
                    return(relation); // TODO: returning sth that does not exist here?!
                }

                _relationRepository.Save(relation);
                scope.Notifications.Publish(new RelationSavedNotification(relation, eventMessages).WithStateFrom(savingNotification));
                scope.Complete();
                return(relation);
            }
        }
Exemplo n.º 14
0
 /// <inheritdoc />
 public IEnumerable <IRelationType> GetAllRelationTypes(params int[] ids)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_relationTypeRepository.GetMany(ids));
     }
 }
Exemplo n.º 15
0
 public IEnumerable <IPartialView> GetPartialViews(params string[] names)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_partialViewRepository.GetMany(names));
     }
 }
Exemplo n.º 16
0
 /// <summary>
 ///     Gets a list of all <see cref="ITemplate" /> objects
 /// </summary>
 /// <returns>An enumerable list of <see cref="ITemplate" /> objects</returns>
 public IEnumerable <ITemplate> GetTemplates(int masterTemplateId)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_templateRepository.GetChildren(masterTemplateId).OrderBy(x => x.Name));
     }
 }
Exemplo n.º 17
0
 public IPartialView?GetPartialViewMacro(string path)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_partialViewMacroRepository.Get(path));
     }
 }
Exemplo n.º 18
0
 /// <summary>
 ///     Gets a <see cref="ITemplate" /> object by its identifier.
 /// </summary>
 /// <param name="id">The identifier of the template.</param>
 /// <returns>The <see cref="ITemplate" /> object matching the identifier, or null.</returns>
 public ITemplate?GetTemplate(int id)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_templateRepository.Get(id));
     }
 }
Exemplo n.º 19
0
    private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int?userId = null)
    {
        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            IPartialViewRepository repository  = GetPartialViewRepository(partialViewType);
            IPartialView?          partialView = repository.Get(path);
            if (partialView == null)
            {
                scope.Complete();
                return(true);
            }

            EventMessages eventMessages        = EventMessagesFactory.Get();
            var           deletingNotification = new PartialViewDeletingNotification(partialView, eventMessages);
            if (scope.Notifications.PublishCancelable(deletingNotification))
            {
                scope.Complete();
                return(false);
            }

            userId ??= Constants.Security.SuperUserId;
            repository.Delete(partialView);
            scope.Notifications.Publish(
                new PartialViewDeletedNotification(partialView, eventMessages).WithStateFrom(deletingNotification));
            Audit(AuditType.Delete, userId.Value, -1, partialViewType.ToString());

            scope.Complete();
        }

        return(true);
    }
Exemplo n.º 20
0
 /// <summary>
 ///     Gets the template descendants
 /// </summary>
 /// <param name="masterTemplateId"></param>
 /// <returns></returns>
 public IEnumerable <ITemplate> GetTemplateDescendants(int masterTemplateId)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_templateRepository.GetDescendants(masterTemplateId));
     }
 }
Exemplo n.º 21
0
 /// <inheritdoc />
 public Stream GetPartialViewFileContentStream(string filepath)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_partialViewRepository.GetFileContentStream(filepath));
     }
 }
Exemplo n.º 22
0
    /// <summary>
    ///     Saves a <see cref="Template" />
    /// </summary>
    /// <param name="template"><see cref="Template" /> to save</param>
    /// <param name="userId"></param>
    public void SaveTemplate(ITemplate template, int userId = Constants.Security.SuperUserId)
    {
        if (template == null)
        {
            throw new ArgumentNullException(nameof(template));
        }

        if (string.IsNullOrWhiteSpace(template.Name) || template.Name.Length > 255)
        {
            throw new InvalidOperationException(
                      "Name cannot be null, empty, contain only white-space characters or be more than 255 characters in length.");
        }

        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            EventMessages eventMessages      = EventMessagesFactory.Get();
            var           savingNotification = new TemplateSavingNotification(template, eventMessages);
            if (scope.Notifications.PublishCancelable(savingNotification))
            {
                scope.Complete();
                return;
            }

            _templateRepository.Save(template);

            scope.Notifications.Publish(
                new TemplateSavedNotification(template, eventMessages).WithStateFrom(savingNotification));

            Audit(AuditType.Save, userId, template.Id, UmbracoObjectTypes.Template.GetName());
            scope.Complete();
        }
    }
Exemplo n.º 23
0
    public override Task PerformExecuteAsync(object?state)
    {
        switch (_serverRegistrar.CurrentServerRole)
        {
        case ServerRole.Subscriber:
            _logger.LogDebug("Does not run on subscriber servers.");
            return(Task.CompletedTask);

        case ServerRole.Unknown:
            _logger.LogDebug("Does not run on servers with unknown role.");
            return(Task.CompletedTask);
        }

        // Ensure we do not run if not main domain, but do NOT lock it
        if (_mainDom.IsMainDom == false)
        {
            _logger.LogDebug("Does not run if not MainDom.");
            return(Task.CompletedTask);
        }

        // Ensure we use an explicit scope since we are running on a background thread.
        using (ICoreScope scope = _scopeProvider.CreateCoreScope())
            using (_profilingLogger.DebugDuration <LogScrubber>("Log scrubbing executing", "Log scrubbing complete"))
            {
                _auditService.CleanLogs((int)_settings.MaxLogAge.TotalMinutes);
                _ = scope.Complete();
            }

        return(Task.CompletedTask);
    }
Exemplo n.º 24
0
    /// <summary>
    ///     Saves a collection of <see cref="Template" /> objects
    /// </summary>
    /// <param name="templates">List of <see cref="Template" /> to save</param>
    /// <param name="userId">Optional id of the user</param>
    public void SaveTemplate(IEnumerable <ITemplate> templates, int userId = Constants.Security.SuperUserId)
    {
        ITemplate[] templatesA = templates.ToArray();
        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            EventMessages eventMessages      = EventMessagesFactory.Get();
            var           savingNotification = new TemplateSavingNotification(templatesA, eventMessages);
            if (scope.Notifications.PublishCancelable(savingNotification))
            {
                scope.Complete();
                return;
            }

            foreach (ITemplate template in templatesA)
            {
                _templateRepository.Save(template);
            }

            scope.Notifications.Publish(
                new TemplateSavedNotification(templatesA, eventMessages).WithStateFrom(savingNotification));

            Audit(AuditType.Save, userId, -1, UmbracoObjectTypes.Template.GetName());
            scope.Complete();
        }
    }
Exemplo n.º 25
0
 /// <inheritdoc />
 public long GetStylesheetFileSize(string filepath)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_stylesheetRepository.GetFileSize(filepath));
     }
 }
Exemplo n.º 26
0
    /// <summary>
    ///     Deletes a template by its alias
    /// </summary>
    /// <param name="alias">Alias of the <see cref="ITemplate" /> to delete</param>
    /// <param name="userId"></param>
    public void DeleteTemplate(string alias, int userId = Constants.Security.SuperUserId)
    {
        using (ICoreScope scope = ScopeProvider.CreateCoreScope())
        {
            ITemplate?template = _templateRepository.Get(alias);
            if (template == null)
            {
                scope.Complete();
                return;
            }

            EventMessages eventMessages        = EventMessagesFactory.Get();
            var           deletingNotification = new TemplateDeletingNotification(template, eventMessages);
            if (scope.Notifications.PublishCancelable(deletingNotification))
            {
                scope.Complete();
                return;
            }

            _templateRepository.Delete(template);

            scope.Notifications.Publish(
                new TemplateDeletedNotification(template, eventMessages).WithStateFrom(deletingNotification));

            Audit(AuditType.Delete, userId, template.Id, UmbracoObjectTypes.Template.GetName());
            scope.Complete();
        }
    }
Exemplo n.º 27
0
 /// <inheritdoc />
 public IScript?GetScript(string?name)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_scriptRepository.Get(name));
     }
 }
Exemplo n.º 28
0
 /// <inheritdoc />
 public IEnumerable <IStylesheet> GetStylesheets(params string[] paths)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_stylesheetRepository.GetMany(paths));
     }
 }
Exemplo n.º 29
0
        /// <inheritdoc />
        public void DeleteScript(string path, int?userId = null)
        {
            using (ICoreScope scope = ScopeProvider.CreateCoreScope())
            {
                IScript?script = _scriptRepository.Get(path);
                if (script == null)
                {
                    scope.Complete();
                    return;
                }

                EventMessages eventMessages        = EventMessagesFactory.Get();
                var           deletingNotification = new ScriptDeletingNotification(script, eventMessages);
                if (scope.Notifications.PublishCancelable(deletingNotification))
                {
                    scope.Complete();
                    return;
                }

                userId ??= Constants.Security.SuperUserId;
                _scriptRepository.Delete(script);
                scope.Notifications.Publish(new ScriptDeletedNotification(script, eventMessages).WithStateFrom(deletingNotification));

                Audit(AuditType.Delete, userId.Value, -1, "Script");
                scope.Complete();
            }
        }
Exemplo n.º 30
0
 /// <inheritdoc />
 public IEnumerable <IUmbracoEntity> GetPagedChildEntitiesByParentId(int id, long pageIndex, int pageSize, out long totalChildren, params UmbracoObjectTypes[] entityTypes)
 {
     using (ICoreScope scope = ScopeProvider.CreateCoreScope(autoComplete: true))
     {
         return(_relationRepository.GetPagedChildEntitiesByParentId(id, pageIndex, pageSize, out totalChildren, entityTypes.Select(x => x.GetGuid()).ToArray()));
     }
 }