Exemplo n.º 1
0
 /// <summary>
 /// Instantiates a new <see cref="DelegateEndpointConventionBuilder" /> given a single
 /// <see cref="IEndpointConventionBuilder" />.
 /// </summary>
 /// <param name="endpointConventionBuilder">The <see cref="IEndpointConventionBuilder" /> to instantiate with.</param>
 internal DelegateEndpointConventionBuilder(IEndpointConventionBuilder endpointConventionBuilder)
 {
     _endpointConventionBuilders = new List <IEndpointConventionBuilder>()
     {
         endpointConventionBuilder
     };
 }
Exemplo n.º 2
0
 public void Apply(IEndpointConventionBuilder builder)
 {
     foreach (var a in this._actions)
     {
         builder.Add(a);
     }
 }
Exemplo n.º 3
0
 /// <summary>
 /// Instantiates a new <see cref="RouteHandlerBuilder" /> given a single
 /// <see cref="IEndpointConventionBuilder" />.
 /// </summary>
 /// <param name="endpointConventionBuilder">The <see cref="IEndpointConventionBuilder" /> to instantiate with.</param>
 internal RouteHandlerBuilder(IEndpointConventionBuilder endpointConventionBuilder)
 {
     _endpointConventionBuilders = new List <IEndpointConventionBuilder>()
     {
         endpointConventionBuilder
     };
 }
Exemplo n.º 4
0
 public void Execute(IEndpointConventionBuilder endpointConventionBuilder)
 {
     foreach (var deferredConvention in _deferredConventions)
     {
         endpointConventionBuilder.Add(deferredConvention);
     }
 }
        /// <summary>
        /// Adds Easy.Endpoints routes to EndpointRouteBuilder
        /// </summary>
        /// <param name="endpoints">Microsoft.AspNetCore.Routing.IEndpointRouteBuilder to add Easy.Endpoints to</param>
        /// <returns>Returns Microsoft.AspNetCore.Builder.IEndpointConventionBuilder for endpoints</returns>
        public static IEndpointConventionBuilder MapEasyEndpoints(
            this IEndpointRouteBuilder endpoints)
        {
            var requestEndPoints = endpoints.ServiceProvider.GetRequiredService <IEndpointManifest>().ToArray();
            var dataSource       = endpoints.DataSources.OfType <EasyEndpointDataSource>().FirstOrDefault();

            if (dataSource is null)
            {
                dataSource = new EasyEndpointDataSource();
                endpoints.DataSources.Add(dataSource);
            }
            var results = new IEndpointConventionBuilder[requestEndPoints.Length];
            var i       = 0;

            foreach (var endPoint in requestEndPoints)
            {
                var builder = new RouteEndpointBuilder(
                    BuildDelegate(endPoint),
                    endPoint.Pattern, endPoint.Order)
                {
                    DisplayName = endPoint.Name,
                };
                foreach (var meta in endPoint.Meta)
                {
                    builder.Metadata.Add(meta);
                }
                results[i] = dataSource.AddEndpointBuilder(builder);
                i++;
            }
            return(new GroupedEasyEndpointConventionBuilder(results));
        }
Exemplo n.º 6
0
 public static IEndpointConventionBuilder WithName(this IEndpointConventionBuilder endpointBuilder, string endpointName)
 {
     return(endpointBuilder.WithMetadata(
                new EndpointNameMetadata(endpointName),
                new RouteNameMetadata(endpointName)
                ));
 }
Exemplo n.º 7
0
 internal MinimalActionEndpointConventionBuilder(IEndpointConventionBuilder endpointConventionBuilder)
 {
     _endpointConventionBuilders = new List <IEndpointConventionBuilder>()
     {
         endpointConventionBuilder
     };
 }
Exemplo n.º 8
0
 private void ConfigureAuthorization(IEndpointConventionBuilder builder)
 {
     bool.TryParse(_config["enableCertAuth"], out var enableCertAuth);
     if (enableCertAuth)
     {
         builder.RequireAuthorization();
     }
 }
 public void ConfigureEndpoint(RequestMethod method, IEndpointConventionBuilder builder)
 {
     // Note the optional 'configure' parameter in EndpointBroker.BindEndpoint(...)
     if (ConfigureAction != null)
     {
         ConfigureAction.Invoke(method, builder);
     }
 }
