Ejemplo n.º 1
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public async Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context != null)
            {
                IEndpointValidator validator = null;

                try
                {
                    if (context.RequestServices != null)
                    {
                        validator = context.RequestServices.GetService(Type.GetType(ValidatorType.AssemblyQualifiedName)) as IEndpointValidator;
                    }
                }
                catch { }

                if (validator == null)
                {
                    try
                    {
                        validator = Activator.CreateInstance(Type.GetType(ValidatorType.AssemblyQualifiedName)) as IEndpointValidator;
                    }
                    catch { }
                }

                if (validator != null)
                {
                    return(await validator.Validate(contextResolver).ConfigureAwait(false));
                }
            }

            return(null);
        }
Ejemplo n.º 2
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context != null)
            {
                IPipelineComponent pipeline = null;

                try
                {
                    if (context.RequestServices != null)
                    {
                        pipeline = context.RequestServices.GetService(Type.GetType(PipelineType.AssemblyQualifiedName)) as IPipelineComponent;
                    }
                }
                catch { }

                if (pipeline == null)
                {
                    try
                    {
                        pipeline = Activator.CreateInstance(Type.GetType(PipelineType.AssemblyQualifiedName)) as IPipelineComponent;
                    }
                    catch { }
                }

                if (pipeline != null)
                {
                    await pipeline.Invoke(contextResolver).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>Activates the <see cref="DeepSleep.Auth.IAuthorizationProvider" />.</summary>
        /// <remarks>
        /// For activation to be successful, the <see cref="IAuthorizationProvider" /> must contain a public parameterless constructor
        /// or be accessible via DI using <see cref="IServiceProvider"/>
        /// </remarks>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns>The <see cref="DeepSleep.Auth.IAuthorizationProvider" /></returns>
        protected virtual IAuthorizationProvider Activate(IApiRequestContextResolver contextResolver)
        {
            IAuthorizationProvider provider = null;

            var context = contextResolver?.GetContext();

            if (context != null)
            {
                try
                {
                    if (context.RequestServices != null)
                    {
                        provider = context.RequestServices.GetService(Type.GetType(typeof(T).AssemblyQualifiedName)) as IAuthorizationProvider;
                    }
                }
                catch { }

                if (provider == null)
                {
                    try
                    {
                        provider = Activator.CreateInstance(Type.GetType(typeof(T).AssemblyQualifiedName)) as IAuthorizationProvider;
                    }
                    catch { }
                }
            }

            return(provider);
        }
Ejemplo n.º 4
0
        /// <summary>Activates the <see cref="DeepSleep.Auth.IAuthenticationProvider" />.</summary>
        /// <remarks>
        /// For activation to be successful, the <see cref="IAuthenticationProvider" /> must contain a public parameterless constructor
        /// or be accessible via DI using <see cref="IServiceProvider"/>
        /// </remarks>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns>The <see cref="DeepSleep.Auth.IAuthenticationProvider" /></returns>
        public IAuthenticationProvider Activate(IApiRequestContextResolver contextResolver)
        {
            IAuthenticationProvider provider = null;
            var context = contextResolver?.GetContext();

            if (context != null)
            {
                try
                {
                    if (context.RequestServices != null)
                    {
                        provider = context.RequestServices.GetService(Type.GetType(AuthenticationProviderType.AssemblyQualifiedName)) as IAuthenticationProvider;
                    }
                }
                catch (Exception ex)
                {
                    context.Log(ex.ToString());
                }

                if (provider == null)
                {
                    try
                    {
                        provider = Activator.CreateInstance(Type.GetType(AuthenticationProviderType.AssemblyQualifiedName)) as IAuthenticationProvider;
                    }
                    catch (Exception ex)
                    {
                        context.AddInternalException(ex);
                        context.Log(ex.ToString());
                    }
                }
            }

            return(provider);
        }
Ejemplo n.º 5
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="apiRequestContextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver apiRequestContextResolver)
        {
            var context             = apiRequestContextResolver?.GetContext();
            var suggestedStatusCode = context.Configuration.ValidationErrorConfiguration.UriBindingErrorStatusCode;

            return(Task.FromResult(ApiValidationResult.Single("VALIDATOR-3", suggestedHttpStatusCode: suggestedStatusCode)));
        }
Ejemplo n.º 6
0
        /// <summary>Invokes the specified httpcontext.</summary>
        /// <param name="httpcontext">The httpcontext.</param>
        /// <param name="contextResolver">The context resolver.</param>
        /// <param name="requestPipeline">The request pipeline.</param>
        /// <param name="config">The config.</param>
        /// <returns></returns>
        public async Task Invoke(HttpContext httpcontext, IApiRequestContextResolver contextResolver, IApiRequestPipeline requestPipeline, IDeepSleepServiceConfiguration config)
        {
            var path = httpcontext?.Request?.Path.ToString() ?? string.Empty;

            if (!IsIncludedPath(path, config.IncludePaths))
            {
                await apinext.Invoke(httpcontext);

                return;
            }

            if (IsExcludedPath(path, config.ExcludePaths))
            {
                await apinext.Invoke(httpcontext);

                return;
            }

            contextResolver.SetContext(await BuildApiRequestContext(httpcontext));
            var context = contextResolver.GetContext();

            var defaultRequestConfiguration = context.RequestServices.GetService(typeof(IDeepSleepRequestConfiguration)) as IDeepSleepRequestConfiguration;

            await context.ProcessApiRequest(httpcontext, contextResolver, requestPipeline, defaultRequestConfiguration);
        }
Ejemplo n.º 7
0
        /// <summary>Runs this instance.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public virtual async Task Run(IApiRequestContextResolver contextResolver)
        {
            var first = pipeline.FirstOrDefault();

            if (first != null)
            {
                await first.TaskInvoker(contextResolver).ConfigureAwait(false);
            }
        }
Ejemplo n.º 8
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            await apinext.Invoke(contextResolver).ConfigureAwait(false);

            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            await context.ProcessHttpResponseMessages(contextResolver).ConfigureAwait(false);
        }
Ejemplo n.º 9
0
        /// <summary>Authenticates the request.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public async Task <AuthenticationResult> Authenticate(IApiRequestContextResolver contextResolver)
        {
            var provider = this.Activate(contextResolver);

            if (provider != null)
            {
                return(await provider.Authenticate(contextResolver).ConfigureAwait(false));
            }

            return(null);
        }
Ejemplo n.º 10
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context != null)
            {
                context.TryAddItem(nameof(CustomRequestPipelineComponent), "SET");
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 11
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            if (await context.ProcessHttpRequestCanceled().ConfigureAwait(false))
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Ejemplo n.º 12
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context             = contextResolver?.GetContext();
            var suggestedStatusCode = context.Configuration.ValidationErrorConfiguration.UriBindingErrorStatusCode;

            var results = new List <ApiValidationResult>();

            results.Add(ApiValidationResult.Failure("VALIDATOR-4.1", suggestedHttpStatusCode: suggestedStatusCode));
            results.Add(ApiValidationResult.Failure("VALIDATOR-4.2", suggestedHttpStatusCode: suggestedStatusCode));

            return(Task.FromResult(results as IList <ApiValidationResult>));
        }
