Exemplo n.º 1
0
        public ValueTask InvokeAsync(IMiddlewareContext context)
        {
            if (context.Result is SerializedData s)
            {
                context.Result = s.Data is IReadOnlyDictionary <string, object> d
                    ? d
                    : DictionaryDeserializer.DeserializeResult(
                    context.Selection.Type,
                    s.Data,
                    context.Service <InputParser>(),
                    context.Path);
            }
            else if (context.Result is null &&
                     !context.Selection.Field.Directives.Contains(DirectiveNames.Computed) &&
                     context.Parent <object>() is IReadOnlyDictionary <string, object> dict)
            {
                string responseName = context.Selection.SyntaxNode.Alias == null
                    ? context.Selection.SyntaxNode.Name.Value
                    : context.Selection.SyntaxNode.Alias.Value;

                dict.TryGetValue(responseName, out var obj);
                context.Result = DictionaryDeserializer.DeserializeResult(
                    context.Selection.Type,
                    obj,
                    context.Service <InputParser>(),
                    context.Path);
            }

            return(_next.Invoke(context));
        }
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            await _next(context).ConfigureAwait(false);

            if (context.Result is IAsyncEnumerable <T> ae)
            {
                await using IAsyncEnumerator <T> enumerator =
                                ae.GetAsyncEnumerator(context.RequestAborted);

                if (await enumerator.MoveNextAsync().ConfigureAwait(false))
                {
                    context.Result = enumerator.Current;
                }
                else
                {
                    context.Result = default(T) !;
                }
            }
            else if (context.Result is IEnumerable <T> e)
            {
                context.Result = await Task
                                 .Run(() => e.FirstOrDefault(), context.RequestAborted)
                                 .ConfigureAwait(false);
            }
        }
 public override void ResolverError(
     IMiddlewareContext context,
     IError error
     )
 {
     _logger.LogError(error.Exception, $"During execution of the operation {context.Operation} the error {ConvertErrorToString(error)} occurred.");
 }
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            await _next(context).ConfigureAwait(false);

            IValueNode sortArgument = context.Argument <IValueNode>(_contextData.ArgumentName);

            if (sortArgument is null || sortArgument is NullValueNode)
            {
                return;
            }

            IQueryable <T>?source = null;

            if (context.Result is IQueryable <T> q)
            {
                source = q;
            }
            else if (context.Result is IEnumerable <T> e)
            {
                source = e.AsQueryable();
            }

            if (source is not null &&
                context.Field.Arguments[_contextData.ArgumentName].Type is InputObjectType iot &&
                iot is ISortInputType fit &&
                fit.EntityType is { })
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            await _next(context).ConfigureAwait(false);

            IValueNode filter = context.ArgumentLiteral <IValueNode>(_contextData.ArgumentName);

            if (filter is NullValueNode)
            {
                return;
            }

            IQueryable <T>?source = null;

            if (context.Result is IQueryable <T> q)
            {
                source = q;
            }
            else if (context.Result is IEnumerable <T> e)
            {
                source = e.AsQueryable();
            }

            if (source is not null &&
                context.Field.Arguments[_contextData.ArgumentName].Type is InputObjectType iot &&
                iot is IFilterInputType fit)
            {
                var visitorContext = new QueryableFilterVisitorContext(
                    iot, fit.EntityType, _converter, source is EnumerableQuery);
                QueryableFilterVisitor.Default.Visit(filter, visitorContext);

                source = source.Where(visitorContext.CreateFilter <T>());

                context.Result = source;
            }
        }
 public override IEnumerable <ResolvedValidator> GetValidators(
     IMiddlewareContext context, IInputField argument)
 {
     yield return(new ResolvedValidator(
                      new RequiresOwnScopeValidator(),
                      _mockScope));
 }