Exemplo n.º 10
0
 public static IEndpointConventionBuilder RequireAuthorization(this IEndpointConventionBuilder builder, params string[] roles)
 {
     builder.Apply(endpointBuilder => endpointBuilder.Metadata.Add(new AuthorizeAttribute
     {
         Roles = string.Join(",", roles)
     }));
     return(builder);
 }
        /// <summary>
        /// Adds the default authorization policy to the endpoint(s).
        /// </summary>
        /// <param name="builder">The endpoint convention builder.</param>
        /// <returns>The original convention builder parameter.</returns>
        public static IEndpointConventionBuilder RequireAuthorization(this IEndpointConventionBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            return(builder.RequireAuthorization(new AuthorizeAttribute()));
        }
Exemplo n.º 12
0
        private static void Map <TRequest>(
            this IEndpointRouteBuilder endpoints,
            string pattern,
            HttpMethod method,
            string group = null,
            CommandEndpointResponse response = null,
            OpenApiOperation openApi         = null)
        {
            if (pattern.IsNullOrEmpty())
            {
                throw new ArgumentNullException($"{typeof(TRequest)} cannot be registered with a null or empty route pattern.");
            }

            if (!pattern.StartsWith('/'))
            {
                pattern = $"/{pattern}"; // ensure leading pattern slash
            }

            var mediator = endpoints.ServiceProvider.GetService <IMediator>()
                           ?? throw new InvalidOperationException("IMediator has not been added to IServiceCollection. You can add it with services.AddMediatR(...);");
            var configuration = endpoints.ServiceProvider.GetService <ICommandEndpointConfiguration>() // =singleton
                                ?? throw new InvalidOperationException("ICommandEndpointRegistrations has not been added to IServiceCollection. You can add it with services.AddCommandEndpoints(...);");
            var registration = configuration.AddRegistration <TRequest>(pattern, method);

            registration.OpenApi = openApi ?? new OpenApiOperation()
            {
                GroupName = group ?? pattern.SliceFromLast("/").SliceTill("?").SliceTill("{").EmptyToNull() ?? "Undefined"
            };
            registration.Response = response;

            IEndpointConventionBuilder builder = null;

            if (method == HttpMethod.Get)
            {
                builder = endpoints.MapGet(pattern.SliceTill("?"), CommandEndpointRequestHandler.InvokeAsync);
            }
            else if (method == HttpMethod.Post)
            {
                builder = endpoints.MapPost(pattern.SliceTill("?"), CommandEndpointRequestHandler.InvokeAsync);
            }
            else if (method == HttpMethod.Put)
            {
                builder = endpoints.MapPut(pattern.SliceTill("?"), CommandEndpointRequestHandler.InvokeAsync);
            }
            else if (method == HttpMethod.Delete)
            {
                builder = endpoints.MapDelete(pattern.SliceTill("?"), CommandEndpointRequestHandler.InvokeAsync);
            }

            //else if (method == HttpMethod.Patch)
            //{
            //    builder = endpoints.MapPatch(pattern.SliceTill("?"), CommandEndpointRequestDelegate);
            //}

            builder?.WithDisplayName(registration.Name);
            builder?.WithMetadata(registration);
        }
Exemplo n.º 13
0
        private void ConfigureAuthorization(IEndpointConventionBuilder builder)
        {
#if NET5_0_OR_GREATER
            bool.TryParse(_config["enableCertAuth"], out var enableCertAuth);
            if (enableCertAuth)
            {
                builder.RequireAuthorization();
            }
#endif
        }
