Esempio n. 1
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var model = context.GetArgument <Account>();

            validationContext.When(model, m => m.Email)
            .IsNotEmail()
            .AddValidationDetail("Это не email =/");

            validationContext.When(model, m => m.Password)
            .IsNullOrWhitespace()
            .AddValidationDetail("Укажите ваш пароль");

            if (validationContext.IsValid(model, m => m.Email) && validationContext.IsValid(model, m => m.Password))
            {
                var account = await databaseContext
                              .Accounts
                              .FirstOrDefaultAsync(x => x.Email == model.Email);

                var accountExists = account != null &&
                                    passwordHasher.VerifyHashedPassword(
                    account,
                    account.Password,
                    model.Password) == PasswordVerificationResult.Success;

                validationContext.When()
                .IsNot(() => accountExists)
                .AddValidationDetail("Email/пароль неверный, либо аккаунт не существует");
            }
        }
Esempio n. 2
0
        public void IsValid_InnerPath_InnerValidationContext()
        {
            var withPrefix = validationContext.CreateScope("path");

            withPrefix.When("key", "value").AddValidationDetail("Error");

            Assert.False(withPrefix.IsValid("key"));
            Assert.False(validationContext.IsValid("path.key"));

            Assert.True(validationContext.IsValid("key"));
        }
Esempio n. 3
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Column>();

            var columnExists = await databaseContext
                               .Columns
                               .Include(x => x.Board)
                               .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                               .AnyAsync(x => x.Id == model.Id);

            validationContext.When()
            .IsNot(() => columnExists)
            .AddValidationDetail("Колонка не существует");

            if (validationContext.IsValid())
            {
                var hasColumns = await databaseContext
                                 .Columns
                                 .Where(x => x.Id == model.Id)
                                 .Where(x => x.Cards.Any())
                                 .AnyAsync();

                validationContext.When()
                .Is(() => hasColumns)
                .AddValidationDetail("Колонка содержит карточки");
            }
        }
Esempio n. 4
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Column>();

            var boardExists = await databaseContext
                              .Boards
                              .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                              .AnyAsync(x => x.Id == model.BoardId);

            validationContext.When(model, m => m.BoardId)
            .IsNot(() => boardExists)
            .AddValidationDetail("Доска не найдена");

            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Имя колонки не указано");

            if (validationContext.IsValid(model, m => m.Name))
            {
                var columnExists = await databaseContext
                                   .Columns
                                   .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                                   .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => columnExists)
                .AddValidationDetail("Колонка с таким именем уже сущетсвует");
            }
        }
Esempio n. 5
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var model = context.GetArgument <Organization>();

            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Задайте имя организации");

            if (validationContext.IsValid(model, m => m.Name))
            {
                var organizationNameExists = await databaseContext
                                             .Organizations
                                             .AnyAsync(organization => organization.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => organizationNameExists)
                .AddValidationDetail("Имя организации уже используется");
            }

            validationContext.When(model, m => m.Accounts)
            .IsEmpty()
            .AddValidationDetail("Создайте хотя-бы один аккаунт");

            for (var index = 0; index < model.Accounts.Count; index++)
            {
                var account = model.Accounts[index];

                using (var scope = validationContext.CreateScope(model, m => m.Accounts[index]))
                {
                    await accountValidation.ValidateAccount(scope, account);
                }
            }
        }