Exemplo n.º 7
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            var queryAuthorizationService = context.Service <IServiceProvider>().GetService <IQueryAuthorizationService>();

            if (queryAuthorizationService != null)
            {
                var authorizationResult = await queryAuthorizationService.IsAllowedAsync(queryType);

                if (authorizationResult != AuthorizationResult.Allowed)
                {
                    var eb = ErrorBuilder.New()
                             .SetMessage(authorizationResult == AuthorizationResult.Unauthorized ? "Unauthorized" : "Forbidden")
                             .SetCode("AuthorizationResult")
                             .SetExtension("StatusCode", authorizationResult == AuthorizationResult.Unauthorized ? "401" : "403")
                             .SetPath(context.Path)
                             .AddLocation(context.Selection.SyntaxNode);

                    context.Result = eb.Build();

                    return;
                }
            }


            await _next.Invoke(context);
        }
Exemplo n.º 8
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            await _next(context).ConfigureAwait(false);

            var pagingDetails = new PagingDetails
            {
                First  = context.ArgumentValue <int?>("first"),
                After  = context.ArgumentValue <string>("after"),
                Last   = context.ArgumentValue <int?>("last"),
                Before = context.ArgumentValue <string>("before"),
            };

            IQueryable <T> source = context.Result switch
            {
                IQueryable <T> q => q,
                IEnumerable <T> e => e.AsQueryable(),
                _ => null
            };

            if (source != null)
            {
                IConnectionResolver connectionResolver = _createConnectionResolver(
                    source, pagingDetails);

                context.Result = await connectionResolver
                                 .ResolveAsync(context.RequestAborted)
                                 .ConfigureAwait(false);
            }
        }
Exemplo n.º 9
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)
                                );
                        }
                    }
                }
            }
        }
            public async Task InvokeAsync(IMiddlewareContext context)
            {
                TDataLoader dataloader = context.DataLoader <TDataLoader>();

                await _next(context).ConfigureAwait(false);

                if (context.Result is IReadOnlyCollection <TKey> values)
                {
                    IReadOnlyList <TValue[]> data = await dataloader
                                                    .LoadAsync(values, context.RequestAborted)
                                                    .ConfigureAwait(false);

                    var result = new HashSet <object>();
                    for (var m = 0; m < data.Count; m++)
                    {
                        for (var n = 0; n < data[m].Length; n++)
                        {
                            result.Add(data[m][n] !);
                        }
                    }

                    context.Result = result;
                }
                else if (context.Result is TKey value)
                {
                    context.Result = await dataloader
                                     .LoadAsync(value, context.RequestAborted)
                                     .ConfigureAwait(false);
                }
            }
        private static IReadOnlyCollection <Delegation.VariableValue> CreateVariableValues(
            IMiddlewareContext context,
            NameString schemaName,
            IEnumerable <Delegation.VariableValue> scopedVariables,
            ExtractedField extractedField,
            ExtractFieldQuerySyntaxRewriter rewriter)
        {
            var values = new Dictionary <string, Delegation.VariableValue>();

            foreach (Delegation.VariableValue value in scopedVariables)
            {
                values[value.Name] = value;
            }

            IReadOnlyDictionary <string, IValueNode> requestVariables = context.GetVariables();

            foreach (Delegation.VariableValue value in ResolveUsedRequestVariables(
                         context.Schema, schemaName, extractedField,
                         requestVariables, rewriter))
            {
                values[value.Name] = value;
            }

            return(values.Values);
        }