Exemplo n.º 14
0
        public static IEndpointConventionBuilder RequireFeature(this IEndpointConventionBuilder builder, string featureName)
        {
            builder.Add(endpointBuilder =>
            {
                var featureGate = new EndpointFeatureGateAttribute(true, featureName);

                endpointBuilder.Metadata.Add(featureGate);
            });

            return(builder);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Adds a CORS policy with the specified name to the endpoint(s).
        /// </summary>
        /// <param name="builder">The endpoint convention builder.</param>
        /// <param name="policyName">The CORS policy name.</param>
        /// <returns>The original convention builder parameter.</returns>
        public static IEndpointConventionBuilder WithCorsPolicy(this IEndpointConventionBuilder builder, string policyName)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.Add(endpointBuilder =>
            {
                endpointBuilder.Metadata.Add(new EnableCorsAttribute(policyName));
            });
            return(builder);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Sets the <see cref="EndpointBuilder.DisplayName"/> to the provided <paramref name="displayName"/> for all
        /// builders created by <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder">The <see cref="IEndpointConventionBuilder"/>.</param>
        /// <param name="displayName">The display name.</param>
        /// <returns>The <see cref="IEndpointConventionBuilder"/>.</returns>
        public static IEndpointConventionBuilder WithDisplayName(this IEndpointConventionBuilder builder, string displayName)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.Add(b =>
            {
                b.DisplayName = displayName;
            });

            return(builder);
        }
        public static IEndpointConventionBuilder RequireAuthorization(this IEndpointConventionBuilder builder, params string[] policyNames)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (policyNames == null)
            {
                throw new ArgumentNullException(nameof(policyNames));
            }

            return(builder.RequireAuthorization(policyNames.Select(n => new AuthorizeAttribute(n)).ToArray()));
        }
Exemplo n.º 18
0
        /// <summary>
        /// Adds <typeparamref name="TComponent"/> to the list of components registered with this <see cref="ComponentHub"/> instance.
        /// </summary>
        /// <typeparam name="TComponent">The component type.</typeparam>
        /// <param name="builder">The <see cref="IEndpointConventionBuilder"/>.</param>
        /// <param name="selector">A CSS selector that identifies the DOM element into which the <typeparamref name="TComponent"/> will be placed.</param>
        /// <returns>The <paramref name="builder"/>.</returns>
        public static IEndpointConventionBuilder AddComponent <TComponent>(this IEndpointConventionBuilder builder, string selector)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }

            return(AddComponent(builder, typeof(TComponent), selector));
        }
Exemplo n.º 19
0
        protected virtual TestServer CreateStarWarsServer(
            string pattern = "/graphql",
            Action <IEndpointConventionBuilder> configureConventions = default)
        {
            return(ServerFactory.Create(
                       services => services
                       .AddRouting()
                       .AddHttpRequestSerializer(HttpResultSerialization.JsonArray)
                       .AddGraphQLServer()
                       .AddStarWarsTypes()
                       .AddTypeExtension <QueryExtension>()
                       .AddExportDirectiveType()
                       .AddStarWarsRepositories()
                       .AddInMemorySubscriptions()
                       .AddGraphQLServer("evict")
                       .AddQueryType(d => d.Name("Query"))
                       .AddTypeExtension <QueryExtension>()
                       .AddGraphQLServer("arguments")
                       .AddQueryType(d =>
            {
                d
                .Name("QueryRoot");

                d
                .Field("double_arg")
                .Argument("d", t => t.Type <FloatType>())
                .Type <FloatType>()
                .Resolve(c => c.ArgumentValue <double?>("d"));

                d
                .Field("decimal_arg")
                .Argument("d", t => t.Type <DecimalType>())
                .Type <DecimalType>()
                .Resolve(c => c.ArgumentValue <decimal?>("d"));
            }),
                       app => app
                       .UseWebSockets()
                       .UseRouting()
                       .UseEndpoints(endpoints =>
            {
                IEndpointConventionBuilder builder = endpoints.MapGraphQL(pattern);

                if (configureConventions is { })
                {
                    configureConventions(builder);
                }

                endpoints.MapGraphQL("/evict", "evict");
                endpoints.MapGraphQL("/arguments", "arguments");
            })));
Exemplo n.º 20
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseForwardedHeaders();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error");
            }

            app
            .UseMiddleware <RequestLoggingMiddleware>()
            .UseMiddleware <OpenTracingSpanTaggingMiddleware>()
            .UseSwagger()
            .UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Scaffold.WebApi v1");
            });

            app
            .UseRouting()
            .UseHttpMetrics()
            .UseAuthorization()
            .UseEndpoints(endpoints =>
            {
                IEndpointConventionBuilder healthCheckEndpoint = endpoints.MapHealthChecks("/health");

                if (this.Configuration["HealthCheckPort"] != null)
                {
                    healthCheckEndpoint.RequireHost($"*:{this.Configuration["HealthCheckPort"]}");
                }

                IEndpointConventionBuilder metricsEndpoint = endpoints.MapMetrics();

                if (this.Configuration["MetricsPort"] != null)
                {
                    metricsEndpoint.RequireHost($"*:{this.Configuration["MetricsPort"]}");
                }

                endpoints.MapControllers();
            });
        }
