private async Task ExecuteAsync(HttpContext context, ISchema schema)
        {
            string body;

            using (var streamReader = new StreamReader(context.Request.Body))
            {
                body = await streamReader.ReadToEndAsync().ConfigureAwait(true);
            }

            var request = JsonConvert.DeserializeObject <GraphQLRequest>(body);

            var validationRules = new List <IValidationRule>()
            {
                new RequiresAuthValidationRule()
            };

            var result = await DataLoaderContext.Run(ctx => _executer.ExecuteAsync(_ =>
            {
                _.OperationName   = request.OperationName;
                _.Schema          = schema;
                _.Query           = request.Query;
                _.Inputs          = request.Variables.ToInputs();
                _.ValidationRules = validationRules.Concat(DocumentValidator.CoreRules());
                _.UserContext     = new GraphQLUserContext(ctx, context.User);
            }));

            await WriteResponseAsync(context, result);
        }
Esempio n. 2
0
        public async Task <ExecuteGQLQueryResults> ExecuteQuery(string queryTemplate, IDictionary <string, object> parameters)
        {
            var schema = await _schemaService.GetSchemaAsync();

            var gqlSettings    = _settingsAccessor.Value;
            var tokenizedQuery = await _liquidTemplateManager.RenderStringAsync(queryTemplate, NullEncoder.Default, parameters.Select(x => new KeyValuePair <string, FluidValue>(x.Key, FluidValue.Create(x.Value, _templateOptions))));

            var result = new ExecuteGQLQueryResults()
            {
                TokenizedQuery = tokenizedQuery
            };

            result.Result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema           = schema;
                _.Query            = tokenizedQuery;
                _.UserContext      = gqlSettings.BuildUserContext?.Invoke(_httpContextAccessor.HttpContext);
                _.ExposeExceptions = gqlSettings.ExposeExceptions;
                _.ValidationRules  = DocumentValidator.CoreRules()
                                     .Concat(_validationRules);
                _.ComplexityConfiguration = new ComplexityConfiguration
                {
                    MaxDepth      = gqlSettings.MaxDepth,
                    MaxComplexity = gqlSettings.MaxComplexity,
                    FieldImpact   = gqlSettings.FieldImpact
                };
                _.Listeners.Add(_dataLoaderDocumentListener);
            });

            return(result);
        }
        private async Task ExecuteAsync(HttpContext context, ISchema schema)
        {
            var request = Deserialize <GraphQLQuery>(context.Request.Body);

            object userContext        = null;
            var    userContextBuilder = context.RequestServices.GetService <IUserContextBuilder>();

            if (userContextBuilder != null)
            {
                userContext = await userContextBuilder.BuildUserContext(context);
            }
            else
            {
                userContext = _options.BuildUserContext?.Invoke(context);
            }

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema           = schema;
                _.Query            = request.Query;
                _.OperationName    = request.OperationName;
                _.Inputs           = request.Variables.ToInputs();
                _.UserContext      = userContext;
                _.ExposeExceptions = _options.ExposeExceptions;
                _.ValidationRules  = _options.ValidationRules.Concat(DocumentValidator.CoreRules()).ToList();
            });

            await WriteResponseAsync(context, result);
        }