Exemplo n.º 12
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            if (context.ContextData.TryGetValue(BewitTokenHeader.Value, out var objectToken) &&
                objectToken is string bewitToken)
            {
                try
                {
                    object payload = await _tokenValidator.ValidateBewitTokenAsync(
                        new BewitToken <T>(bewitToken),
                        context.RequestAborted);

                    _httpContextAccessor.SetBewitPayload(payload);
                }
                catch (Exception ex)
                {
                    CreateError(context, ex);
                }

                await _next(context);
            }
            else
            {
                CreateError(context);
            }
        }
 public SkipValidationContext(
     IMiddlewareContext middlewareContext,
     IInputField argument)
 {
     MiddlewareContext = middlewareContext;
     Argument          = argument;
 }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            DelegateDirective delegateDirective = context.Field
                                                  .Directives[DirectiveNames.Delegate]
                                                  .FirstOrDefault()?.ToObject <DelegateDirective>();

            if (delegateDirective != null)
            {
                IImmutableStack <SelectionPathComponent> path =
                    delegateDirective.Path is null
                    ? ImmutableStack <SelectionPathComponent> .Empty
                    : SelectionPathParser.Parse(delegateDirective.Path);

                IReadOnlyQueryRequest request =
                    CreateQuery(context, delegateDirective.Schema, path);

                IReadOnlyQueryResult result = await ExecuteQueryAsync(
                    context, request, delegateDirective.Schema)
                                              .ConfigureAwait(false);

                UpdateContextData(context, result, delegateDirective);

                context.Result = new SerializedData(
                    ExtractData(result.Data, path.Count()));
                ReportErrors(context, result.Errors);
            }

            await _next.Invoke(context).ConfigureAwait(false);
        }
Exemplo n.º 16
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            await _next(context).ConfigureAwait(false);

            var page = context.Argument <int?>("page") ?? 1;

            if (page <= 0)
            {
                page = 1;
            }

            var pageSize = context.Argument <int?>("pageSize") ?? 10;

            var source = context.Result switch
            {
                IQueryable <TValueType> q => q,
                IEnumerable <TValueType> e => e.AsQueryable(),
                _ => null
            };

            if (source != null)
            {
                context.Result = new OffsetPaging <TValueType>
                {
                    TotalCount = source.LongCount(),
                    Edges      = source
                                 .Skip((page - 1) * pageSize)
                                 .Take(pageSize)
                                 .ToList()
                };
            }
        }
    }
Exemplo n.º 17
0
            public static bool ShouldValidateBasedOnValidateDescriptor(IMiddlewareContext context, IInputField argument)
            {
                // If argument itself was annotated
                if (IsValidateDescriptorApplied(argument.ContextData))
                {
                    return(true);
                }

                // If argument's input type was annotated
                if (argument.Type.InnerType() is InputObjectType inputType &&
                    IsValidateDescriptorApplied(inputType))
                {
                    return(true);
                }

                // If argument's clr type was annotated
                if (ClrTypesMarkedWithValidate.Cache.GetOrAdd(
                        argument.RuntimeType,
                        clrType => clrType.GetCustomAttribute <ValidateAttribute>(inherit: true) != null))
                {
                    return(true);
                }

                return(false);
            }
Exemplo n.º 18
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            var fieldName  = context.Field.Name;
            var objectType = context.ObjectType.Name;

            var contextAccessor = context.Service <IHttpContextAccessor>();

            if (!contextAccessor.HttpContext.User.Identity.IsAuthenticated)
            {
                context.Result = ErrorBuilder.New()
                                 .SetMessage("Forbidden")
                                 .SetCode("503")
                                 .SetPath(context.Path)
                                 .AddLocation(context.FieldSelection)
                                 .Build();

                return;
            }

            if (fieldName.Value == "PostalCode" && objectType.Value == "Restaurant")
            {
                context.Result = ErrorBuilder.New()
                                 .SetMessage("Forbidden")
                                 .SetCode("503")
                                 .SetPath(context.Path)
                                 .AddLocation(context.FieldSelection)
                                 .Build();

                return;
            }

            await _next.Invoke(context);
        }
        public virtual IEnumerable <ResolvedValidator> GetValidators(IMiddlewareContext context, IInputField argument)
        {
            if (!argument.ContextData.TryGetValue(
                    WellKnownContextData.ValidatorDescriptors,
                    out var validatorDescriptorsRaw) ||
                validatorDescriptorsRaw is not IEnumerable <ValidatorDescriptor> validatorDescriptors)
            {
                yield break;
            }

            foreach (var validatorDescriptor in validatorDescriptors)
            {
                if (validatorDescriptor.RequiresOwnScope)
                {
                    var scope     = context.Services.CreateScope(); // disposed by middleware
                    var validator = (IValidator)scope.ServiceProvider.GetRequiredService(validatorDescriptor.ValidatorType);
                    yield return(new ResolvedValidator(validator, scope));
                }
                else
                {
                    var validator = (IValidator)context.Services.GetRequiredService(validatorDescriptor.ValidatorType);
                    yield return(new ResolvedValidator(validator));
                }
            }
        }
