Esempio n. 1
0
        /// <summary>
        /// Verify whether token stored inside HTTP request header is valid and leads to an authorized user.
        /// </summary>
        /// <param name="context">Middleware context used in resolving.</param>
        /// <returns>Task result of the request.</returns>
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            var token = _tokenizer.GetToken();
            var user  = _tokenizer.GetUser();

            if (token == null)
            {
                context.ReportError(ErrorBuilder.New()
                                    .SetCode(AuthorizationErrorCodes.NoToken.ToString())
                                    .SetMessage("No authorization token provided!")
                                    .Build());

                return;
            }

            if (user == null)
            {
                context.ReportError(ErrorBuilder.New()
                                    .SetCode(AuthorizationErrorCodes.NoAssociatedUser.ToString())
                                    .SetMessage("Provided authorization token isn't associated with a valid user!")
                                    .Build());

                return;
            }

            await _next(context);
        }
Esempio n. 2
0
            public async Task InvokeAsync(IMiddlewareContext context)
            {
                IFieldCollection <IInputField> arguments = context.Selection.Field.Arguments;

                foreach (IInputField argument in arguments)
                {
                    var  value      = context.ArgumentValue <object?>(argument.Name) !;
                    Type actualType = value.GetType();

                    if (argument.RuntimeType != actualType)
                    {
                        context.ReportError($"RuntimeType ({argument.RuntimeType}) not equal to actual type ({actualType})");
                    }

                    if (context.Selection.Field.Name.Value.StartsWith("array"))
                    {
                        if (!argument.RuntimeType.IsArray)
                        {
                            context.ReportError($"Field defined with array but ArgDeg saying it's a {argument.RuntimeType}");
                        }

                        if (!actualType.IsArray)
                        {
                            context.ReportError($"Field defined with array but actual type is a {actualType}");
                        }
                    }
                }

                await _next(context);
            }
Esempio n. 3
0
        public void Validate(object instance, IMiddlewareContext context)
        {
            ValidationContext validationContext = new ValidationContext(instance);

            if (instance != null)
            {
                foreach (PropertyInfo propInfo in instance.GetType().GetRuntimeProperties())
                {
                    foreach (ValidationAttribute validationAttr in propInfo.GetCustomAttributes().OfType <ValidationAttribute>())
                    {
                        validationContext.DisplayName = propInfo.Name;

                        object           value  = propInfo.GetValue(instance);
                        ValidationResult result = validationAttr.GetValidationResult(value, validationContext);
                        if (result != null)
                        {
                            Dictionary <string, object> extensions = new Dictionary <string, object>();

                            foreach (PropertyInfo argPropInfo in validationAttr.GetType().GetTypeInfo().DeclaredProperties)
                            {
                                extensions[argPropInfo.Name] = argPropInfo.GetValue(validationAttr);
                            }

                            extensions.Add("key", "ValidationError");
                            extensions.Add("field", propInfo.Name);
                            extensions.Add("validator", validationAttr.GetType().Name);

                            context.ReportError(
                                new Error(result.ErrorMessage, "ValidationError", context.Path, extensions: extensions)
                                );
                        }
                    }
                }
            }
        }
Esempio n. 4
0
        public async Task Invoke(
            IMiddlewareContext context)
        {
            if (context.Selection.SyntaxNode.Arguments.Any())
            {
                var serviceProvider = context.Service <IServiceProvider>();
                var errors          = new List <(IInputField Argument, IList <ValidationFailure> Failures)>();

                foreach (IInputField argument in context.Field.Arguments)
                {
                    var validationOptions = new ArgumentValidationOptions <object>(
                        argument, context.ArgumentValue <object>(argument.Name));

                    if (!validationOptions.AllowedToValidate())
                    {
                        continue;
                    }

                    IValidator validator = validationOptions.GetValidator(serviceProvider);

                    if (validator == null)
                    {
                        continue;
                    }

                    ValidationResult result = await validator.ValidateAsync(
                        validationOptions.BuildValidationContext(), context.RequestAborted).ConfigureAwait(false);

                    if (result.Errors.Any())
                    {
                        errors.Add((argument, result.Errors));
                    }
                }

                if (errors.Any())
                {
                    var errorBuilder = ActivatorUtilities.CreateInstance(
                        serviceProvider, _errorBuilderType) as IValidationErrorBuilder;

                    foreach (var error in errors)
                    {
                        foreach (var failure in error.Failures)
                        {
                            context.ReportError(
                                errorBuilder.BuildError(
                                    ErrorBuilder.New(), failure, error.Argument, context)
                                .Build());
                        }
                    }

                    return;
                }
            }

            await _next(context).ConfigureAwait(false);
        }