Esempio n. 4
0
        public async Task <IActionResult> Post([FromBody] GraphQLParameter parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            var executionOptions = new ExecutionOptions
            {
                Schema        = _schema,
                Query         = parameter.Query,
                Inputs        = parameter.Variables.ToInputs(),
                OperationName = parameter.OperationName,
                UserContext   = new GraphQLUserContext {
                    User = User
                },
                ValidationRules = DocumentValidator.CoreRules().Concat(_validationRules).ToList()
            };

            executionOptions.Listeners.Add(_listener);

            var result = await _documentExecuter
                         .ExecuteAsync(executionOptions)
                         .ConfigureAwait(false);

            if (result.Errors?.Count > 0)
            {
                return(BadRequest(result.Errors));
            }

            return(Ok(result));
        }
        //
        // Summary:
        //     /// Method responsible for run the middleware. ///
        //
        // Parameters:
        //   httpContext:
        //     The httpContext param.
        //
        //   schema:
        //     The schema param.
        //
        //   serviceProvider:
        //     The serviceProvider param.
        //
        public async Task InvokeAsync(HttpContext httpContext, ISchema schema, IServiceProvider serviceProvider)
        {
            if (!(httpContext.Request.Path.StartsWithSegments("/graphqlapi") &&
                  string.Equals(httpContext.Request.Method, "POST", StringComparison.OrdinalIgnoreCase)))
            {
                await _next(httpContext);
            }

            using (StreamReader streamReader = new StreamReader(httpContext.Request.Body))
            {
                string body = await streamReader.ReadToEndAsync();

                GraphQLQuery request = JsonConvert.DeserializeObject <GraphQLQuery>(body);

                DateTime start = DateTime.UtcNow;

                ExecutionResult result = await _documentExecutor.ExecuteAsync(x =>
                {
                    x.Schema = schema;
                    x.Query  = request.Query;
                    x.Inputs = request.Variables.ToInputs();
                    x.Listeners.Add(serviceProvider.GetRequiredService <DataLoaderDocumentListener>());
                    x.ExposeExceptions        = false;
                    x.ComplexityConfiguration = new ComplexityConfiguration {
                        MaxDepth = 15
                    };
                    x.ValidationRules = DocumentValidator.CoreRules().Concat(_validationRules).ToList();
                }).ConfigureAwait(false);

                string json = await _documentWriter.WriteToStringAsync(result);

                await httpContext.Response.WriteAsync(json);
            }
        }
        protected virtual ExecutionOptions GetOptions(string operationName, string query, Inputs variables, object context, CancellationToken cancellationToken)
        {
            var opts = new ExecutionOptions()
            {
                Schema                  = Schema,
                OperationName           = operationName,
                Query                   = query,
                Inputs                  = variables,
                UserContext             = context,
                CancellationToken       = cancellationToken,
                ComplexityConfiguration = _options.ComplexityConfiguration,
                EnableMetrics           = _options.EnableMetrics,
                ExposeExceptions        = _options.ExposeExceptions,
                SetFieldMiddleware      = _options.SetFieldMiddleware
            };

            foreach (var listener in _listeners)
            {
                opts.Listeners.Add(listener);
            }

            opts.ValidationRules = _validationRules
                                   .Concat(DocumentValidator.CoreRules())
                                   .ToList();

            return(opts);
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            var schema = new Schema()
            {
                Mutation = new ExampleMutation()
            };

            var res = schema.Execute(_ =>
            {
                _.Query           = @"
                    mutation {
                      exampleMutation(theParameter: {
                        pleaseValidateMe: ""foo""
                      })
                    }";
                _.ValidationRules =
                    new IValidationRule[]
                {
                    new ValidationRuleA(),
                    new ValidationRuleB()
                }
                .Concat(DocumentValidator.CoreRules());
            });

            Console.WriteLine("Press a key to quit");
            Console.ReadKey();
        }
Esempio n. 8
0
        private ExecutionOptions BuildExecutionOptions(string query, PermissionsContext permissionsContext)
        {
            var services = new ServiceCollection();

            services.AddAuthorization();
            services.AddLogging();
            services.AddOptions();

            services.AddScoped <IAuthorizationHandler, PermissionContextAuthorizationHandler>(x =>
            {
                return(new PermissionContextAuthorizationHandler(permissionsContext));
            });

            services.AddScoped <IValidationRule, RequiresPermissionValidationRule>();

            var serviceProvider = services.BuildServiceProvider();

            return(new ExecutionOptions
            {
                Query = query,
                Schema = new ValidationSchema(),
                UserContext = new GraphQLContext
                {
                    ServiceProvider = serviceProvider,
                    User = new ClaimsPrincipal(new StubIdentity())
                },
                ValidationRules = DocumentValidator.CoreRules().Concat(serviceProvider.GetServices <IValidationRule>())
            });
        }