Exemplo n.º 20
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            var queryArgument = context.ArgumentValue <object>("params");

            if (queryArgument != null)
            {
                var service = context.Service <IGraphQLValidationService>();
                var result  = await service.ValidateObjectAsync(queryArgument, context.RequestAborted);

                if (!result.IsValid)
                {
                    var eb = ErrorBuilder.New()
                             .SetMessage("There are some validations errors")
                             .SetCode("ValidationError")
                             .SetPath(context.Path)
                             .AddLocation(context.Selection.SyntaxNode);

                    foreach (var error in result.Errors)
                    {
                        eb.SetExtension(error.Field, error.Errors);
                    }

                    context.Result = eb.Build();

                    return;
                }
            }

            await _next.Invoke(context);
        }
Exemplo n.º 21
0
    private static async Task <AuthorizeResult> AuthorizeWithPolicyAsync(
        IMiddlewareContext context,
        AuthorizeDirective directive,
        ClaimsPrincipal principal)
    {
        IServiceProvider      services         = context.Service <IServiceProvider>();
        IAuthorizationService?authorizeService =
            services.GetService <IAuthorizationService>();
        IAuthorizationPolicyProvider?policyProvider =
            services.GetService <IAuthorizationPolicyProvider>();

        if (authorizeService == null || policyProvider == null)
        {
            // authorization service is not configured so the user is
            // authorized with the previous checks.
            return(string.IsNullOrWhiteSpace(directive.Policy)
                ? AuthorizeResult.Allowed
                : AuthorizeResult.NotAllowed);
        }

        AuthorizationPolicy?policy = null;

        if ((directive.Roles is null || directive.Roles.Count == 0) &&
            string.IsNullOrWhiteSpace(directive.Policy))
        {
            policy = await policyProvider.GetDefaultPolicyAsync()
                     .ConfigureAwait(false);

            if (policy == null)
            {
                return(AuthorizeResult.NoDefaultPolicy);
            }
        }
Exemplo n.º 22
0
        private void SetupContext(string method)
        {
            var request = new Mock <IMiddlewareRequest>();

            request.Setup(c => c.Method).Returns(method);
            request.Setup(c => c.PathBase).Returns("/basePath123");
            request.Setup(c => c.ReadFormAsync()).Returns(Task.FromResult <IDictionary <string, string[]> >(new Dictionary <string, string[]> {
                { "id", new[] { "12" } }
            }));

            var response = new Mock <IMiddlewareResponse>();

            response.SetupSet(c => c.StatusCode  = It.IsAny <int>()).Callback <int>(c => statusCode = c);
            response.SetupSet(c => c.ContentType = It.IsAny <string>()).Callback <string>(c => content = c);
            response.Setup(c => c.Redirect(It.IsAny <string>())).Callback <string>(c => location       = c);
            response.Setup(c => c.WriteAsync(It.IsAny <string>())).Callback <string>(c => responsebody = c);

            var services = new ServiceCollection();

            services.AddSingleton(new RazorPage1());

            var mockContext = new Mock <IMiddlewareContext>();

            mockContext.Setup(c => c.Request).Returns(request.Object);
            mockContext.Setup(c => c.Response).Returns(response.Object);
            mockContext.Setup(c => c.InternalServiceProvider).Returns(services.BuildServiceProvider());
            mockContext.Setup(c => c.UriMatch).Returns(Regex.Match("abc", "[a-z]*"));
            context = mockContext.Object;
        }
Exemplo n.º 23
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);
            }
Exemplo n.º 24
0
            public Task InvokeAsync(IMiddlewareContext context)
            {
                context.Result = "worked";
                return(Task.CompletedTask);

                ;
            }
