コード例 #1
0
        private ExecuteMiddleware BuildMiddleware(
            IEnumerable <IDirective> directives)
        {
            Action <IDirectiveContext, IDirective> updateContext =
                (context, directive) =>
            {
                if (context is DirectiveContext c)
                {
                    c.Directive = directive;
                }
            };

            DirectiveDelegate component = async context =>
            {
                if (!context.IsResultModified)
                {
                    context.Result = await context.ResolveAsync <object>();
                }
            };

            foreach (IDirective directive in directives.Reverse())
            {
                component = BuildComponent(directive, updateContext, component);
            }

            return(async(context, executeResolver) =>
            {
                var directiveContext = new DirectiveContext(
                    context, executeResolver);
                await component.Invoke(directiveContext);

                return directiveContext.Result;
            });
        }
コード例 #2
0
        private static async Task AuthorizeAsync(
            IDirectiveContext context,
            DirectiveDelegate next)
        {
            AuthorizeDirective directive = context.Directive
                                           .ToObject <AuthorizeDirective>();

            ClaimsPrincipal principal = context
                                        .CustomProperty <ClaimsPrincipal>(nameof(ClaimsPrincipal));

            var allowed = IsInRoles(principal, directive.Roles);

#if !ASPNETCLASSIC
            if (allowed && NeedsPolicyValidation(directive))
            {
                allowed = await AuthorizeWithPolicyAsync(
                    context, directive, principal)
                          .ConfigureAwait(false);
            }
#endif
            if (allowed)
            {
                await next(context);
            }
            else if (context.Result == null)
            {
                context.Result = QueryError.CreateFieldError(
                    "The current user is not authorized to " +
                    "access this resource.",
                    context.Path,
                    context.FieldSelection);
            }
        }