Esempio n. 9
0
        public async Task <IActionResult> PostAsync([FromBody] GraphQLQuery query)
        {
            var inputs         = query.Variables.ToInputs();
            var queryToExecute = query.Query;

            if (!string.IsNullOrWhiteSpace(query.NamedQuery))
            {
                queryToExecute = _namedQueries[query.NamedQuery];
            }

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.UserContext             = new GraphQLUserContext(_httpContextAccessor);
                _.Schema                  = _schema;
                _.Query                   = queryToExecute;
                _.OperationName           = query.OperationName;
                _.Inputs                  = inputs;
                _.ComplexityConfiguration = new ComplexityConfiguration {
                    MaxDepth = 15
                };
                _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
                _.ValidationRules = _pluginValidationRules.Concat(DocumentValidator.CoreRules());
            }).ConfigureAwait(false);

            var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;

            var json = _writer.Write(result);

            return(new ObjectResult(json)
            {
                StatusCode = (int)httpResult
            });
        }
Esempio n. 10
0
        public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var inputs           = query.Variables.ToInputs();
            var executionOptions = new ExecutionOptions
            {
                Schema      = _schema,
                Query       = query.Query,
                Inputs      = inputs,
                UserContext = _userContext
            };

            var validationRuleServices = _serviceProvider.GetServices <IValidationRule>();

            executionOptions.ValidationRules = DocumentValidator.CoreRules().Concat(validationRuleServices);

            //Using middleware example
            executionOptions.FieldMiddleware.Use(next =>
            {
                return(context =>
                {
                    _logger.LogDebug($"FieldName middleware => {context.FieldName}");
                    return next(context);
                });
            });

            var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);

            HttpStatusCode statusCode = HttpStatusCode.OK;

            if (result.Errors?.Any() ?? false)
            {
                statusCode = HttpStatusCode.InternalServerError;
                if (result.Errors.Any(x => x.Code == "VALIDATION_ERROR"))
                {
                    statusCode = HttpStatusCode.BadRequest;
                }
                else if (result.Errors.Any(x => x.Code == "UNAUTHORIZED_ACCESS"))
                {
                    statusCode = HttpStatusCode.Forbidden;
                }
            }

            return(new ContentResult
            {
                Content = await _documentWriter.WriteToStringAsync(result),
                ContentType = "application/json; charset=utf-8",
                StatusCode = (int)statusCode
            });
        }
Esempio n. 11
0
 protected static async Task <ExecutionResult> Validate(string query, Schema schema, Inputs inputs = null)
 {
     return(await new DocumentExecuter().ExecuteAsync(options =>
     {
         options.Query = query;
         options.Schema = schema;
         options.UserContext = new DataSource();
         options.Inputs = inputs;
         options.ValidationRules = DocumentValidator.CoreRules();
     }));
 }
Esempio n. 12
0
        private static async Task <ExecuteAsyncResult> ExecuteAsync(
            string queryPath,
            object variableObject           = null,
            Action <Position> setPermission = null
            )
        {
            var variable = "{}";

            if (variableObject is string)
            {
                variable = File.ReadAllText(((string)variableObject).TrimStart('/'));
            }
            else if (variableObject != null)
            {
                variable = JsonConvert.SerializeObject(variableObject);
            }
            var query = File.ReadAllText(queryPath.TrimStart('/'));

            var User = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new[] { new Claim(ClaimTypes.Name, Constant.adminName) }
                    )
                );

            var position = EmployeeBusiness.Get(Constant.adminName).Position;

            if (setPermission != null)
            {
                PositionBusiness.UpdateForHelper(setPermission, position);
            }

            var result = await Initializer.DocumentExecuter.ExecuteAsync(_ =>
            {
                _.Schema      = Initializer.Schema;
                _.Query       = query;
                _.Inputs      = JObject.Parse(variable).ToInputs();
                _.UserContext = new GraphQLUserContext {
                    User = User
                };
                _.ValidationRules = DocumentValidator.CoreRules().Concat(Initializer.ValidationRule).ToList();
            }).ConfigureAwait(false);

            return(new ExecuteAsyncResult
            {
                Result = result,
                Query = query,
                Variable = variable
            });
        }
