public static APIKey loadThisAPIKey(SqlConnection connection, string key)
        {
            APIKey returnMe = null;

            /* Make sure that the API key is valid - if not, do not attempt an SQL query with it */

            /* API keys are 40 characters */
            if (key.Length != 40)
            {
                return(null);
            }

            /* Check for non alphanumeric characters */
            Regex r = new Regex("^[a-zA-Z0-9]*$");

            if (!r.IsMatch(key))
            {
                return(null);
            }

            /* TODO: figure out other ways to validate it... */

            /* Attempt to load the API key from the database */
            SqlCommand sqlCommand = new SqlCommand();

            sqlCommand.Connection  = connection;
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.CommandText = "SELECT * FROM api_keys WHERE api_key=@APIKEY AND active=1;";
            sqlCommand.Parameters.AddWithValue("@APIKEY", key);
            sqlCommand.Connection.Open();
            SqlDataReader dataReader = sqlCommand.ExecuteReader();

            if (dataReader.HasRows)
            {
                while (dataReader.Read())
                {
                    returnMe = new APIKey(
                        dataReader["api_key"].ToString().Trim(),
                        dataReader["username"].ToString().Trim(),
                        dataReader["description"].ToString().Trim(),
                        DateTime.Parse(dataReader["date_issued"].ToString().Trim()),
                        DateTime.Parse(dataReader["date_expires"].ToString().Trim()),
                        bool.Parse(dataReader["is_internal_only"].ToString().Trim())
                        );
                }
            }

            sqlCommand.Connection.Close();
            return(returnMe);
        }
 public static bool logAPIKeyUse(SqlConnection connection, APIKey key, string url, string useragent, string ip)
 {
     try
     {
         SqlCommand sqlCommand = new SqlCommand();
         sqlCommand.Connection  = connection;
         sqlCommand.CommandType = CommandType.Text;
         sqlCommand.CommandText = "INSERT INTO key_access_log(dDate, api_key, url_accessed, user_agent, remote_ip, key_user) VALUES(@DATE, @KEY, @URL, @USERAGENT, @IP, @USER)";
         sqlCommand.Parameters.AddWithValue("@DATE", DateTime.Now);
         sqlCommand.Parameters.AddWithValue("@KEY", key.key);
         sqlCommand.Parameters.AddWithValue("@URL", url);
         sqlCommand.Parameters.AddWithValue("@USERAGENT", useragent);
         sqlCommand.Parameters.AddWithValue("@IP", ip);
         sqlCommand.Parameters.AddWithValue("@USER", key.username);
         sqlCommand.Connection.Open();
         sqlCommand.ExecuteNonQuery();
         sqlCommand.Connection.Close();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
        protected void Page_Init(object sender, EventArgs e)
        {
            // Check the IP to make sure traffic originates from within our network
            if (
                !(
                    (Request.ServerVariables["REMOTE_ADDR"].Contains("127.0.0.1")) ||
                    (Request.ServerVariables["REMOTE_ADDR"].Contains("::1"))
                    )
                )
            {
                if (!Request.ServerVariables["REMOTE_ADDR"].StartsWith(localNetworkChunk))
                {
                    Response.Redirect(outsideErrorMessage);
                    Response.End();
                }
            }


            String dbConnectionString = ConfigurationManager.ConnectionStrings["DataExplorerDatabase"].ConnectionString;
            APIKey apiKey             = null;

            /* Check for an API key */
            if (!string.IsNullOrEmpty(Request.QueryString["apikey"]))
            {
                using (SqlConnection connection = new SqlConnection(dbConnectionString))
                {
                    apiKey = APIKey.loadThisAPIKey(connection, Request.QueryString["apikey"]);
                }

                if (apiKey != null)
                {
                    if (apiKey.internalOnly)
                    {
                        if (
                            !(
                                (Request.ServerVariables["REMOTE_ADDR"].Contains("127.0.0.1")) ||
                                (Request.ServerVariables["REMOTE_ADDR"].Contains("::1"))
                                )
                            )
                        {
                            apiKey = null;
                        }
                    }
                }

                /* If they key is used, log it */
                if (apiKey != null)
                {
                    using (SqlConnection connection = new SqlConnection(dbConnectionString))
                    {
                        APIKey.logAPIKeyUse(connection, apiKey, Request.ServerVariables["UNENCODED_URL"], Request.ServerVariables["HTTP_USER_AGENT"], Request.ServerVariables["REMOTE_ADDR"]);
                    }
                }
            }


            /* Check for a username */
            if (!string.IsNullOrEmpty(getSessionIDFromCookies()))
            {
                using (SqlConnection connection = new SqlConnection(dbConnectionString))
                {
                    loggedInUser = session.loadThisSession(connection, getSessionIDFromCookies(), Request.ServerVariables["REMOTE_ADDR"], Request.ServerVariables["HTTP_USER_AGENT"]);
                }
            }

            if ((loggedInUser == null) && (apiKey == null))
            {
                if (!Request.ServerVariables["SCRIPT_NAME"].ToLower().Equals(loginURL.ToLower()))
                {
                    redirectToLogin();
                }
            }

            /* Check to see if the the page is restricted to admins only */
            if (MainMenu == null)
            {
                MainMenu = Nav.getMainMenu();
            }
            List <string> restrictedPages = new List <string>();

            foreach (NavMenuItem item in MainMenu)
            {
                if (item.admin_only)
                {
                    restrictedPages.Add(item.url);
                }
            }

            bool grantAccess = true;

            foreach (string restrictedURL in restrictedPages)
            {
                if (Request.RawUrl.ToLower().Contains(restrictedURL.ToLower()))
                {
                    if (!loggedInUser.is_admin)
                    {
                        grantAccess = false;
                    }
                }
            }

            if (!grantAccess)
            {
                Response.Write("Your user account does not have access to this page.");
                Response.End();
            }
        }