Exemplo n.º 1
0
        public async Task <IActionResult> Save([FromQuery] SaveLocationViewModel model)
        {
            try
            {
                if (await _apiClientRepository.Exists(model.ApiKey))
                {
                    var location = new Location
                    {
                        Latitude  = model.Latitude,
                        Longitude = model.Longitude,
                        Tracker   = new Tracker {
                            Tag = model.TrackerId
                        }
                    };

                    await _locationRepository.SaveLocation(location);

                    return(Ok(new { status = "success", message = "location successfully saved" }));
                }
                return(BadRequest(new ErrorModel {
                    Status = "error", Message = "invalid api key"
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new ErrorModel {
                    Status = "error", Message = ex.Message
                }));
            }
        }
        public async Task Invoke(HttpContext context, IApiClientRepository apiClientRepository)
        {
            if (context.Request.Path.Value.Contains("/api/v1/location/save", StringComparison.OrdinalIgnoreCase) || !context.Request.Path.Value.Contains("/api/", StringComparison.OrdinalIgnoreCase))
            {
                await _next.Invoke(context);
            }
            else
            {
                if (!context.Request.Headers.Keys.Any(h => h.Equals("ApiKey", StringComparison.OrdinalIgnoreCase)))
                {
                    context.Response.Headers["WWW-Authenticate"] = $" ApiKey error=\"missing\", error_description=\"apikey is not present\"";
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsync("Api Key is missing");

                    return;
                }
                else
                {
                    var apiKey = context.Request.Headers.FirstOrDefault(h => h.Key.Equals("ApiKey", StringComparison.OrdinalIgnoreCase)).Value;
                    if (!await apiClientRepository.Exists(apiKey))
                    {
                        context.Response.Headers["WWW-Authenticate"] = $" ApiKey error=\"invalid_apiKey\", error_description=\"apikey is not recognize\"";
                        context.Response.StatusCode = 401;
                        await context.Response.WriteAsync("Invalid Api Key");

                        return;
                    }
                }
                await _next.Invoke(context);
            }
        }