Esempio n. 13
0
 public IValidationResult Validate(string originalQuery, ISchema schema, Document document, IEnumerable <IValidationRule> rules = null, object userContext = null, Inputs inputs = null)
 {
     if (rules == null)
     {
         rules = DocumentValidator.CoreRules();
         //TODO: These rules must be included in the future, currently tests and calling applications do not obey these rules
         (rules as List <IValidationRule>).RemoveAll(rule =>
         {
             return(rule is KnownArgumentNames ||
                    rule is ArgumentsOfCorrectType ||
                    rule is FieldsOnCorrectType);
         });
     }
     return(new DocumentValidator().Validate(originalQuery, schema, document, rules, userContext));
 }
Esempio n. 14
0
        private async Task ExecuteAsync(HttpContext context, ISchema schema)
        {
            var request = Deserialize <GraphQLRequest>(context.Request.Body);

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema          = schema;
                _.Query           = request.Query;
                _.OperationName   = request.OperationName;
                _.Inputs          = request.Variables.ToInputs();
                _.UserContext     = _settings.BuildUserContext?.Invoke(context);
                _.ValidationRules = DocumentValidator.CoreRules().Concat(new [] { new InputValidationRule() });
            });

            await WriteResponseAsync(context, result);
        }
        internal async Task <IActionResult> ProcessQueryAsync(GraphQLQuery query)
        {
            try
            {
                var inputs         = query.Variables.ToInputs();
                var queryToExecute = query.Query;
                var result         = await _executer.ExecuteAsync(_ =>
                {
                    _.UserContext             = new GraphQLUserContext(_httpContextAccessor);
                    _.Schema                  = _schema;
                    _.Query                   = queryToExecute;
                    _.OperationName           = query.OperationName;
                    _.Inputs                  = inputs;
                    _.ComplexityConfiguration = new ComplexityConfiguration {
                        MaxDepth = 15
                    };
                    _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
                    _.ValidationRules = _pluginValidationRules.Concat(DocumentValidator.CoreRules());
                }).ConfigureAwait(false);

                var httpResult = result.Errors?.Count > 0
                    ? HttpStatusCode.BadRequest
                    : HttpStatusCode.OK;
                MemoryStream stream = new MemoryStream();
                await _writer.WriteAsync(stream, result);

                StreamReader reader = new StreamReader(stream);
                stream.Seek(0, SeekOrigin.Begin);
                string  json = reader.ReadToEnd();
                dynamic obj  = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(json);

                var objectResult = new ObjectResult(obj)
                {
                    StatusCode = (int)httpResult
                };

                var summaryLog = string.Join(";", _scopedSummaryLogger.Select(x => x.Key + "=" + x.Value).ToArray());
                Logger.LogCritical(summaryLog);
                return(objectResult);
            }
            catch (Exception ex)
            {
                var summaryLog = string.Join(";", _scopedSummaryLogger.Select(x => x.Key + "=" + x.Value).ToArray());
                Logger.LogError(ex, summaryLog);
                return(MakeObjectResult("Unable to process request", HttpStatusCode.NotFound));
            }
        }
        public async Task <ExecutionResult> ExecuteAsync(GraphQlDomainRequest graphQlDomainRequest)
        {
            bool.TryParse(_configuration["GraphQl:EnableMetrics"], out var enableMetrics);
            bool.TryParse(_configuration["GraphQl:ExposeExceptions"], out var exposeExceptions);

            var start = DateTime.UtcNow;

            _graphRequestContext.HttpRequest = _requestContext;

            var options = new ExecutionOptions
            {
                OperationName    = graphQlDomainRequest.OperationName,
                Schema           = _schema,
                Query            = graphQlDomainRequest.Query,
                EnableMetrics    = enableMetrics,
                UserContext      = _graphRequestContext,
                ExposeExceptions = exposeExceptions,
                ValidationRules  = DocumentValidator.CoreRules().Concat(_validationRules)
            };

            if (graphQlDomainRequest.Variables != null)
            {
                options.Inputs = JsonConvert.SerializeObject(graphQlDomainRequest.Variables).ToInputs();
            }

            var results = await _documentExecuter.ExecuteAsync(options);

            if (results.Errors != null && results.Errors.Count > 0)
            {
                results.Errors.ToList().ForEach(ex =>
                {
                    _logger.LogError(ex.Message);
                });
            }

            if (enableMetrics)
            {
                results.EnrichWithApolloTracing(start);
            }

            return(results);
        }
        public async Task <IActionResult> PostAsync( )
        {
            string body;

            using (var streamReader = new StreamReader(Request.Body))
            {
                body = await streamReader.ReadToEndAsync().ConfigureAwait(true);
            }

            var query = JsonConvert.DeserializeObject <GraphQLQuery>(body);

            var inputs         = query.Variables.ToInputs();
            var queryToExecute = query.Query;

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.UserContext             = new GraphQLUserContext(_httpContextAccessor);
                _.Schema                  = _schema;
                _.Query                   = queryToExecute;
                _.OperationName           = query.OperationName;
                _.Inputs                  = inputs;
                _.ComplexityConfiguration = new ComplexityConfiguration {
                    MaxDepth = 15
                };
                _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
                _.ValidationRules = _pluginValidationRules.Concat(DocumentValidator.CoreRules());
            }).ConfigureAwait(false);

            var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;

            var     json = _writer.Write(result);
            dynamic obj  = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(json);

            var rr = new ObjectResult(obj)
            {
                StatusCode = (int)httpResult
            };

            return(rr);
        }
        public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var executionOptions = new ExecutionOptions
            {
                Schema           = Schema,
                Query            = query.Query,
                Inputs           = query.Variables.ToInputs(),
                ExposeExceptions = true,
                ValidationRules  = DocumentValidator.CoreRules().Concat(ValidationRules)
            };

            var result = await DocumentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);

            return(Ok(result));
        }
