Пример #1
0
        public CreateCommand(string descricao, int[] idCategorias)
        {
            Descricao    = descricao;
            IdCategorias = idCategorias;

            var validator = new CreateCommandValidator();

            validation = validator.Validate(this);
        }
Пример #2
0
        public void CreateCommandValidatorFailsIfProjectAlreadyExists()
        {
            var mockReservedDirectories = new Mock <IReservedDirectories>();

            var mockFileSystem = new MockFileSystem();

            const string projectName         = "MyUnitTestProject";
            const string outputDirectoryName = "public";

            string projectRootPath = mockFileSystem.Path.Combine(
                Environment.CurrentDirectory,
                projectName);

            // Simulate the `Create` command already having been successfully run by
            // adding a directory with the same project name.
            mockFileSystem.AddDirectory(projectRootPath);

            var command = new CreateCommand
            {
                ProjectName         = projectName,
                OutputDirectoryName = outputDirectoryName
            };

            var validator = new CreateCommandValidator(
                mockFileSystem,
                mockReservedDirectories.Object);

            var validationResult = validator.Validate(command);

            string expectedErrorMessage      = $"A Sculptor project with the name `{projectName}` already exists in the provided directory";
            bool   hasExpectedNumberOfErrors = validationResult.Errors.Count() == 1;
            bool   hasExpectedErrorMessage   = validationResult
                                               .Errors
                                               .Any(x => x.ErrorMessage == expectedErrorMessage);

            Assert.Multiple(() =>
            {
                Assert.True(hasExpectedNumberOfErrors);
                Assert.True(hasExpectedErrorMessage);
            });
        }
Пример #3
0
        public void CreateCommandValidatorFailsForInvalidCommand(
            string projectName,
            string outputDirectoryName,
            int expectedNumberOfErrors)
        {
            var mockReservedDirectories = new Mock <IReservedDirectories>();

            mockReservedDirectories
            .Setup(x => x.IsDirectoryNameReserved(It.IsAny <string>()))
            .Returns(true);

            var mockFileSystem = new MockFileSystem();

            var command = new CreateCommand
            {
                ProjectName         = projectName,
                OutputDirectoryName = outputDirectoryName
            };

            var validator = new CreateCommandValidator(
                mockFileSystem,
                mockReservedDirectories.Object);

            var validationResult = validator.Validate(command);

            const string expectedErrorMessage      = "Invalid path character(s) provided for:";
            bool         hasExpectedNumberOfErrors = validationResult.Errors.Count() == expectedNumberOfErrors;
            bool         hasExpectedErrorMessage   = validationResult
                                                     .Errors
                                                     .Any(x => x.ErrorMessage.StartsWith(
                                                              expectedErrorMessage,
                                                              StringComparison.Ordinal));

            Assert.Multiple(() =>
            {
                Assert.True(hasExpectedNumberOfErrors);
                Assert.True(hasExpectedErrorMessage);
            });
        }
Пример #4
0
        public void CreateCommandValidatorFailsIfOutputDirectoryMatchesReservedName()
        {
            var mockReservedDirectories = new Mock <IReservedDirectories>();

            mockReservedDirectories
            .Setup(x => x.IsDirectoryNameReserved(It.IsAny <string>()))
            .Returns(true);

            var mockFileSystem = new MockFileSystem();

            mockFileSystem.AddDirectory(Environment.CurrentDirectory);

            var command = new CreateCommand
            {
                ProjectName = "MyUnitTestProject",
                // It doesn't matter what this is set to as we have stubbed the
                // `IsDirectoryNameReserved` method above to always return true.
                OutputDirectoryName = "reserved-for-internal-use"
            };

            var validator = new CreateCommandValidator(
                mockFileSystem,
                mockReservedDirectories.Object);

            var validationResult = validator.Validate(command);

            const string expectedErrorMessage = "The value provided for: `output` is reserved for internal use by Sculptor";

            bool hasExpectedNumberOfErrors = validationResult.Errors.Count() == 1;
            bool hasExpectedErrorMessage   = validationResult
                                             .Errors
                                             .Any(x => x.ErrorMessage == expectedErrorMessage);

            Assert.Multiple(() =>
            {
                Assert.True(hasExpectedNumberOfErrors);
                Assert.True(hasExpectedErrorMessage);
            });
        }