Esempio n. 6
0
 /// <summary>
 ///   If validation context is not valid, throws <see cref="ValidationContextException" />
 /// </summary>
 public static void EnsureIsValid(this IValidationContext validationContext, params string[] validationParts)
 {
     if (!validationContext.IsValid(validationParts))
     {
         throw new ValidationContextException(validationContext);
     }
 }
 /// <summary>
 ///   Checks validation context is not valid
 /// </summary>
 public static bool IsNotValid <TModel>(
     this IValidationContext validationContext,
     TModel model,
     params Expression <Func <TModel, object> >[] expressions)
 {
     return(!validationContext.IsValid(model, expressions));
 }
 /// <summary>
 ///   Ensures that validation context has no details with greater or equal severity than
 ///   ValidationContext.ValidationSeverity
 /// </summary>
 /// <exception cref="ValidationContextException">Throws when any detail has greater or equal severity</exception>
 public static void EnsureIsValid <TModel>(
     this IValidationContext validationContext,
     TModel model,
     params Expression <Func <TModel, object> >[] expressions)
 {
     if (!validationContext.IsValid(model, expressions))
     {
         throw new ValidationContextException(validationContext);
     }
 }
Esempio n. 9
0
        public async Task ValidateCardName(IValidationContext validationContext, Card card, Card model, Guid accountId)
        {
            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Укажите название карточки");

            if (validationContext.IsValid(model, m => m.Name) && validationContext.IsValid(model, m => m.Id))
            {
                var cardNameExists = await databaseContext.Boards
                                     .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                                     .Where(x => x.Columns.Any(c => c.Id == card.ColumnId))
                                     .SelectMany(x => x.Columns)
                                     .SelectMany(x => x.Cards)
                                     .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => cardNameExists)
                .AddValidationDetail("Карточка с таким названием уже существует");
            }
        }
        /// <summary>
        ///   Checks validation context for any detail with greater or equal severity for specified expression
        /// </summary>
        public static bool IsValid <TModel>(
            this IValidationContext validationContext,
            TModel model,
            params Expression <Func <TModel, object> >[] expressions)
        {
            var serviceProvider    = (IServiceProvider)validationContext;
            var validationResolver = serviceProvider.GetRequiredService <IValidationPathResolver>();

            var validationParts = expressions.Select(e => validationResolver.FromExpression(e.Body)).ToArray();

            return(validationContext.IsValid(validationParts));
        }
Esempio n. 11
0
        public IActionResult CreateOrder([FromBody] ExampleOrderModel model)
        {
            model.Save(/*databaseContext, */ validationContext);

            if (validationContext.IsValid())
            {
                // databaseContext.SaveChanges();
                return(Ok(new { Payload = model }));
            }

            return(BadRequest(new { validationContext.ValidationDetails }));
        }
Esempio n. 12
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Column>();

            var columnExists = await databaseContext
                               .Columns
                               .Include(x => x.Board)
                               .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                               .AnyAsync(x => x.Id == model.Id);

            validationContext.When(model, m => m.Id)
            .IsNot(() => columnExists)
            .AddValidationDetail("Колонка не найдена");

            validationContext.When(model, m => m.Name)
            .IsWhitespace()
            .AddValidationDetail("Имя колонки не указано");

            if (validationContext.IsValid(model, m => m.Name) && model.Name != null)
            {
                var columnNameExists = await databaseContext
                                       .Columns
                                       .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                                       .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => columnNameExists)
                .AddValidationDetail($"Колонка с именем '{model.Name}' уже сущетсвует");
            }

            if (model.Order != 0)
            {
                validationContext.When(model, x => x.Order)
                .IsLess(0)
                .AddValidationDetail("Порядок не может быть меньше нуля");

                var columnsCount = await databaseContext
                                   .Columns
                                   .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                                   .CountAsync(x => x.Board.Columns.Any(c => c.Id == model.Id));

                validationContext.When(model, m => m.Order)
                .IsGreater(columnsCount)
                .AddValidationDetail($"Порядок не может быть больше {columnsCount}");
            }
        }
Esempio n. 13
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Board>();

            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Название доски не задано");

            if (validationContext.IsValid(model, m => m.Name))
            {
                var boardExists = await databaseContext.Boards
                                  .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                                  .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => boardExists)
                .AddValidationDetail("Доска с таким именем уже существует");
            }
        }