Esempio n. 19
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var validationRules = app.ApplicationServices.GetServices <IValidationRule>();

            var options = new GraphQLHttpOptions();

            validationRules.Concat(DocumentValidator.CoreRules()).Apply(options.ValidationRules.Add);
            options.BuildUserContext = httpContext => new GraphQLUserContext {
                User = httpContext.User
            };

            app.UseGraphQLHttp <ISchema>(options);
            app.UseGraphiQLServer(new GraphiQLOptions());

            app.UseMvc();
        }
Esempio n. 20
0
        public static void AddGraphQlAuth(this IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IAuthorizationEvaluator, AuthorizationEvaluator>();
            services.AddTransient <AuthorizationValidationRule>();
            services.AddSingleton(s =>
            {
                var authSettings = new AuthorizationSettings();

                authSettings.AddPolicy(AuthorizationConstants.GraphQlAdminPolicy, _ => _.RequireClaim(ClaimTypes.Role, AuthorizationConstants.AdminRole));

                return(authSettings);
            });
            services.AddSingleton <IEnumerable <IValidationRule> >(s =>
            {
                List <IValidationRule> validationRules        = DocumentValidator.CoreRules();
                AuthorizationValidationRule authorizationRule = s.GetRequiredService <AuthorizationValidationRule>();
                validationRules.Add(authorizationRule);
                return(validationRules);
            });
        }