Esempio n. 5
0
        public async Task Invoke(IMiddlewareContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            try
            {
                await _next(context).ConfigureAwait(false);
            }
            catch (ApiException <ValidationProblemDetails> exception)
            {
                var errors = exception.Result.Errors;
                foreach (var validationErrors in errors)
                {
                    foreach (var validationError in validationErrors.Value)
                    {
                        context.ReportError(ErrorBuilder
                                            .New()
                                            .SetMessage(validationError)
                                            .SetPath(context.Path)
                                            .SetExtension("field", validationErrors.Key)
                                            .SetExtension("extra", exception.Result.AdditionalProperties)
                                            .Build());
                    }
                }
            }
            catch (ApiException <ProblemDetails> exception)
            {
                context.ReportError(ErrorBuilder
                                    .New()
                                    .SetMessage(exception.Result.Title)
                                    .SetPath(context.Path)
                                    .SetExtension("extra", exception.Result.AdditionalProperties)
                                    .Build());
            }
        }
Esempio n. 6
0
 public virtual void Handle(
     IMiddlewareContext context,
     IEnumerable <ArgumentValidationResult> invalidResults)
 {
     foreach (var invalidResult in invalidResults)
     {
         foreach (var failure in invalidResult.Result.Errors)
         {
             var errorBuilder = CreateErrorBuilder(context, invalidResult.ArgumentName, invalidResult.Validator, failure);
             var error        = errorBuilder.Build();
             context.ReportError(error);
         }
     }
 }
Esempio n. 7
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            var arguments = context.Field.Arguments;

            if (arguments.Count is 0)
            {
                await _next(context);
            }

            var errors = new List <ValidationResult>();

            foreach (var argument in arguments)
            {
                if (argument == null)
                {
                    continue;
                }

                var input = context.ArgumentValue <object>(argument.Name);

                if (input == null)
                {
                    continue;
                }

                if (!ValidatorSettings.ValidateAllInputs &&
                    input.GetType().GetCustomAttribute(typeof(ValidatableAttribute)) == null)
                {
                    continue;
                }

                var validationContext = new ValidationContext(input);
                Validator.TryValidateObject(input, validationContext, errors, true);
            }

            if (errors.Any())
            {
                foreach (var error in errors)
                {
                    context.ReportError(ErrorBuilder.New()
                                        .SetMessage(error.ErrorMessage)
                                        .Build());
                }
            }
            else
            {
                await _next(context);
            }
        }
Esempio n. 8
0
        public async Task Invoke(IMiddlewareContext context)
        {
            if (context.FieldSelection.Arguments.Count == 0)
            {
                await _next(context);

                return;
            }

            var errors = context.FieldSelection.Arguments
                         .Select(a => context.Argument <object>(a.Name.Value))
                         .SelectMany(ValidateObject);

            if (errors.Any())
            {
                foreach (var error in errors)
                {
                    context.ReportError(ErrorBuilder.New()
                                        .SetCode("error.validation")
                                        .SetMessage(error.ErrorMessage)
                                        .SetExtension("memberNames", error.MemberNames)
                                        .AddLocation(context.FieldSelection.Location.Line, context.FieldSelection.Location.Column)
                                        .SetPath(context.Path)
                                        .Build());
                }

                context.Result = null;
            }
            else
            {
                await _next(context);
            }

            IEnumerable <ValidationResult> ValidateObject(object argument)
            {
                var results = new List <ValidationResult>();

                Validator.TryValidateObject(argument, new ValidationContext(argument), results, validateAllProperties: true);

                return(results);
            }
        }
 public override bool Handle(IMiddlewareContext context, ValidationResult result)
 {
     context.ReportError("lol");
     return(false);
 }
Esempio n. 10
0
    public async Task Invoke(IMiddlewareContext context)
    {
        if (context.FieldSelection.Arguments.Count == 0)
        {
            await _next(context);

            return;
        }

        var errors = context.FieldSelection.Arguments
                     .Select(a => context.Argument <object>(a.Name.Value))
                     .SelectMany(ValidateObject);

        if (errors.Any())
        {
            foreach (var error in errors)
            {
                context.ReportError(ErrorBuilder.New()
                                    .SetCode(error.ErrorCode)
                                    .SetMessage(error.ErrorMessage)
                                    .SetExtension("memberNames", error.PropertyName)
                                    .AddLocation(context.FieldSelection.Location.Line, context.FieldSelection.Location.Column)
                                    .SetPath(context.Path)
                                    .Build());
            }

            context.Result = null;
        }
        else
        {
            await _next(context);
        }

        IEnumerable <ValidationFailure> ValidateObject(object argument)
        {
            try
            {
                var    actualObjectType     = argument.GetType();
                var    validatorGenericType = typeof(IValidator <>);
                var    validatorType        = validatorGenericType.MakeGenericType(actualObjectType);
                object validator            = null;
                try
                {
                    validator = context.Service(validatorType);
                }
                catch (InvalidOperationException)
                {
                    // No service found
                    return(Enumerable.Empty <ValidationFailure>());
                }

                if (validator == null)
                {
                    return(Enumerable.Empty <ValidationFailure>());
                }

                var validateMethodInfo = validatorType.GetMethod(nameof(IValidator.Validate), new[] { actualObjectType });
                var results            = validateMethodInfo.Invoke(validator, new[] { argument }) as ValidationResult;

                return(results.Errors.AsEnumerable());
            }
            catch (Exception ex)
            {
                throw new Exception($"Failed to validate with error '{ex.Message}'.");
            }
        }
    }