Exemplo n.º 21
0
        /// <summary>
        /// Requires that endpoints match one of the specified hosts during routing.
        /// </summary>
        /// <param name="builder">The <see cref="IEndpointConventionBuilder"/> to add the metadata to.</param>
        /// <param name="hosts">
        /// The hosts used during routing.
        /// Hosts should be Unicode rather than punycode, and may have a port.
        /// An empty collection means any host will be accepted.
        /// </param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IEndpointConventionBuilder RequireHost(this IEndpointConventionBuilder builder, params string[] hosts)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (hosts == null)
            {
                throw new ArgumentNullException(nameof(hosts));
            }

            builder.Add(endpointBuilder =>
            {
                endpointBuilder.Metadata.Add(new HostAttribute(hosts));
            });
            return(builder);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Sets the <see cref="EndpointBuilder.DisplayName"/> using the provided <paramref name="func"/> for all
        /// builders created by <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder">The <see cref="IEndpointConventionBuilder"/>.</param>
        /// <param name="func">A delegate that produces the display name for each <see cref="EndpointBuilder"/>.</param>
        /// <returns>The <see cref="IEndpointConventionBuilder"/>.</returns>
        public static IEndpointConventionBuilder WithDisplayName(this IEndpointConventionBuilder builder, Func <EndpointBuilder, string> func)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (func == null)
            {
                throw new ArgumentNullException(nameof(func));
            }

            builder.Add(b =>
            {
                b.DisplayName = func(b);
            });

            return(builder);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Adds <paramref name="componentType"/> to the list of components registered with this <see cref="ComponentHub"/> instance.
        /// The selector will default to the component name in lowercase.
        /// </summary>
        /// <param name="builder">The <see cref="IEndpointConventionBuilder"/>.</param>
        /// <param name="componentType">The component type.</param>
        /// <param name="selector">The component selector in the DOM for the <paramref name="componentType"/>.</param>
        /// <returns>The <paramref name="builder"/>.</returns>
        public static IEndpointConventionBuilder AddComponent(this IEndpointConventionBuilder builder, Type componentType, string selector)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (componentType == null)
            {
                throw new ArgumentNullException(nameof(componentType));
            }

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }

            builder.Add(endpointBuilder => AddComponent(endpointBuilder.Metadata, componentType, selector));
            return(builder);
        }
        public static IEndpointConventionBuilder RequireAuthorization(this IEndpointConventionBuilder builder, params IAuthorizeData[] authorizeData)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (authorizeData == null)
            {
                throw new ArgumentNullException(nameof(authorizeData));
            }

            builder.Apply(endpointBuilder =>
            {
                foreach (var data in authorizeData)
                {
                    endpointBuilder.Metadata.Add(data);
                }
            });
            return(builder);
        }
Exemplo n.º 25
0
    private static void ApplyAuthRolesAndPolicies(IEndpointConventionBuilder builder, bool auth, string roles,
                                                  params string[] policies)
    {
        if (policies is not null && policies.Any())
        {
            builder.RequireAuthorization(policies);
            return;
        }

        var hasRoles  = !string.IsNullOrWhiteSpace(roles);
        var authorize = new AuthorizeAttribute();

        if (hasRoles)
        {
            authorize.Roles = roles;
        }

        if (auth || hasRoles)
        {
            builder.RequireAuthorization(authorize);
        }
    }
