Exemplo n.º 1
0
        public async Task InvokeAsync(HttpContext context, IApiClientService apiClientService)
        {
            // If we are calling from localhost, don't bother using an API key.
            if (context.Connection.RemoteIpAddress.Equals(IPAddress.Parse("::1")))
            {
                await _next(context);

                return;
            }

            // API Key was not found.
            if (!context.Request.Headers.ContainsKey("x-api-key"))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync(JSON.Serialize(new
                {
                    message   = "No API key supplied.",
                    errorCode = "noApiKey"
                }));

                return;
            }

            var apiClient = await apiClientService.GetForKeyAsync(context.Request.Headers["x-api-key"]);

            if (apiClient == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync(JSON.Serialize(new
                {
                    message   = "An invalid API Key was supplied.",
                    errorCode = "wrongApiKey"
                }));

                return;
            }

            // Continue executing.
            await _next(context);
        }