public async Task Should_call_esrijson()
        {
            var httpContext = new DefaultHttpContext();

            httpContext.Request.QueryString = new QueryString("?format=esriJSON");

            var mediator = new Mock <IMediator>();
            var response = new ApiResponseContainer <Graphic> {
                Result = new Graphic(new Point(2, 2), new Dictionary <string, object>())
            };

            mediator.Setup(x => x.Send(It.IsAny <EsriGraphic.Command>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(response));

            var filter   = new JsonOutputFormatResultFilter(mediator.Object);
            var contexts = CreateContext(httpContext);

            await filter.OnResultExecutionAsync(contexts.ExecutingContext,
                                                () => Task.FromResult(contexts.ExecutedContext));

            var result  = contexts.ExecutingContext.Result as ObjectResult;
            var result2 = contexts.ExecutedContext.Result as ObjectResult;

            result.Value.ShouldBeOfType <ApiResponseContainer <Graphic> >();
            result2.Value.ShouldBeOfType <ApiResponseContainer <Graphic> >();
        }
        public async Task Should_call_geojson()
        {
            var httpContext = new DefaultHttpContext();

            httpContext.Request.QueryString = new QueryString("?format=GeoJSON");

            var mediator = new Mock <IMediator>();
            var response = new ApiResponseContainer <Feature> {
                Result = new Feature(new GeoJSON.Net.Geometry.Point(new Position(1, 1)))
            };

            mediator.Setup(x => x.Send(It.IsAny <GeoJsonFeature.Command>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(response));

            var filter   = new JsonOutputFormatResultFilter(mediator.Object);
            var contexts = CreateContext(httpContext);

            await filter.OnResultExecutionAsync(contexts.ExecutingContext,
                                                () => Task.FromResult(contexts.ExecutedContext));

            var result  = contexts.ExecutingContext.Result as ObjectResult;
            var result2 = contexts.ExecutedContext.Result as ObjectResult;

            result.Value.ShouldBeOfType <ApiResponseContainer <Feature> >();
            result2.Value.ShouldBeOfType <ApiResponseContainer <Feature> >();
        }
示例#3
0
        public async Task Should_handle_address_not_found()
        {
            var responseContainer = new ApiResponseContainer <GeocodeAddressApiResponse> {
                Result  = null,
                Message = "No address candidates found with a score of 70 or better.",
                Status  = 404
            };

            var request = new EsriGraphic.Command(responseContainer);
            var result  = await _handler.Handle(request, new CancellationToken());

            result.Result.ShouldBeNull();
            result.Message.ShouldBe(responseContainer.Message);
            result.Status.ShouldBe(responseContainer.Status);
        }
示例#4
0
        public async Task Should_convert_to_esri_graphic()
        {
            var responseContainer = new ApiResponseContainer <GeocodeAddressApiResponse> {
                Result = new GeocodeAddressApiResponse {
                    Candidates   = new Candidate[0],
                    InputAddress = "Input Address",
                    Location     = new Point {
                        X = 1,
                        Y = 1
                    },
                    Locator      = "Centerlines",
                    MatchAddress = "Matched Address",
                    Score        = 100,
                    Wkid         = 26912
                },
                Status = 200
            };

            var request = new EsriGraphic.Command(responseContainer);
            var result  = await _handler.Handle(request, new CancellationToken());

            var point = new EsriJson.Net.Geometry.Point(1, 1)
            {
                CRS = new Crs {
                    WellKnownId = 26912
                }
            };

            var attributes = new Dictionary <string, object> {
                { "location", new Point(1, 1) },
                { "score", 100.0 },
                { "locator", "Centerlines" },
                { "matchAddress", "Matched Address" },
                { "inputAddress", "Input Address" },
                { "scoreDifference", 0.0 }
            };

            var graphic    = JsonConvert.SerializeObject(new Graphic(point, attributes));
            var resultJson = JsonConvert.SerializeObject(result.Result);

            resultJson.ShouldBe(graphic);
        }
示例#5
0
            protected override ApiResponseContainer <Graphic> Handle(Command request)
            {
                EsriJsonObject geometry   = null;
                var            attributes = new Dictionary <string, object>();
                var            message    = request.Container.Message;
                var            status     = request.Container.Status;
                var            result     = request.Container.Result;

                if (result?.Location != null)
                {
                    geometry = new Point(result.Location.X, result.Location.Y)
                    {
                        CRS = new Crs {
                            WellKnownId = result.Wkid
                        }
                    };

                    attributes = JObject.FromObject(request.Container.Result)
                                 .ToObject <Dictionary <string, object> >();
                }

                if (geometry == null && attributes.Count < 1)
                {
                    return(new ApiResponseContainer <Graphic> {
                        Status = status,
                        Message = message
                    });
                }

                var graphic =
                    new Graphic(geometry,
                                attributes.Where(x => x.Value != null).ToDictionary(x => x.Key, y => y.Value));

                var responseContainer = new ApiResponseContainer <Graphic> {
                    Result  = graphic,
                    Status  = status,
                    Message = message
                };

                return(responseContainer);
            }
示例#6
0
        public async Task Should_convert_to_geojson_feature()
        {
            var responseContainer = new ApiResponseContainer <GeocodeAddressApiResponse> {
                Result = new GeocodeAddressApiResponse {
                    Candidates   = new Candidate[0],
                    InputAddress = "Input Address",
                    Location     = new Point {
                        X = 1,
                        Y = 1
                    },
                    Locator      = "Centerlines",
                    MatchAddress = "Matched Address",
                    Score        = 100,
                    Wkid         = 26912
                },
                Status = 200
            };

            var request = new GeoJsonFeature.Command(responseContainer);
            var result  = await _handler.Handle(request, new CancellationToken());

            var position   = new Position(1, 1);
            var point      = new GeoJSON.Net.Geometry.Point(position);
            var properties = new Dictionary <string, object> {
                { "location", new Point(1, 1) },
                { "score", 100.0 },
                { "locator", "Centerlines" },
                { "matchAddress", "Matched Address" },
                { "inputAddress", "Input Address" },
                { "scoreDifference", 0.0 }
            };

            var feature    = JsonConvert.SerializeObject(new Feature(point, properties));
            var resultJson = JsonConvert.SerializeObject(result.Result);

            resultJson.ShouldBe(feature);
        }
示例#7
0
            protected override ApiResponseContainer <Feature> Handle(Command request)
            {
                IGeometryObject geometry   = null;
                var             attributes = new Dictionary <string, object>();
                var             message    = request.Container.Message;
                var             status     = request.Container.Status;
                var             result     = request.Container.Result;

                if (result?.Location != null)
                {
                    geometry = new Point(new Position(result.Location.Y, result.Location.X));

                    attributes = JObject.FromObject(request.Container.Result)
                                 .ToObject <Dictionary <string, object> >();
                }

                if (geometry == null && attributes.Count < 1)
                {
                    return(new ApiResponseContainer <Feature> {
                        Status = status,
                        Message = message
                    });
                }

                var feature =
                    new Feature(geometry,
                                attributes.Where(x => x.Value != null).ToDictionary(x => x.Key, y => y.Value));

                var responseContainer = new ApiResponseContainer <Feature> {
                    Result  = feature,
                    Status  = status,
                    Message = message
                };

                return(responseContainer);
            }
示例#8
0
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            var key = _apiKeyProvider.Get(context.HttpContext.Request);

            // key hasn't been created
            if (string.IsNullOrWhiteSpace(key))
            {
                var missingResponse = new ApiResponseContainer
                {
                    Status  = BadRequest,
                    Message =
                        "Your API key is missing from your request. Add an `apikey={key}` to the request as a query string parameter."
                };

                context.Result = new BadRequestObjectResult(missingResponse);

                return;
            }

            var apiKey = await _repo.GetKey(key);

            var badKeyResponse = new ApiResponseContainer
            {
                Status  = BadRequest,
                Message = "Your API key does match the pattern created in the developer console. " +
                          $"Check the referrer header on the request with the pattern for the api key `{key}`"
            };

            // key hasn't been created
            if (apiKey == null)
            {
                context.Result = new BadRequestObjectResult(badKeyResponse);

                return;
            }

            // TODO handle whitelist

            // TODO make sure user has confirmed email address

            if (apiKey.Deleted || apiKey.ApiKeyStatus == ApiKey.KeyStatus.Disabled)
            {
                context.Result = new BadRequestObjectResult(new ApiResponseContainer
                {
                    Status  = BadRequest,
                    Message = $"{key} is no longer active. It has been disabled or deleted by it's owner."
                });

                return;
            }

            if (apiKey.Type == ApiKey.ApplicationType.Browser)
            {
                var pattern = new Regex(apiKey.RegexPattern, RegexOptions.IgnoreCase);

                if (!context.HttpContext.Request.Headers.TryGetValue("Referrer", out var referrer))
                {
                    context.HttpContext.Request.Headers.TryGetValue("Referer", out referrer);
                }

                var hasOrigin = context.HttpContext.Request.Headers.Where(x => x.Key == "Origin").ToList();

                if (string.IsNullOrEmpty(referrer.ToString()) && !hasOrigin.Any())
                {
                    context.Result = new BadRequestObjectResult(new ApiResponseContainer
                    {
                        Status  = BadRequest,
                        Message =
                            "The http referrer header is missing. Turn off any security solutions that may remove this " +
                            "header to use this service. If you are trying to test your query add the referer header via a tool like postman " +
                            "or browse to api.mapserv.utah.gov and use the api explorer."
                    });

                    return;
                }

                var corsOriginHeader = hasOrigin.FirstOrDefault();
                var corsOriginValue  = "";

                if (corsOriginHeader.Key != null)
                {
                    corsOriginValue = corsOriginHeader.Value.SingleOrDefault();
                }

                if (apiKey.AppStatus == ApiKey.ApplicationStatus.Development &&
                    IsLocalDevelopment(new Uri(referrer.ToString()), corsOriginValue))
                {
                    await next();

                    return;
                }

                if (!ApiKeyPatternMatches(pattern, corsOriginValue, new Uri(referrer.ToString())))
                {
                    context.Result = new BadRequestObjectResult(badKeyResponse);

                    return;
                }
            }
            else
            {
                var ip = apiKey.Pattern;
                var userHostAddress = _serverIpProvider.Get(context.HttpContext.Request);

                if (ip != userHostAddress)
                {
                    context.Result = new BadRequestObjectResult(new ApiResponseContainer
                    {
                        Status  = BadRequest,
                        Message =
                            $"Your API key does match the pattern created in the developer console for key `{key}`. " +
                            $"The request is not originiating from `{userHostAddress}`"
                    });

                    return;
                }
            }

            await next();
        }
示例#9
0
 public Command(ApiResponseContainer <GeocodeAddressApiResponse> container)
 {
     Container = container;
 }