Esempio n. 21
0
        public ExecutionResult ExecuteQuery(
            string query,
            Inputs inputs,
            object root,
            object userContext = null,
            CancellationToken cancellationToken       = default(CancellationToken),
            IEnumerable <IPluginValidationRule> rules = null)
        {
            var fixedRules = rules != null?rules.ToList() : new List <IPluginValidationRule>();

            var newRules  = fixedRules.Concat(DocumentValidator.CoreRules());
            var runResult = Executer.ExecuteAsync(
                Schema,
                root,
                query,
                null,
                inputs,
                userContext,
                cancellationToken,
                newRules
                ).Result;

            var writtenResult = Writer.Write(runResult);

            // #if DEBUG
            //             Console.WriteLine(writtenResult);
            // #endif

            string additionalInfo = null;

            if (runResult.Errors?.Any() == true)
            {
                additionalInfo = string.Join(Environment.NewLine, runResult.Errors
                                             .Where(x => x.InnerException is GraphQLSyntaxErrorException)
                                             .Select(x => x.InnerException.Message));
            }

            return(runResult);
        }
        private async Task <IActionResult> ProcessQueryAsync(GraphQLQuery query)
        {
            try
            {
                var inputs         = query.Variables.ToInputs();
                var queryToExecute = query.Query;
                var result         = await _executer.ExecuteAsync(_ =>
                {
                    _.UserContext             = new GraphQLUserContext(_httpContextAccessor);
                    _.Schema                  = _schema;
                    _.Query                   = queryToExecute;
                    _.OperationName           = query.OperationName;
                    _.Inputs                  = inputs;
                    _.ComplexityConfiguration = new ComplexityConfiguration {
                        MaxDepth = 15
                    };
                    _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
                    _.ValidationRules = _pluginValidationRules.Concat(DocumentValidator.CoreRules());
                }).ConfigureAwait(false);

                var httpResult = result.Errors?.Count > 0
                    ? HttpStatusCode.BadRequest
                    : HttpStatusCode.OK;

                var     json = _writer.Write(result);
                dynamic obj  = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(json);

                var objectResult = new ObjectResult(obj)
                {
                    StatusCode = (int)httpResult
                };
                return(objectResult);
            }
            catch (Exception e)
            {
                return(MakeObjectResult("Unhandled GraphQL Exception", HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 23
0
        public async Task <dynamic> PostAsync(GraphQLQuery query)
        {
            var inputs         = query.Variables.ToInputs();
            var queryToExecute = query.Query;

            if (!string.IsNullOrWhiteSpace(query.NamedQuery))
            {
                queryToExecute = _namedQueries[query.NamedQuery];
            }

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema                  = _schema;
                _.Query                   = queryToExecute;
                _.OperationName           = query.OperationName;
                _.Inputs                  = inputs;
                _.ComplexityConfiguration = new ComplexityConfiguration {
                    MaxDepth = 15
                };
                _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
                _.ValidationRules = _validationRules.Concat(DocumentValidator.CoreRules());
            }).ConfigureAwait(false);

            var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;



            if (httpResult != HttpStatusCode.OK)
            {
                throw new Exception(result.Errors.First().Message);
            }
            var     json = _writer.Write(result);
            dynamic obj  = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(json);

            return(obj);
        }
Esempio n. 24
0
        private async Task ExecuteAsync(HttpContext context, ISchema schema)
        {
            var start   = DateTime.UtcNow;
            var request = Deserialize <GraphQLRequest>(context.Request.Body);

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema          = schema;
                _.Query           = request?.Query;
                _.OperationName   = request?.OperationName;
                _.Inputs          = request?.Variables.ToInputs();
                _.UserContext     = _settings.BuildUserContext?.Invoke(context);
                _.ValidationRules = DocumentValidator.CoreRules().Concat(new[] { new InputValidationRule() });
                _.EnableMetrics   = true;
                _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
            });

            result.EnrichWithApolloTracing(start);

            await ApolloTraceBuilder.SendResultToApollo(result);

            await WriteResponseAsync(context, result);
        }
Esempio n. 25
0
        private async Task ExecuteAsync(HttpContext context, ISchema schema)
        {
            string body;

            using (var streamReader = new StreamReader(context.Request.Body))
            {
                body = await streamReader.ReadToEndAsync().ConfigureAwait(true);
            }

            var request = JsonConvert.DeserializeObject <GraphQLQuery>(body);

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema           = schema;
                _.Query            = request.Query;
                _.OperationName    = request.OperationName;
                _.Inputs           = request.Variables.ToInputs();
                _.UserContext      = _options.BuildUserContext?.Invoke(context);
                _.ExposeExceptions = _options.ExposeExceptions;
                _.ValidationRules  = _options.ValidationRules.Concat(DocumentValidator.CoreRules()).ToList();
            });

            await WriteResponseAsync(context, result);
        }