Esempio n. 14
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var inviteId  = context.GetArgument <Guid>("id");

            var invite = await databaseContext
                         .Invites
                         .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                         .FirstOrDefaultAsync(x => x.Id == inviteId);

            validationContext.When("id")
            .Is(() => invite == null)
            .AddValidationDetail("Приглашение не найдено");

            if (validationContext.IsValid("id"))
            {
                validationContext.When("id")
                .Is(() => invite.AccountId != null)
                .AddValidationDetail("Нельзя удалить использованное приглашение");
            }
        }
Esempio n. 15
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <CardAssignment>();

            var accountExists = await databaseContext.Accounts
                                .Where(x => x.Id == accountId)
                                .Select(x => x.Organization)
                                .SelectMany(x => x.Accounts)
                                .AnyAsync(x => x.Id == model.AccountId);

            validationContext.When(model, m => m.AccountId)
            .IsNot(() => accountExists)
            .AddValidationDetail("Аккаунт не найден");

            var cardExists = await databaseContext.Accounts
                             .Where(x => x.Id == accountId)
                             .Select(x => x.Organization)
                             .SelectMany(x => x.Boards)
                             .SelectMany(x => x.Columns)
                             .SelectMany(x => x.Cards)
                             .AnyAsync(x => x.Id == model.CardId);

            validationContext.When(model, m => m.AccountId)
            .IsNot(() => cardExists)
            .AddValidationDetail("Карточка не найдена");

            if (validationContext.IsValid())
            {
                var assignmentExists = await databaseContext
                                       .CardAssignments
                                       .AnyAsync(x => x.AccountId == model.AccountId && x.CardId == model.CardId);

                validationContext.When()
                .Is(() => assignmentExists)
                .AddValidationDetail("Аккаунт уже назначен");
            }
        }
Esempio n. 16
0
 /// <summary>
 ///   Checks validation context is not valid
 /// </summary>
 public static bool IsNotValid(this IValidationContext validationContext, params string[] validationParts)
 {
     return(!validationContext.IsValid(validationParts));
 }
Esempio n. 17
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var model = context.GetArgument <Account>();

            if (model.Login != null)
            {
                validationContext.When(model, m => m.Login)
                .IsNullOrWhitespace()
                .AddValidationDetail("Логин не задан");

                if (validationContext.IsValid(model, m => m.Login))
                {
                    var accountExists = await databaseContext
                                        .Accounts
                                        .AnyAsync(x => x.Login == model.Login);

                    validationContext.When(model, m => m.Login)
                    .Is(() => accountExists)
                    .AddValidationDetail("Логин уже существует");
                }
            }

            if (model.Email != null)
            {
                validationContext.When(model, m => m.Email)
                .IsNotEmail()
                .AddValidationDetail("Это не email =/");

                if (validationContext.IsValid(model, m => m.Email))
                {
                    var accountExists = await databaseContext
                                        .Accounts
                                        .AnyAsync(account => account.Email == model.Email);

                    validationContext.When(model, m => m.Email)
                    .Is(() => accountExists)
                    .AddValidationDetail("Email уже используется");
                }

                if (model.Password != null)
                {
                    validationContext.When(model, m => m.Password)
                    .IsNullOrWhitespace()
                    .AddValidationDetail("Пароль не задан");
                }

                if (model.FirstName != null)
                {
                    validationContext.When(model, m => m.FirstName)
                    .IsNullOrWhitespace()
                    .AddValidationDetail("Имя не задано");
                }

                if (model.MiddleName != null)
                {
                    validationContext.When(model, m => m.MiddleName)
                    .IsNullOrWhitespace()
                    .AddValidationDetail("Отчество не задано");
                }

                if (model.LastName != null)
                {
                    validationContext.When(model, m => m.LastName)
                    .IsNullOrWhitespace()
                    .AddValidationDetail("Фамилия не задана");
                }
            }
        }
 public void IsValid()
 {
     validationContext.IsValid("Model");
 }