Ejemplo n.º 1
0
        private static void SeedDatabase(IDocumentStore documentStore)
        {
            using (var session = documentStore.OpenSession())
            {
                var adminUser = new Account
                {
                    CodingExperience = 10,
                    Company = "AGRC",
                    Confirmation = new EmailConfirmation(ConfigurationManager.AppSettings["api_explorer_api_key"])
                    {
                        ConfirmationDate = DateTime.UtcNow,
                        Confirmed = true,
                        TimesSent = 0
                    },
                    ContactRoute = "email",
                    Email = ConfigurationManager.AppSettings["admin_email"],
                    FirstName = "AGRC",
                    JobCategory = "Geography",
                    JobTitle = "Government",
                    KeyQuota = new KeyQuota(1)
                    {
                        KeysUsed = 1
                    },
                    LastName = "AGRC",
                    Password = CommandExecutor.ExecuteCommand(new HashPasswordCommand(ConfigurationManager.AppSettings["admin_password"])).Result
                };

                if (!session.Query<Account>().Any(x => x.Email == ConfigurationManager.AppSettings["admin_email"]))
                {
                    session.Store(adminUser);

                    var explorerKey = new ApiKey(ConfigurationManager.AppSettings["api_explorer_api_key"])
                    {
                        AccountId = adminUser.Id,
                        ApiKeyStatus = ApiKey.KeyStatus.Active,
                        AppStatus = ApiKey.ApplicationStatus.Production,
                        CreatedAtTicks = DateTime.UtcNow.Ticks,
                        Deleted = false,
                        IsMachineName = false,
                        Pattern = ".*/beta/webapi/*",
                        RegexPattern = ".*/beta/webapi/*",
                        Type = ApiKey.ApplicationType.Browser
                    };

                    session.Store(explorerKey);
                }

                if (!session.Query<AdminContainer>().Any())
                {
                    session.Store(new AdminContainer(ConfigurationManager.AppSettings["admin_email"].Split(';')));
                }

                session.SaveChanges();
            }
        }
 public KeyCreatedEmailCommand(Account account, ApiKey newKey)
 {
     Account = account;
     NewKey = newKey;
 }
Ejemplo n.º 3
0
 public WhitelistItems(string key, ApiKey.KeyStatus status)
 {
     Key = key;
     Status = status;
 }
Ejemplo n.º 4
0
 public LogRequestCommand(ApiKey key, object container, IDocumentStore store)
 {
     _store = store;
     Key = key;
     Container = container;
 }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (!request.Properties.Any())
            {
                //properties is null under test need to add basic configuration
                request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
            }

            if (DocumentStore == null || DocumentStore.WasDisposed)
            {
                DocumentStore = request.GetDependencyScope().GetService(typeof (IDocumentStore)) as IDocumentStore;
            }

            var apikey = await ApiKeyProvider.GetApiFromRequestAsync(request);

            if (string.IsNullOrWhiteSpace(apikey))
            {
                var response = request.CreateResponse(HttpStatusCode.BadRequest,
                    new ResultContainer
                    {
                        Status = (int) HttpStatusCode.BadRequest,
                        Message = "Missing API key."
                    }, new MediaTypeHeaderValue("application/json"));

                return response;
            }

            using (var s = DocumentStore.OpenSession())
            {
                _invalidResponse = request.CreateResponse(HttpStatusCode.BadRequest,
                    new ResultContainer
                    {
                        Status = (int) HttpStatusCode.BadRequest,
                        Message = "Invalid API key."
                    }, new MediaTypeHeaderValue("application/json"));

                var key = s.Query<ApiKey, IndexApiKey>()
                    .Customize(c => c.WaitForNonStaleResultsAsOfNow())
                    .Include(x => x.AccountId)
                    .SingleOrDefault(x => x.Key == apikey);

                if (key == null && apikey != "agrc-ago")
                {
                    return _invalidResponse;
                }

                var validateUser = true;

                // TODO: some sort of agency ago whitelist container
                if (apikey == "agrc-ago")
                {
                    // referrer: http://utah.maps.arcgis.com/home/webmap/viewer.html?useExisting=1

                    key = new ApiKey(apikey)
                    {
                        RegexPattern = @"^http(?:s)?://(?:utah\.maps|www)\.arcgis\.com",
                        Type = ApiKey.ApplicationType.Browser,
                        AppStatus = ApiKey.ApplicationStatus.Production
                    };

#if DEBUG
                    key.RegexPattern = ".*";
#endif

                    validateUser = false;
                }

                var isWhitelisted = s.Query<WhitelistContainer>()
                    .SingleOrDefault(x => x.Items.Any(y => y.Key == key.Key));

                if (isWhitelisted != null)
                {
                    return await base.SendAsync(request, cancellationToken);
                }

                if (validateUser)
                {
                    var user = s.Load<Account>(key.AccountId);

                    if (user == null || !user.Confirmation.Confirmed)
                    {
                        return request.CreateResponse(HttpStatusCode.BadRequest,
                            new ResultContainer
                            {
                                Status = (int) HttpStatusCode.BadRequest,
                                Message =
                                    "Invalid key owner. Key does not belong to user or user has not been confirmed. " +
                                    "Browse to your profile and click the confirm button next to your email. " +
                                    "Follow the instructions in your inbox."
                            },
                            new MediaTypeHeaderValue("application/json"));
                    }

                    if (key.Deleted || key.ApiKeyStatus == ApiKey.KeyStatus.Disabled)
                    {
                        return request.CreateResponse(HttpStatusCode.BadRequest,
                            new ResultContainer
                            {
                                Status = (int) HttpStatusCode.BadRequest,
                                Message = "Key no longer exists or has been deactivated."
                            },
                            new MediaTypeHeaderValue("application/json"));
                    }
                }

                var response = await ValidateRequest(key, request, cancellationToken);

                if (response != null)
                {
                    return response;
                }
            }

            return await base.SendAsync(request, cancellationToken);
        }
        private async Task<HttpResponseMessage> ValidateRequest(ApiKey key, HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (key.Type == ApiKey.ApplicationType.Browser)
            {
                var pattern = new Regex(key.RegexPattern, RegexOptions.IgnoreCase);

                var referrer = request.Headers.Referrer;
                var hasOrigin = request.Headers.Where(x => x.Key == Origin).ToList();

                if (referrer == null && !hasOrigin.Any())
                {
                    return request.CreateResponse(HttpStatusCode.BadRequest,
                        new ResultContainer
                        {
                            Status = (int) HttpStatusCode.BadRequest,
                            Message = "Referrer http header is missing. " +
                                      "Turn off any security solutions that hide this header to use this service."
                        },
                        new MediaTypeHeaderValue("application/json"));
                }

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

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

                if (key.AppStatus == ApiKey.ApplicationStatus.Development &&
                    IsLocalDevelopment(referrer, corsOriginValue))
                {
                    return await base.SendAsync(request, cancellationToken);
                }

                if (!ApiKeyPatternMatches(pattern, corsOriginValue, referrer))
                {
                    return _invalidResponse;
                }
            }
            else
            {
                var ip = key.Pattern;
                var userHostAddress = IpProvider.GetIp(request);

                if (ip != userHostAddress)
                {
                    return request.CreateResponse(HttpStatusCode.BadRequest,
                        new ResultContainer
                        {
                            Status = (int) HttpStatusCode.BadRequest,
                            Message = string.Format("Invalid API key. Pattern does not match {0}.", userHostAddress)
                        },
                        new MediaTypeHeaderValue("application/json"));
                }
            }

            return null;
        }