コード例 #3
0
        public ReturnDirective(DirectiveDelegate next, JsonElement config)
        {
            _next = next;
            if (config.TryGetProperty("value", out var filesProperty))
            {
                if (filesProperty.ValueKind == JsonValueKind.String)
                {
                    string value = filesProperty.GetString();
                    if (string.IsNullOrEmpty(value))
                    {
                        throw new NullReferenceException("'value' property is null or empty.");
                    }
                    string[] returnData = value.Split(" ");
                    switch (returnData.Length)
                    {
                    case 1 when int.TryParse(returnData[0], out int statusCode):
                        _statusCode = statusCode;

                        _type = 1;
                        break;

                    case 1:
                        _statusCode = 301;
                        _data       = returnData[0];
                        _type       = 2;
                        break;

                    case >= 2: {
                        if (!int.TryParse(returnData[0], out int statusCode))
                        {
                            return;
                        }
                        _statusCode = statusCode;
                        if (returnData[1][0].Equals('"') && returnData[^ 1][returnData[^ 1].Length - 1].Equals('"'))
コード例 #4
0
        private static FieldDelegate BuildComponent(
            IDirective directive,
            FieldDelegate first)
        {
            FieldDelegate next = first;

            IReadOnlyList <DirectiveMiddleware> components =
                directive.MiddlewareComponents;

            for (int i = components.Count - 1; i >= 0; i--)
            {
                DirectiveDelegate component = components[i].Invoke(next);

                next = context =>
                {
                    if (HasErrors(context.Result))
                    {
                        return(Task.CompletedTask);
                    }

                    return(component.Invoke(
                               new DirectiveContext(context, directive)));
                };
            }

            return(next);
        }
コード例 #5
0
ファイル: DirectiveBuilder.cs プロジェクト: jpdante/HtcSharp
        public DirectiveDelegate Build()
        {
            DirectiveDelegate app = context => {
                // End of pipe-line
                context.Response.StatusCode = 404;
                return(context.Site.TemplateManager.TryGetTemplate("404", out var template) ? template.SendTemplate(context) : Task.CompletedTask);
            };

            return(_directives.Reverse().Aggregate(app, (current, component) => component(current)));
        }
コード例 #6
0
ファイル: SiteLocation.cs プロジェクト: jpdante/HtcSharp
        public SiteLocation(LocationConfig locationConfig, IServiceProvider serviceProvider)
        {
            Regex regex;

            switch (locationConfig.LocationType)
            {
            case LocationType.None:
            case LocationType.NoRegex:
                Match = httpContext => httpContext.Request.Path.Value.StartsWith(locationConfig.Location);
                break;

            case LocationType.Equal:
                Match = httpContext => httpContext.Request.Path.Value.Equals(locationConfig.Location);
                break;

            case LocationType.Regex:
                regex = new Regex(locationConfig.Location);
                Match = httpContext => regex.IsMatch(httpContext.Request.Path.Value);
                break;

            case LocationType.RegexCaseInsensitive:
                regex = new Regex(locationConfig.Location, RegexOptions.IgnoreCase);
                Match = httpContext => regex.IsMatch(httpContext.Request.Path.Value);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var directiveBuilder = new DirectiveBuilder(serviceProvider);
            var directiveManager = serviceProvider.GetService <DirectiveManager>();

            foreach (var directiveConfig in locationConfig.Directives)
            {
                if (!directiveConfig.TryGetProperty("type", out var property))
                {
                    continue;
                }
                string directiveName = property.GetString();
                if (string.IsNullOrEmpty(directiveName))
                {
                    throw new NullReferenceException("Directive name is empty or invalid.");
                }
                if (directiveManager.TryGetDirective(property.GetString(), out var directiveType))
                {
                    directiveBuilder.UseDirective(directiveType, directiveConfig);
                }
                else
                {
                    throw new UnknownDirectiveException($"Unknown directive '{directiveName}', missing plugin?");
                }
            }
            _directiveDelegate = directiveBuilder.Build();
        }
コード例 #7
0
 public AddHeaderDirective(DirectiveDelegate next, JsonElement config)
 {
     _next    = next;
     _headers = new Dictionary <string, string>();
     if (!config.TryGetProperty("headers", out var headersProperty))
     {
         return;
     }
     foreach (var property in headersProperty.EnumerateObject().Where(property => property.Value.ValueKind == JsonValueKind.String))
     {
         _headers.Add(property.Name, property.Value.GetString());
     }
 }
コード例 #8
0
        private static FieldDelegate BuildComponent(IDirective directive, FieldDelegate first)
        {
            FieldDelegate next = first;
            IReadOnlyList <DirectiveMiddleware> components = directive.MiddlewareComponents;

            for (var i = components.Count - 1; i >= 0; i--)
            {
                DirectiveDelegate component = components[i].Invoke(next);

                next = context =>
                {
                    if (HasErrors(context.Result))
                    {
                        return(default);
コード例 #9
0
        private static FieldDelegate BuildComponent(
            IDirective directive,
            FieldDelegate next)
        {
            DirectiveDelegate component = directive.Middleware.Invoke(next);

            return(context =>
            {
                if (HasErrors(context.Result))
                {
                    return Task.CompletedTask;
                }

                return component.Invoke(
                    new DirectiveContext(context, directive));
            });
        }
コード例 #10
0
        public IndexDirective(DirectiveDelegate next, JsonElement config)
        {
            _next = next;
            if (config.TryGetProperty("files", out var filesProperty))
            {
                ;
                switch (filesProperty.ValueKind)
                {
                case JsonValueKind.String: {
                    string value = filesProperty.GetString();
                    if (string.IsNullOrEmpty(value))
                    {
                        throw new NullReferenceException("'files' property cannot be null or empty.");
                    }
                    _files = new List <string> {
                        value.StartsWith("/") ? value : $"/{value}"
                    };
                    break;
                }

                case JsonValueKind.Array: {
                    _files = new List <string>();
                    foreach (var arrayElement in filesProperty.EnumerateArray())
                    {
                        string value = arrayElement.GetString();
                        if (string.IsNullOrEmpty(value))
                        {
                            continue;
                        }
                        _files.Add(value.StartsWith("/") ? value : $"/{value}");
                    }

                    break;
                }
                }
            }
            else
            {
                _files = new List <string> {
                    "/$internal",
                    "/index.html",
                    "/index.htm"
                };
            }
        }
コード例 #11
0
        public ExtensionProcessorDirective(DirectiveDelegate next, JsonElement config)
        {
            _next = next;
            if (config.TryGetProperty("paths", out var filesProperty))
            {
                switch (filesProperty.ValueKind)
                {
                case JsonValueKind.String: {
                    string value = filesProperty.GetString();
                    if (string.IsNullOrEmpty(value))
                    {
                        throw new NullReferenceException("'paths' property cannot be null or empty.");
                    }
                    _paths = new List <string> {
                        value
                    };
                    break;
                }

                case JsonValueKind.Array: {
                    _paths = new List <string>();
                    foreach (var arrayElement in filesProperty.EnumerateArray())
                    {
                        string value = arrayElement.GetString();
                        if (string.IsNullOrEmpty(value))
                        {
                            continue;
                        }
                        _paths.Add(value);
                    }

                    break;
                }

                default:
                    throw new NullReferenceException("'paths' property unknown type.");
                }
            }
            else
            {
                _paths = new List <string> {
                    "$uri"
                };
            }
        }
コード例 #12
0
        private DirectiveDelegate BuildComponent(
            IDirective directive,
            Action <IDirectiveContext, IDirective> updateContext,
            DirectiveDelegate next)
        {
            DirectiveDelegate component = directive.Middleware.Invoke(next);

            return(context =>
            {
                if (HasErrors(context.Result))
                {
                    return Task.CompletedTask;
                }

                updateContext(context, directive);
                return component.Invoke(context)
                .ContinueWith((task, state) =>
                              updateContext(context, directive), null);
            });
        }
コード例 #13
0
        private DirectiveDelegate BuildComponent(
            IDirective directive,
            Action <IDirectiveContext, IDirective> updateContext,
            DirectiveDelegate next)
        {
            DirectiveDelegate component = directive.Middleware.Invoke(next);

            return(context =>
            {
                context.Result = context.CompleteResolverResult(context.Result);

                if (HasErrors(context.Result))
                {
                    return Task.CompletedTask;
                }

                updateContext(context, directive);
                return component.Invoke(context);
            });
        }
コード例 #14
0
        private static async Task AuthorizeAsync(
            IDirectiveContext context,
            DirectiveDelegate next)
        {
#if !ASPNETCLASSIC
            IAuthorizationService authorizeService = context
                                                     .Service <IAuthorizationService>();
#endif
            ClaimsPrincipal principal = context
                                        .CustomProperty <ClaimsPrincipal>(nameof(ClaimsPrincipal));
            AuthorizeDirective directive = context.Directive
                                           .ToObject <AuthorizeDirective>();
            bool allowed = IsInRoles(principal, directive.Roles);

#if !ASPNETCLASSIC
            if (allowed && !string.IsNullOrEmpty(directive.Policy))
            {
                AuthorizationResult result = await authorizeService
                                             .AuthorizeAsync(principal, directive.Policy);

                allowed = result.Succeeded;
            }
#endif

            if (allowed)
            {
                await next(context);
            }
            else
            {
                context.Result = QueryError.CreateFieldError(
                    "The current user is not authorized to " +
                    "access this resource.",
                    context.Path,
                    context.FieldSelection);
            }
        }
コード例 #15
0
 public TestDirective(DirectiveDelegate next, JsonElement config)
 {
     Name  = config.GetProperty("name").GetString();
     _next = next;
 }
コード例 #16
0
 public ListDirectoryDirective(DirectiveDelegate next, JsonElement config)
 {
     _next = next;
 }
コード例 #17
0
        public Task OnHttpExtensionProcess(DirectiveDelegate next, HtcHttpContext httpContext, string fileName, string extension)
        {
            var luaContext = new LuaContext(httpContext, fileName);

            return(luaContext.LoadFile() ? luaContext.ProcessRequest() : next(httpContext));
        }
コード例 #18
0
ファイル: PagesTest.cs プロジェクト: jpdante/HtcSharp
 public async Task OnHttpPageRequest(DirectiveDelegate next, HtcHttpContext httpContext, string fileName)
 {
     await httpContext.Response.WriteAsync($"Requested page: {fileName}");
 }