Ejemplo n.º 13
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            await apinext.Invoke(contextResolver).ConfigureAwait(false);

            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var formatterFactory = context?.RequestServices?.GetService <IDeepSleepMediaSerializerFactory>();

            await context.ProcessHttpResponseBodyWriting(contextResolver, formatterFactory).ConfigureAwait(false);
        }
Ejemplo n.º 14
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            await apinext.Invoke(contextResolver).ConfigureAwait(false);

            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var defaultRequestConfiguration = context.RequestServices.GetService <IDeepSleepRequestConfiguration>();

            await context.ProcessHttpResponseCaching(defaultRequestConfiguration).ConfigureAwait(false);
        }
Ejemplo n.º 15
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var formUrlEncodedObjectSerializer = context?.RequestServices?.GetService <IFormUrlEncodedObjectSerializer>();

            if (await context.ProcessHttpRequestUriBinding(formUrlEncodedObjectSerializer).ConfigureAwait(false))
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Ejemplo n.º 16
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver.GetContext();
            var body    = context.Request.InvocationContext.Models <DataAnnotationsBodyModel>().FirstOrDefault();
            var uri     = context.Request.InvocationContext.Models <DataAnnotationsUriModel>().FirstOrDefault();

            if (body.Value != uri.Value)
            {
                return(Task.FromResult(ApiValidationResult.Single("Body value and Uri value must be the same")));
            }

            return(Task.FromResult(ApiValidationResult.Success()));
        }