Пример #5
0
        public async Task <CreateResult> Handle(_TCreateCommand command,
                                                CancellationToken cancellationToken)
        {
            Logger.LogInformation(AppLogEvent.HandleRequest,
                                  "Handle Geo Create Command. Command={Command}",
                                  command.ToDictionary());

            if (command is null)
            {
                Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                  "Handle Geo Create Command got empty command");
                return(ErrorResult("Empty Geo Create Command"));
            }

            try
            {
                var validator        = new CreateCommandValidator <_TCreateCommand>();
                var validationResult = await validator.ValidateAsync(command)
                                       .ConfigureAwait(false);

                if (!validationResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestValidationError,
                                      "Validation command error. Command={Command}. " +
                                      "Error={Error}.",
                                      command.ToDictionary(), validationResult.Errors);
                    return(ErrorResult(validationResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                // Get Actor for current user by user name
                Actor createdBy       = null;
                var   currentUserName = command.CurrentPrincipal?
                                        .Identity?
                                        .Name;
                var creatorResponse = await Mediator
                                      .Send(new DbGetActorByNameRequest(currentUserName))
                                      .ConfigureAwait(false);

                if (creatorResponse.Success)
                {
                    createdBy = creatorResponse.Entity;
                }

                var entity = new _TEntity()
                {
                    CreatedAt   = DateTime.UtcNow,
                    CreatedBy   = createdBy,
                    Description = command.Description,
                    IsArchived  = command.IsArchived,
                    Title       = command.Title,
                    GeoJson     = command.GeoJson,
                    ProjectId   = command.ProjectId
                };

                var validatorBeforeSave        = new BeforeSaveValidator <_TEntity>();
                var validationBeforeSaveResult = await validatorBeforeSave
                                                 .ValidateAsync(entity).ConfigureAwait(false);

                if (!validationBeforeSaveResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestNotValid,
                                      "Geo validation error. Entity={Entity}. " +
                                      "Error={Error}.",
                                      entity.ToDictionary(),
                                      validationBeforeSaveResult.Errors);
                    return(ErrorResult(validationBeforeSaveResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                // Get project role of current actor
                var projectResponse = await Mediator
                                      .Send(new DbGetEntityByIdRequest <Project>(entity.ProjectId))
                                      .ConfigureAwait(false);

                ActorRole currentProjectRole = null;
                if (projectResponse.Success)
                {
                    projectResponse.Entity.ProjectActorRoles
                    .TryGetValue(createdBy.Id, out currentProjectRole);
                }

                var checkPermissionResult = await CheckPermission(entity,
                                                                  createdBy, currentProjectRole)
                                            .ConfigureAwait(false);

                if (!checkPermissionResult.Success)
                {
                    Logger.LogWarning(AppLogEvent.SecurityNotPassed,
                                      "Geo Create permission error. " +
                                      "Entity={Entity}. CurrentActor={CurrentActor}." +
                                      "CurrentActorProjectRole={CurrentActorProjectRole}." +
                                      " Error={Error}.",
                                      entity.ToDictionary(), createdBy?.ToDictionary(),
                                      currentProjectRole.Name, checkPermissionResult.Errors);
                    return(checkPermissionResult);
                }

                return(await Mediator
                       .Send(new DbCreateCommand <_TEntity>(entity))
                       .ConfigureAwait(false));
            }
            catch (Exception e)
            {
                Logger.LogError(AppLogEvent.HandleErrorResponse, e,
                                "Call repository exception");
                return(ErrorResult("Not found"));
            }
        }
Пример #6
0
        public async Task <CreateResult> Handle(_TCreateCommand command,
                                                CancellationToken cancellationToken)
        {
            Logger.LogInformation(AppLogEvent.HandleRequest,
                                  "Handle Project Create Command. Command={Command}",
                                  command.ToDictionary());

            if (command is null)
            {
                Logger.LogWarning(AppLogEvent.HandleArgumentError,
                                  "Handle Create Project Command got empty command");
                return(ErrorResult("Empty Project Create command"));
            }

            try
            {
                var validator        = new CreateCommandValidator <_TCreateCommand>();
                var validationResult = await validator.ValidateAsync(command)
                                       .ConfigureAwait(false);

                if (!validationResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestValidationError,
                                      "Validation command error. Command={Command}. " +
                                      "Error={Error}.",
                                      command.ToDictionary(), validationResult.Errors);
                    return(ErrorResult(validationResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                // Get Actor for current user by user name
                Actor createdBy       = null;
                var   currentUserName = command.CurrentPrincipal?
                                        .Identity?
                                        .Name;
                var creatorResponse = await Mediator
                                      .Send(new DbGetActorByNameRequest(currentUserName))
                                      .ConfigureAwait(false);

                if (creatorResponse.Success)
                {
                    createdBy = creatorResponse.Entity;
                    //TODO Add to all create permission validation CreatedBy not null check
                }

                var entity = new _TEntity()
                {
                    CreatedAt   = DateTime.UtcNow,
                    CreatedBy   = createdBy,
                    Description = command.Description,
                    IsArchived  = command.IsArchived,
                    Title       = command.Title,
                    IsMap       = command.IsMap,
                    MapProvider = command.MapProvider,
                    ShowMap     = command.ShowMap
                };
                entity.Layers.AddRange(command.Layers);
                command.MapParameters
                .ToList()
                .ForEach(x => entity.MapParameters.TryAdd(x.Key, x.Value));
                var checkingActors = command.ProjectActorRoles.Keys;
                if (checkingActors.Count > 0)
                {
                    var actorIdsFromRepository = await GetActorIds
                                                     (checkingActors).ConfigureAwait(false);

                    foreach (var item in command.ProjectActorRoles)
                    {
                        if (!String.IsNullOrWhiteSpace(item.Key) &&
                            actorIdsFromRepository.Contains(item.Key))
                        {
                            entity.ProjectActorRoles.Add(item.Key, item.Value);
                        }
                    }
                }

                var validatorBeforeSave        = new BeforeSaveValidator <_TEntity>();
                var validationBeforeSaveResult = await validatorBeforeSave
                                                 .ValidateAsync(entity).ConfigureAwait(false);

                if (!validationBeforeSaveResult.IsValid)
                {
                    Logger.LogWarning(AppLogEvent.RequestNotValid,
                                      "Project validation error. Entity={Entity}. " +
                                      "Error={Error}.",
                                      entity.ToDictionary(),
                                      validationBeforeSaveResult.Errors);
                    return(ErrorResult(validationBeforeSaveResult.Errors
                                       .Select(x => x.ErrorMessage)));
                }

                var checkPermissionResult = await CheckPermission(entity,
                                                                  createdBy).ConfigureAwait(false);

                if (!checkPermissionResult.Success)
                {
                    Logger.LogWarning(AppLogEvent.SecurityNotPassed,
                                      "Project Create permission error. " +
                                      "Entity={Entity}. CurrentActor={CurrentActor}." +
                                      " Error={Error}.",
                                      entity.ToDictionary(), createdBy?.ToDictionary(),
                                      checkPermissionResult.Errors);
                    return(checkPermissionResult);
                }

                return(await Mediator.Send
                           (new DbCreateCommand <_TEntity>(entity))
                       .ConfigureAwait(false));
            }
            catch (Exception e)
            {
                Logger.LogError(AppLogEvent.HandleErrorResponse, e,
                                "Call repository exception");
                return(ErrorResult("Not found"));
            }
        }
Пример #7
0
 public void TestInitialize()
 {
     _validator = new CreateCommandValidator();
 }