Esempio n. 26
0
        public async Task InvokeAsync(HttpContext context, ISchema schema)
        {
            if (!context.Request.Path.StartsWithSegments(_settings.Path))
            {
                await _next(context);

                return;
            }

            // Handle requests as per recommendation at http://graphql.org/learn/serving-over-http/
            var httpRequest = context.Request;
            var request     = new Request();

            if (HttpMethods.IsGet(httpRequest.Method) || (HttpMethods.IsPost(httpRequest.Method) && httpRequest.Query.ContainsKey(Request.QueryKey)))
            {
                ExtractGraphQLRequestFromQueryString(httpRequest.Query, request);
            }
            else if (HttpMethods.IsPost(httpRequest.Method))
            {
                if (!MediaTypeHeaderValue.TryParse(httpRequest.ContentType, out var mediaTypeHeader))
                {
                    await WriteBadRequestResponseAsync(context, _writer, $"Invalid 'Content-Type' header: value '{httpRequest.ContentType}' could not be parsed.");

                    return;
                }

                switch (mediaTypeHeader.MediaType)
                {
                case "application/json":
                    request = Deserialize <Request>(httpRequest.Body);
                    break;

                case "application/graphql":
                    request.Query = await ReadAsStringAsync(httpRequest.Body);

                    break;

                case "application/x-www-form-urlencoded":
                    var formCollection = await httpRequest.ReadFormAsync();

                    ExtractGraphQLRequestFromPostBody(formCollection, request);
                    break;

                default:
                    await WriteBadRequestResponseAsync(context, _writer, "Invalid 'Content-Type' header: non-supported media type. See: http://graphql.org/learn/serving-over-http/.");

                    return;
                }
            }
            else
            {
                await WriteBadRequestResponseAsync(context, _writer, $"Invalid request method: value '{httpRequest.Method}' could not be handled. See: http://graphql.org/learn/serving-over-http/.");
            }

            var start  = DateTime.UtcNow;
            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema        = schema;
                _.Query         = request?.Query;
                _.OperationName = request?.OperationName;
                _.Inputs        = request?.Variables.ToInputs();
                _.UserContext   = new UserContext
                {
                    User = context.User
                };
                _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
                _.ValidationRules  = DocumentValidator.CoreRules().Concat(_rules);
                _.EnableMetrics    = _settings.EnableMetrics;
                _.ExposeExceptions = _settings.ExposeExceptions;
            });

            if (_settings.EnableMetrics && result.Errors == null)
            {
                result.EnrichWithApolloTracing(start);
            }

            if (result.Errors != null)
            {
                _logger.LogError("GraphQL execution error(s): {Errors}", result.Errors);
            }

            await WriteResponseAsync(context, result);
        }
Esempio n. 27
0
        public async Task <IActionResult> PostGraphQL([FromBody] GraphQLQuery graphQuery)
        {
            if (graphQuery == null)
            {
                return(BadRequest("No Query"));
            }

            var inputs = graphQuery.Variables.ToInputs();

            if (inputs.ContainsKey("participantId"))
            {
                var user = await _userManager.GetUserAsync(User);

                var participant = await _db.Participants
                                  .FirstOrDefaultAsync(p => p.IdentityUser.Id == user.Id);

                if (participant == null)
                {
                    return(BadRequest("Not a valid participant"));
                }

                inputs["participantId"] = participant.ParticipantId.ToString();
            }

            if (inputs.ContainsKey("teamId"))
            {
                var user = await _userManager.GetUserAsync(User);

                var participant = await _db.Participants
                                  .FirstOrDefaultAsync(p => p.IdentityUser.Id == user.Id);

                if (participant == null)
                {
                    return(BadRequest("Not a valid participant"));
                }

                inputs["teamId"] = participant.TeamId.ToString();
            }

            var context = _httpContextAccessor.HttpContext;

            var graphQlUserContext = new GraphQLUserContext
            {
                User = context.User
            };

            var result = await new DocumentExecuter().ExecuteAsync(_ =>
            {
                _.Schema          = _schema;
                _.Query           = graphQuery.Query;
                _.OperationName   = graphQuery.OperationName;
                _.Inputs          = inputs;
                _.UserContext     = graphQlUserContext;
                _.ValidationRules = DocumentValidator.CoreRules().Concat(new IValidationRule[]
                {
                    new AuthorizationValidationRule(_authorizationEvaluator)
                });
            }).ConfigureAwait(false);

            if (result.Errors?.Count > 0)
            {
                var msg = "";
                foreach (var err in result.Errors)
                {
                    msg = msg + " " + err.Message;
                }
                return(BadRequest(result.Errors.Select(e => e.Message)));
            }

            return(Ok(result.Data));
        }