Ejemplo n.º 17
0
        /// <summary>Processes the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public override Task <object> Process(IApiRequestContextResolver contextResolver, IList <string> errors)
        {
            if ((errors?.Count ?? 0) > 0)
            {
                var messages = errors
                               .Where(e => !string.IsNullOrWhiteSpace(e))
                               .Distinct()
                               .ToList();

                return(Task.FromResult(messages as object));
            }

            return(Task.FromResult(null as object));
        }
Ejemplo n.º 18
0
        /// <summary>Tasks the invoker.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public async Task TaskInvoker(IApiRequestContextResolver contextResolver)
        {
            var context            = contextResolver.GetContext();
            var registeredPipeline = this.pipeline.RegisteredPipeline;
            var index = registeredPipeline.FirstOrDefault(p => p.Value.type == this.type).Key;

            var next = (index >= registeredPipeline.Count - 1)
                ? new ApiRequestDelegate(TaskFinisher)
                : registeredPipeline[index + 1].requestDelegate;

            var instance = Activator.CreateInstance(this.type, new object[] { next }) as IPipelineComponent;

            await instance.Invoke(contextResolver).ConfigureAwait(false);
        }
Ejemplo n.º 19
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            try
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
            finally
            {
                var context = contextResolver
                              .GetContext()
                              .SetThreadCulure();

                await context.ProcessHttpResponseCrossOriginResourceSharing().ConfigureAwait(false);
            }
        }
Ejemplo n.º 20
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var routes               = context?.RequestServices.GetService <IApiRoutingTable>();
            var resolver             = context?.RequestServices.GetService <IUriRouteResolver>();
            var defaultRequestConfig = context?.RequestServices?.GetService <IDeepSleepRequestConfiguration>();

            if (await context.ProcessHttpRequestMethod(routes, resolver, defaultRequestConfig).ConfigureAwait(false))
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Ejemplo n.º 21
0
        public Task <AuthenticationResult> Authenticate(IApiRequestContextResolver contextResolver)
        {
            var context     = contextResolver.GetContext();
            var clientValue = context.Request.ClientAuthenticationInfo.AuthValue ?? string.Empty;
            var isMatch     = clientValue == "91E4BCD0-9C67-4AA1-9821-D2AC6B7AB037";

            if (!isMatch)
            {
                return(Task.FromResult(new AuthenticationResult("InvalidToken")));
            }

            var myIPrincipal = new SecurityContextPrincipal(1, new[] { "SiteUser" }, "AuthType");

            return(Task.FromResult(new AuthenticationResult(true, myIPrincipal)));
        }
Ejemplo n.º 22
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var routes   = context.RequestServices.GetService <IApiRoutingTable>();
            var resolver = context.RequestServices.GetService <IUriRouteResolver>();
            var defaultRequestConfiguration = context.RequestServices.GetService <IDeepSleepRequestConfiguration>();

            if (await context.ProcessHttpRequestCrossOriginResourceSharingPreflight(routes, resolver, defaultRequestConfiguration).ConfigureAwait(false))
            {
                await this.apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Ejemplo n.º 23
0
        /// <summary>Processes the HTTP response request processing.</summary>
        /// <param name="context">The context.</param>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <param name="apiServiceConfiguration">The API service configuration.</param>
        /// <returns></returns>
        public static async Task <bool> ProcessHttpResponseRequestProcessing(
            this ApiRequestContext context,
            IApiRequestContextResolver contextResolver,
            IDeepSleepServiceConfiguration apiServiceConfiguration)
        {
            if (apiServiceConfiguration?.OnRequestProcessed != null)
            {
                try
                {
                    await apiServiceConfiguration.OnRequestProcessed(contextResolver).ConfigureAwait(false);
                }
                catch { }
            }

            return(true);
        }
Ejemplo n.º 24
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context?.ValidationState() != ApiValidationState.Failed)
            {
                context.TryAddItem <string>("TestItem", "TestItemValue-ShouldBe-Overridden-First");
                context.UpsertItem <string>("TestItem", "TestItemValue-ShouldBe-Overridden");
                context.UpsertItem <string>("TestItem", "TestItemValue");
                context.TryAddItem <string>("TestItem", "TestItemValue-ShouldBe-Overridden-First");


                context.UpsertItem <string>("TestItem2", "TestItemValue2");
            }

            return(Task.FromResult(null as IList <ApiValidationResult>));
        }