Exemplo n.º 26
0
        /// <summary>
        /// Adds the provided metadata <paramref name="items"/> to <see cref="EndpointBuilder.Metadata"/> for all builders
        /// produced by <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder">The <see cref="IEndpointConventionBuilder"/>.</param>
        /// <param name="items">A collection of metadata items.</param>
        /// <returns>The <see cref="IEndpointConventionBuilder"/>.</returns>
        public static IEndpointConventionBuilder WithMetadata(this IEndpointConventionBuilder builder, params object[] items)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            builder.Add(b =>
            {
                foreach (var item in items)
                {
                    b.Metadata.Add(item);
                }
            });

            return(builder);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Adds the specified CORS policy to the endpoint(s).
        /// </summary>
        /// <param name="builder">The endpoint convention builder.</param>
        /// <param name="configurePolicy">A delegate which can use a policy builder to build a policy.</param>
        /// <returns>The original convention builder parameter.</returns>
        public static IEndpointConventionBuilder WithCorsPolicy(this IEndpointConventionBuilder builder, Action <CorsPolicyBuilder> configurePolicy)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (configurePolicy == null)
            {
                throw new ArgumentNullException(nameof(configurePolicy));
            }

            var policyBuilder = new CorsPolicyBuilder();

            configurePolicy(policyBuilder);
            var policy = policyBuilder.Build();

            builder.Add(endpointBuilder =>
            {
                endpointBuilder.Metadata.Add(new CorsPolicyMetadata(policy));
            });
            return(builder);
        }
    /// <summary>
    /// Adds a Banana Cake Pop endpoint to the endpoint configurations.
    /// </summary>
    /// <param name="endpointRouteBuilder">
    /// The <see cref="IEndpointConventionBuilder"/>.
    /// </param>
    /// <param name="toolPath">
    /// The path to which banana cake pop is mapped.
    /// </param>
    /// <param name="relativeRequestPath">
    /// The relative path on which the server is listening for GraphQL requests.
    /// </param>
    /// <returns>
    /// Returns the <see cref="IEndpointConventionBuilder"/> so that
    /// configuration can be chained.
    /// </returns>
    public static BananaCakePopEndpointConventionBuilder MapBananaCakePop(
        this IEndpointRouteBuilder endpointRouteBuilder,
        PathString?toolPath        = default,
        string?relativeRequestPath = "..")
    {
        if (endpointRouteBuilder is null)
        {
            throw new ArgumentNullException(nameof(endpointRouteBuilder));
        }

        toolPath ??= "/graphql/ui";
        relativeRequestPath ??= "..";

        RoutePattern        pattern         = Parse(toolPath.ToString() + "/{**slug}");
        IApplicationBuilder requestPipeline = endpointRouteBuilder.CreateApplicationBuilder();
        IFileProvider       fileProvider    = CreateFileProvider();

        requestPipeline
        .UseCancellation()
        .UseMiddleware <ToolDefaultFileMiddleware>(fileProvider, toolPath)
        .UseMiddleware <ToolOptionsFileMiddleware>(toolPath)
        .UseMiddleware <ToolStaticFileMiddleware>(fileProvider, toolPath)
        .Use(_ => context =>
        {
            context.Response.StatusCode = 404;
            return(Task.CompletedTask);
        });

        IEndpointConventionBuilder builder = endpointRouteBuilder
                                             .Map(pattern, requestPipeline.Build())
                                             .WithDisplayName("Banana Cake Pop Pipeline")
                                             .WithMetadata(new GraphQLEndpointOptions {
            GraphQLEndpoint = relativeRequestPath
        });

        return(new BananaCakePopEndpointConventionBuilder(builder));
    }
Exemplo n.º 29
0
 internal ComponentEndpointConventionBuilder(IEndpointConventionBuilder endpointConventionBuilder)
 {
     _endpointConventionBuilder = endpointConventionBuilder;
 }
 internal GraphQLHttpEndpointConventionBuilder(IEndpointConventionBuilder builder)
 {
     _builder = builder;
 }