private async Task ValidateIsUniqueAsync( UpdateUserCommand command, IUserAreaDefinition userArea, IExecutionContext executionContext ) { var query = new IsUsernameUniqueQuery() { UserId = command.UserId, UserAreaCode = userArea.UserAreaCode }; if (userArea.UseEmailAsUsername) { query.Username = command.Email?.Trim(); } else { query.Username = command.Username.Trim(); } var isUnique = await _queryExecutor.ExecuteAsync(query, executionContext); if (!isUnique) { if (userArea.UseEmailAsUsername) { throw ValidationErrorException.CreateWithProperties("This email is already registered", "Email"); } else { throw ValidationErrorException.CreateWithProperties("This username is already registered", "Username"); } } }
private async Task ValidatePasswordAsync( IUserAreaDefinition userArea, User user, AddUserCommand command, IExecutionContext executionContext ) { var isPasswordEmpty = string.IsNullOrWhiteSpace(command.Password); if (userArea.AllowPasswordSignIn && isPasswordEmpty) { throw ValidationErrorException.CreateWithProperties("Password field is required", nameof(command.Password)); } else if (!userArea.AllowPasswordSignIn && !isPasswordEmpty) { throw ValidationErrorException.CreateWithProperties("Password field should be empty because the specified user area does not use passwords", nameof(command.Password)); } else if (!userArea.AllowPasswordSignIn) { return; } var context = NewPasswordValidationContext.MapFromUser(user); context.Password = command.Password; context.PropertyName = nameof(command.Password); context.ExecutionContext = executionContext; await _newPasswordValidationService.ValidateAsync(context); }
/// <summary> /// Perform some additional command validation that we can't do using data /// annotations. /// </summary> private void ValidateCommand(AddUserCommand command, IUserAreaDefinition userArea) { // Password var isPasswordEmpty = string.IsNullOrWhiteSpace(command.Password); if (userArea.AllowPasswordLogin && isPasswordEmpty && !command.GeneratePassword) { throw ValidationErrorException.CreateWithProperties("Password field is required", "Password"); } else if (!userArea.AllowPasswordLogin && !isPasswordEmpty) { throw ValidationErrorException.CreateWithProperties("Password field should be empty because the specified user area does not use passwords", "Password"); } // Email if (userArea.UseEmailAsUsername && string.IsNullOrEmpty(command.Email)) { throw ValidationErrorException.CreateWithProperties("Email field is required.", "Email"); } // Username if (userArea.UseEmailAsUsername && !string.IsNullOrEmpty(command.Username)) { throw ValidationErrorException.CreateWithProperties("Username field should be empty becuase the specified user area uses the email as the username.", "Password"); } else if (!userArea.UseEmailAsUsername && string.IsNullOrWhiteSpace(command.Username)) { throw ValidationErrorException.CreateWithProperties("Username field is required", "Username"); } }
private static void ValidateUserAccountExists(User user) { if (user == null) { throw ValidationErrorException.CreateWithProperties("Account not found.", "Username"); } }
private void ValidateIsUnique(bool isUnique) { if (!isUnique) { throw ValidationErrorException.CreateWithProperties("A role with this title already exists", "Title"); } }
public async Task ExecuteAsync(AddDocumentAssetCommand command, IExecutionContext executionContext) { var documentAsset = new DocumentAsset(); documentAsset.Title = command.Title; documentAsset.Description = command.Description ?? string.Empty; documentAsset.FileName = FilePathHelper.CleanFileName(command.Title); documentAsset.VerificationToken = _randomStringGenerator.Generate(6); if (string.IsNullOrWhiteSpace(documentAsset.FileName)) { throw ValidationErrorException.CreateWithProperties("Document title is empty or does not contain any safe file path characters.", nameof(command.Title)); } _entityTagHelper.UpdateTags(documentAsset.DocumentAssetTags, command.Tags, executionContext); _entityAuditHelper.SetCreated(documentAsset, executionContext); documentAsset.FileUpdateDate = executionContext.ExecutionDate; using (var scope = _transactionScopeFactory.Create(_dbContext)) { _dbContext.DocumentAssets.Add(documentAsset); await _documentAssetCommandHelper.SaveFile(command.File, documentAsset); command.OutputDocumentAssetId = documentAsset.DocumentAssetId; scope.QueueCompletionTask(() => OnTransactionComplete(documentAsset)); await scope.CompleteAsync(); } }
private static void ValidateNotRootDirectory(PageDirectory pageDirectory) { if (!pageDirectory.ParentPageDirectoryId.HasValue) { throw ValidationErrorException.CreateWithProperties("Cannot delete the root page directory.", nameof(pageDirectory.PageDirectoryId)); } }
private void ValidateParentDirectory(UpdatePageDirectoryUrlCommand command, ICollection <int> affectedDirectoryIds) { if (affectedDirectoryIds.Contains(command.ParentPageDirectoryId)) { throw ValidationErrorException.CreateWithProperties("The parent directory cannot be a child of this directory.", nameof(command.ParentPageDirectoryId)); } }
private async Task <PageTemplate> GetTemplateAsync(AddPageCommand command) { var template = await _dbContext .PageTemplates .SingleOrDefaultAsync(t => t.PageTemplateId == command.PageTemplateId); if (template == null) { throw ValidationErrorException.CreateWithProperties("Template not found.", nameof(command.PageTemplateId)); } if (template.IsArchived) { throw ValidationErrorException.CreateWithProperties("You cannot use an archived template to create a new page.", nameof(command.PageTemplateId)); } if (command.PageType == PageType.CustomEntityDetails) { if (!template.IsCustomEntityTemplate()) { throw ValidationErrorException.CreateWithProperties("Template does not support custom entities.", nameof(command.PageTemplateId)); } } else if (template.IsCustomEntityTemplate()) { throw ValidationErrorException.CreateWithProperties("A custom entity template template can only be used for custom entity details pages.", nameof(command.PageTemplateId)); } return(template); }
private void ValidateRoleIsInUserArea(IUserAreaDefinition userAreaDefinition, Role role) { if (role != null && role.UserAreaCode != userAreaDefinition.UserAreaCode) { throw ValidationErrorException.CreateWithProperties($"This role is not in the {userAreaDefinition.Name} user area.", nameof(role.RoleId)); } }
private static void ValidateRole(List <Role> existingRoles, IRoleDefinition roleDefinition) { if (string.IsNullOrWhiteSpace(roleDefinition.Title)) { throw ValidationErrorException.CreateWithProperties("Role title cannot be empty", nameof(IRoleDefinition.Title)); } if (string.IsNullOrWhiteSpace(roleDefinition.RoleCode)) { throw ValidationErrorException.CreateWithProperties("Role RoleCode cannot be empty", nameof(IRoleDefinition.RoleCode)); } if (roleDefinition.RoleCode.Length != 3) { throw ValidationErrorException.CreateWithProperties("Role RoleCode must be 3 characters in length", nameof(IRoleDefinition.RoleCode)); } if (existingRoles .Any(r => r.Title.Equals(roleDefinition.Title?.Trim(), StringComparison.OrdinalIgnoreCase) && r.UserAreaCode == roleDefinition.UserAreaCode) ) { throw new UniqueConstraintViolationException($"A role with the title '{ roleDefinition.Title }' already exists", nameof(Role.Title)); } }
private async Task MapPageAsync(UpdatePageUrlCommand command, IExecutionContext executionContext, Page page) { if (page.PageTypeId == (int)PageType.CustomEntityDetails) { var rule = await _queryExecutor.ExecuteAsync(new GetCustomEntityRoutingRuleByRouteFormatQuery(command.CustomEntityRoutingRule), executionContext); if (rule == null) { throw ValidationErrorException.CreateWithProperties("Routing rule not found", nameof(command.CustomEntityRoutingRule)); } var customEntityDefinition = await _queryExecutor.ExecuteAsync(new GetCustomEntityDefinitionSummaryByCodeQuery(page.CustomEntityDefinitionCode), executionContext); EntityNotFoundException.ThrowIfNull(customEntityDefinition, page.CustomEntityDefinitionCode); if (customEntityDefinition.ForceUrlSlugUniqueness && !rule.RequiresUniqueUrlSlug) { throw ValidationErrorException.CreateWithProperties("Ths routing rule requires a unique url slug, but the selected custom entity does not enforce url slug uniqueness", nameof(command.CustomEntityRoutingRule)); } page.UrlPath = rule.RouteFormat; } else { page.UrlPath = command.UrlPath; } page.PageDirectoryId = command.PageDirectoryId; page.LocaleId = command.LocaleId; }
private async Task UpdateEmailAsync( UpdateCurrentUserAccountCommand command, int userId, User user, IExecutionContext executionContext ) { var userArea = _userAreaRepository.GetByCode(user.UserAreaCode); var newEmail = command.Email?.Trim(); if (userArea.UseEmailAsUsername && user.Username != newEmail) { var uniqueQuery = new IsUsernameUniqueQuery() { Username = newEmail, UserId = userId, UserAreaCode = CofoundryAdminUserArea.AreaCode }; if (!await _queryExecutor.ExecuteAsync(uniqueQuery, executionContext)) { throw ValidationErrorException.CreateWithProperties("This email is already registered", "Email"); } user.Username = newEmail; } user.Email = newEmail; }
private async Task ValidateUrlPropertiesAllowedToChange(UpdatePageDirectoryCommand command, PageDirectory pageDirectory) { var props = GetChangedPathProperties(command, pageDirectory); if (props.Any() && await HasDependencies(pageDirectory)) { throw ValidationErrorException.CreateWithProperties("This directory is in use and the url cannot be changed", props.First()); } }
/// <summary> /// Validates a file's extension and mime type, throwing a validation /// exception if they are invalid. Use AssetFilesSettings to configure /// the validation behavior. /// </summary> /// <param name="fileNameOrFileExtension"> /// The file name or file extension, with or without the leading dot. The /// check is case-insensitive. /// </param> /// <param name="mimeType"> /// Mime type to check. The check is case-insensitive. /// </param> /// <param name="propertyName"> /// The name of the model property being validated, used in the validation exception. /// </param> public virtual void ValidateAndThrow(string fileNameOrFileExtension, string mimeType, string propertyName) { var error = Validate(fileNameOrFileExtension, mimeType, propertyName).FirstOrDefault(); if (error != null) { throw ValidationErrorException.CreateWithProperties(error.ErrorMessage, error.MemberNames?.ToArray()); } }
private async Task <CustomEntityDefinitionSummary> GetCustomEntityDefinitionAsync(string customEntityDefinitionCode, IExecutionContext executionContext) { var definition = await _queryExecutor.ExecuteAsync(new GetCustomEntityDefinitionSummaryByCodeQuery(customEntityDefinitionCode), executionContext); if (definition == null) { throw ValidationErrorException.CreateWithProperties("Custom entity defintion does not exists.", nameof(definition.CustomEntityDefinitionCode)); } return(definition); }
/// <summary> /// A partir de la excepción de validación, obtiene el mensaje amigable de validación /// Si no encuentra el mensaje amigable, regresa un código de error /// </summary> /// <param name="error"></param> /// <returns></returns> public string TranspileFriendlyMessage(ValidationErrorException error) { var errorCode = $"{string.Join("-", error.Properties)}:{error.Type.ToString()}".ToUpper(); var errorTranslationExist = translationTable.TryGetValue(errorCode, out var errorMessage); return(errorTranslationExist ? errorMessage : errorCode); }
private void throwError(RestClientException clientException) { if (clientException.Response.StatusCode == (HttpStatusCode)422) { var validationError = new ValidationErrorException("Validation has failed", clientException); validationError.ErrorDetails = StringHelper.getJsonAsDictionary((new StreamReader(clientException.Response.GetResponseStream())).ReadToEnd()); throw validationError; } else { throw clientException; } }
private async Task <PageDirectory> GetPageDirectoryAsync(int pageDirectoryId) { var pageDirectory = await _dbContext .PageDirectories .FilterById(pageDirectoryId) .SingleOrDefaultAsync(); if (pageDirectory == null) { throw ValidationErrorException.CreateWithProperties("The selected page directory does not exist.", nameof(pageDirectory.PageDirectoryId)); } return(pageDirectory); }
private void ValidateFileType(DocumentAsset file) { // TODO: this i think should be wrapped in a IAssetFileValidator service // Asset file settings to disable checking // configurable blacklist or whitelist? if (DangerousFileConstants.DangerousFileExtensions.Contains(file.FileExtension)) { throw ValidationErrorException.CreateWithProperties("The type of file you're trying to upload isn't allowed.", "File"); } else if (string.IsNullOrWhiteSpace(file.ContentType) || DangerousFileConstants.DangerousMimeTypes.Contains(file.ContentType)) { throw ValidationErrorException.CreateWithProperties("The type of file you're trying to upload isn't allowed.", "File"); } }
private void UpdatePassword(UpdateCurrentUserPasswordCommand command, IExecutionContext executionContext, User user) { EntityNotFoundException.ThrowIfNull(user, executionContext.UserContext.UserId); var userArea = _userAreaRepository.GetByCode(user.UserAreaCode); _passwordUpdateCommandHelper.ValidateUserArea(userArea); if (!_userAuthenticationHelper.IsPasswordCorrect(user, command.OldPassword)) { throw ValidationErrorException.CreateWithProperties("Incorrect password", "OldPassword"); } _passwordUpdateCommandHelper.UpdatePassword(command.NewPassword, user, executionContext); }
private void ValidateCommand(UpdateUserCommand command, IUserAreaDefinition userArea) { // Email if (userArea.UseEmailAsUsername && string.IsNullOrEmpty(command.Email)) { throw ValidationErrorException.CreateWithProperties("Email field is required.", "Email"); } // Username if (!userArea.UseEmailAsUsername && string.IsNullOrWhiteSpace(command.Username)) { throw ValidationErrorException.CreateWithProperties("Username field is required", "Username"); } }
private void ValidateIsUnique(bool isUnique, IUserAreaDefinition userArea) { if (!isUnique) { if (userArea.UseEmailAsUsername) { throw ValidationErrorException.CreateWithProperties("This email is already registered", "Email"); } else { throw ValidationErrorException.CreateWithProperties("This username is already registered", "Username"); } } }
private async Task <PageDirectory> GetPageDirectoryAsync(int pageDirectoryId) { var pageDirectories = await _dbContext .PageDirectories .ToDictionaryAsync(w => w.PageDirectoryId); var pageDirectory = pageDirectories.GetOrDefault(pageDirectoryId); if (pageDirectory == null) { throw ValidationErrorException.CreateWithProperties("The selected page directory does not exist.", nameof(pageDirectory.PageDirectoryId)); } return(pageDirectory); }
public async Task ExecuteAsync(UpdateDocumentAssetCommand command, IExecutionContext executionContext) { bool hasNewFile = command.File != null; var documentAsset = await _dbContext .DocumentAssets .Include(a => a.DocumentAssetTags) .ThenInclude(a => a.Tag) .FilterById(command.DocumentAssetId) .SingleOrDefaultAsync(); documentAsset.Title = command.Title; documentAsset.Description = command.Description ?? string.Empty; documentAsset.FileName = FilePathHelper.CleanFileName(command.Title); if (string.IsNullOrWhiteSpace(documentAsset.FileName)) { throw ValidationErrorException.CreateWithProperties("Document title is empty or does not contain any safe file path characters.", nameof(command.Title)); } _entityTagHelper.UpdateTags(documentAsset.DocumentAssetTags, command.Tags, executionContext); _entityAuditHelper.SetUpdated(documentAsset, executionContext); using (var scope = _transactionScopeFactory.Create(_dbContext)) { if (hasNewFile) { var deleteOldFileCommand = new QueueAssetFileDeletionCommand() { EntityDefinitionCode = DocumentAssetEntityDefinition.DefinitionCode, FileNameOnDisk = documentAsset.FileNameOnDisk, FileExtension = documentAsset.FileExtension }; await _commandExecutor.ExecuteAsync(deleteOldFileCommand); await _documentAssetCommandHelper.SaveFile(command.File, documentAsset); documentAsset.FileUpdateDate = executionContext.ExecutionDate; } await _dbContext.SaveChangesAsync(); scope.QueueCompletionTask(() => OnTransactionComplete(documentAsset, hasNewFile)); await scope.CompleteAsync(); } }
private void ValidateCommand(AddCustomEntityCommand command, CustomEntityDefinitionSummary definition) { if (definition.AutoGenerateUrlSlug) { command.UrlSlug = SlugFormatter.ToSlug(command.Title); } else { command.UrlSlug = SlugFormatter.ToSlug(command.UrlSlug); } if (command.LocaleId.HasValue && !definition.HasLocale) { throw ValidationErrorException.CreateWithProperties(definition.NamePlural + " cannot be assigned locales", "LocaleId"); } }
/// <summary> /// Emite una respuesta en JSON de un error debido a validación /// </summary> /// <param name="response">Respuesta que se escribirá</param> /// <param name="error">Error de validación arrojado</param> /// <param name="errorMessageTranspiler">Transpilador de mensajes amigables a partir de errores</param> /// <returns></returns> private static async Task EmitValidationErrorResponse( HttpResponse response, ValidationErrorException error, ValidationErrorMessageTranspiler errorMessageTranspiler ) { response.StatusCode = (int)HttpStatusCode.BadRequest; var errorMessage = errorMessageTranspiler.TranspileFriendlyMessage(error); await response.WriteAsync( JsonConvert.SerializeObject( new ValidationErrorResponse(errorMessage) ) ); }
public void Map_Should_ReturnProblemDetails_WithValidationErrors_ForValidationErrorException() { var exception = new ValidationErrorException <string>("param", new[] { "error1", "error1" }); var mapper = TestHelper.CreateProblemDetailsExceptionMapper <Exception>(true); var actionResult = mapper.Map(exception, new DefaultHttpContext()); actionResult.Should().BeOfType <ProblemDetailsResult>(); var problemDetailsResult = (ProblemDetailsResult)actionResult; problemDetailsResult.Value.ShouldNotBeNull(HttpStatusCode.BadRequest); problemDetailsResult.Value.Instance.Should().Be(ResponseStatusCodeLink.BadRequest); var result = problemDetailsResult.Value.TryGetErrors(out var errors); result.Should().BeTrue(); errors.Should().NotBeNull(); errors.Should().HaveCount(1); }
private void ValidateImage( string propertyName, Image <Rgba32> imageFile, IImageFormat imageFormat ) { if (imageFormat == null) { throw ValidationErrorException.CreateWithProperties("Unable to determine image type.", propertyName); } if (imageFile.Width > _imageAssetsSettings.MaxUploadWidth) { throw ValidationErrorException.CreateWithProperties($"Image exceeds the maximum permitted width of {_imageAssetsSettings.MaxUploadWidth} pixels.", propertyName); } if (imageFile.Height > _imageAssetsSettings.MaxUploadHeight) { throw ValidationErrorException.CreateWithProperties($"Image exceeds the maximum permitted height of {_imageAssetsSettings.MaxUploadHeight} pixels.", propertyName); } }
public async Task ExecuteAsync(AddPageDraftVersionCommand command, IExecutionContext executionContext) { int newVersionId; try { newVersionId = await _pageStoredProcedures.AddDraftAsync( command.PageId, command.CopyFromPageVersionId, executionContext.ExecutionDate, executionContext.UserContext.UserId.Value); } catch (StoredProcedureExecutionException ex) when(ex.ErrorNumber == StoredProcedureErrorNumbers.Page_AddDraft.DraftAlreadyExists) { throw ValidationErrorException.CreateWithProperties("A draft cannot be created because this page already has one.", nameof(command.PageId)); } await _transactionScopeFactory.QueueCompletionTaskAsync(_dbContext, () => OnTransactionComplete(command, newVersionId)); command.OutputPageVersionId = newVersionId; }