Ejemplo n.º 25
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context?.ValidationState() != ApiValidationState.Failed)
            {
                if (context.Items.TryGetValue(nameof(CustomRequestPipelineComponent), out var beforeValidator))
                {
                    if (beforeValidator as string == "SET")
                    {
                        context.TryAddItem(nameof(RequestPipelineModelValidator), "VALIDATOR-SET");
                    }
                }
            }

            return(Task.FromResult(null as IList <ApiValidationResult>));
        }
Ejemplo n.º 26
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            try
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                var context = contextResolver
                              .GetContext()
                              .SetThreadCulure();

                var apiServiceConfiguration = context?.RequestServices?.GetService <IDeepSleepServiceConfiguration>();

                await context.ProcessHttpResponseUnhandledException(contextResolver, ex, apiServiceConfiguration).ConfigureAwait(false);
            }
        }
Ejemplo n.º 27
0
        /// <summary>Authenticates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <AuthenticationResult> Authenticate(IApiRequestContextResolver contextResolver)
        {
            var context    = contextResolver?.GetContext();
            var acceptable = "T0RrMlJqWXpNVFF0UmtReFF5MDBRamN5TFVJeE5qZ3RPVGxGTlRBek5URXdNVUkz";
            var authValue  = context.Request.ClientAuthenticationInfo.AuthValue ?? string.Empty;

            if (string.IsNullOrWhiteSpace(authValue))
            {
                return(Task.FromResult(new AuthenticationResult("EmptyStaticToken")));
            }

            if (authValue != acceptable)
            {
                return(Task.FromResult(new AuthenticationResult("InvalidStaticToken")));
            }

            return(Task.FromResult(new AuthenticationResult(true)));
        }
Ejemplo n.º 28
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var beforePipelines = context?.Configuration?.PipelineComponents?
                                  .Where(p => p.Placement == PipelinePlacement.BeforeEndpointValidation)
                                  .OrderBy(p => p.Order)
                                  .ToList() ?? new List <IRequestPipelineComponent>();

            foreach (var pipeline in beforePipelines)
            {
                await pipeline.Invoke(contextResolver).ConfigureAwait(false);
            }

            if (await context.ProcessHttpEndpointValidation().ConfigureAwait(false))
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Ejemplo n.º 29
0
        /// <summary>Processes the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public Task <object> Process(IApiRequestContextResolver contextResolver, IList <string> errors)
        {
            if ((errors?.Count ?? 0) > 0)
            {
                var messages = errors
                               .Where(e => !string.IsNullOrWhiteSpace(e))
                               .Distinct()
                               .Select(e => new ErrorMessage {
                    ErrorMessageStr = e
                })
                               .ToList();

                if (messages.Count > 0)
                {
                    return(Task.FromResult(new CommonErrorResponse
                    {
                        Messages = messages
                    } as object));
                }
            }

            return(Task.FromResult(null as object));
        }
Ejemplo n.º 30
0
        /// <summary>Authorizes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public Task <AuthorizationResult> Authorize(IApiRequestContextResolver contextResolver)
        {
            var context     = contextResolver.GetContext();
            var rolesNeeded = new List <string> {
                "AdminUser"
            };

            var principal = context.Request.ClientAuthenticationInfo.Principal;

            if ((principal?.Identity?.IsAuthenticated ?? false) == false)
            {
                return(Task.FromResult(new AuthorizationResult("NotAuthenticated")));
            }

            foreach (var role in rolesNeeded)
            {
                if (!principal.IsInRole(role))
                {
                    return(Task.FromResult(new AuthorizationResult("InaccessibleRole")));
                }
            }

            return(Task.FromResult(new AuthorizationResult(true)));
        }