Esempio n. 28
0
        private async Task <ExecutionResult> ExecuteAsync(HttpRequest request, ISchema schema, IScSession session, IGraphQLAuthenticationValidator _graphqlAuthenticationValidator)
        {
            string requestBodyText;

            using (var streamReader = new StreamReader(request.Body))
            {
                requestBodyText = await streamReader.ReadToEndAsync().ConfigureAwait(true);
            }
            JObject o = JObject.Parse(requestBodyText);
            var     graphqlRequest = new GraphQLRequest {
                Query         = o["query"]?.ToString(),
                Variables     = o["variables"]?.ToString(),
                Mutation      = o["mutation"]?.ToString(),
                OperationName = o["operationName"]?.ToString()
            };

            var result = await new DocumentExecuter().ExecuteAsync(new ExecutionOptions
            {
                Schema          = schema,
                Query           = o["query"]?.ToString(),
                OperationName   = o["operationName"]?.ToString(),
                Inputs          = o["variables"]?.ToString().ToInputs(),
                UserContext     = session,
                ValidationRules = (new [] { _graphqlAuthenticationValidator }).Concat(DocumentValidator.CoreRules())
            }).ConfigureAwait(true);

            return(result);
        }
Esempio n. 29
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();
            services.AddHealthChecks();
            services.AddControllers();

            services.AddEntityFrameworkSqlite()
            .AddDbContext <IContext, Context>(ops => ops.UseSqlite(@"Data Source=.\Data\Data.db"),
                                              ServiceLifetime.Transient);


            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            //grahql stuff
            services.AddSingleton <IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));
            services.AddSingleton <ISchema, RootSchema>();

            services.AddGraphQL(o =>
            {
                o.EnableMetrics    = true;
                o.ExposeExceptions = !_env.IsProduction();
            })
            .AddGraphTypes();

            // out of the box auth stuff
            services.TryAddSingleton <IAuthorizationEvaluator, AuthorizationEvaluator>();
            // comment out below for diy role-based auth
            //services.AddTransient<IValidationRule, AuthorizationValidationRule>();

            // attribute based auth
            services.AddScoped <IValidationRule, ProductIdValidator>();
            services.AddScoped <IDocumentExecutionListener, AttributeBasedAuthDocumentListener>();

            services.TryAddSingleton(s =>
            {
                var authSettings = new AuthorizationSettings();

                authSettings.AddPolicy("AdminPolicy", _ => _.RequireClaim("role", "Admin"));

                return(authSettings);
            });

            services.AddScoped <ExecutionOptions>(s =>
            {
                var ops = new ExecutionOptions
                {
                    Schema           = s.GetRequiredService <ISchema>(),
                    ValidationRules  = s.GetRequiredService <IEnumerable <IValidationRule> >().Concat(DocumentValidator.CoreRules()),
                    FieldMiddleware  = new FieldMiddlewareBuilder().Use <AuthorizeMiddleware>(),
                    EnableMetrics    = true,
                    ExposeExceptions = !_env.IsProduction()
                };
                foreach (var listener in s.GetRequiredService <IEnumerable <IDocumentExecutionListener> >())
                {
                    ops.Listeners.Add(listener);
                }

                return(ops);
            });
        }
Esempio n. 30
0
 static FixIdTypeRule()
 {
     //initialize a static field in case anyone wants to use it without creating a list
     validationRules = DocumentValidator.CoreRules();
     validationRules.Insert(0, new FixIdTypeRule());
 }