Exemplo n.º 25
0
        protected virtual IErrorBuilder CreateErrorBuilder(
            IMiddlewareContext context,
            string argumentName,
            IValidator validator,
            ValidationFailure failure)
        {
            var builder = ErrorBuilder.New()
                          .SetPath(context.Path)
                          .SetMessage(failure.ErrorMessage)
                          .SetCode("FairyBread_ValidationError")
                          .SetExtension("argumentName", argumentName)
                          .SetExtension("validatorName", validator.GetType().Name)
                          .SetExtension("errorCode", failure.ErrorCode)
                          .SetExtension("errorMessage", failure.ErrorMessage)
                          .SetExtension("attemptedValue", failure.AttemptedValue)
                          .SetExtension("severity", failure.Severity)
                          .SetExtension("formattedMessagePlaceholderValues", failure.FormattedMessagePlaceholderValues);

            if (!string.IsNullOrWhiteSpace(failure.PropertyName))
            {
                builder = builder
                          .SetExtension("propertyName", failure.PropertyName);
            }

            return(builder);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Set form values and run save action if request is a POST
        /// </summary>
        ///<inheritdoc/>
        public async Task Dispatch(IMiddlewareContext context, ILoggingService loggingService)
        {
            Check.NotNull(context, nameof(context));
            Check.NotNull(loggingService, nameof(loggingService));

            var request  = context.Request;
            var response = context.Response;

            if (!"POST".Equals(request.Method, StringComparison.OrdinalIgnoreCase))
            {
                response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                return;
            }

            TPage page = context.InternalServiceProvider.GetRequiredService <TPage>();

            page.LoggingService = loggingService;

            var form = await context.Request.ReadFormAsync().ConfigureAwait(false);

            page.Assign(context);
            page.SetForm(form);

            IMiddlewareDispatcher result = page.Save();

            await result.Dispatch(context, loggingService).ConfigureAwait(false);
        }
 public void ResolverError(IMiddlewareContext context, IError error)
 {
     for (var i = 0; i < _listeners.Length; i++)
     {
         _listeners[i].ResolverError(context, error);
     }
 }
Exemplo n.º 28
0
 public RabbitMiddleware(IMiddlewareContext context, ILogger logger, IApplicationService application, IEmailService email, IPhoneService phone)
     : base(context, logger)
 {
     Application = application ?? throw new ArgumentNullException(nameof(application));
     Email       = email ?? throw new ArgumentNullException(nameof(email));
     Phone       = phone ?? throw new ArgumentNullException(nameof(phone));
 }
            public override IEnumerable <ResolvedValidator> GetValidators(IMiddlewareContext context, IInputField argument)
            {
                var validators = base.GetValidators(context, argument);

                var standardValidator        = validators.Where(v => v.Validator is StandardValidator).Single();
                var anotherStandardValidator = validators.Where(v => v.Validator is AnotherStandardValidator).Single();

                Assert.Null(standardValidator.Scope);
                Assert.Null(anotherStandardValidator.Scope);
                Assert.Equal(standardValidator.Scope, anotherStandardValidator.Scope);

                var ownScopeValidator = validators.Where(v => v.Validator is RequiresOwnScopeValidator).Single();

                Assert.NotNull(ownScopeValidator.Scope);
                Assert.NotEqual(standardValidator.Scope, ownScopeValidator.Scope);

                var anotherOwnScopeValidator = validators.Where(v => v.Validator is AnotherRequiresOwnScopeValidator).Single();

                Assert.NotNull(anotherOwnScopeValidator.Scope);
                Assert.NotEqual(standardValidator.Scope, anotherOwnScopeValidator.Scope);

                Assert.NotEqual(ownScopeValidator.Scope, anotherOwnScopeValidator.Scope);

                return(validators);
            }
 protected virtual void HandleInvalid(IMiddlewareContext context, ValidationResult result)
 {
     foreach (var failure in result.Errors)
     {
         HandleFailure(context, failure);
     }
 }