Skip to content

Instantly share code, notes, and snippets.

@code-atom
Last active September 1, 2017 05:18
Show Gist options
  • Save code-atom/58baa0394df9eefbeffc6ec2186aa502 to your computer and use it in GitHub Desktop.
Save code-atom/58baa0394df9eefbeffc6ec2186aa502 to your computer and use it in GitHub Desktop.
IP block ASP.NET Module
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.Script.Serialization;
namespace Website.App_Code
{
public class IPAddressLocation
{
public string ip { get; set; }
public string country_code { get; set; }
public string country_name { get; set; }
public string region_code { get; set; }
public string region_name { get; set; }
public string city { get; set; }
public string zip_code { get; set; }
public string time_zone { get; set; }
public float latitude { get; set; }
public float longitude { get; set; }
public int metro_code { get; set; }
}
public class IPBlockModule : IHttpModule
{
private EventHandler onBeginRequest;
private static string _defaultCookieValue = "NCUTY";
public IPBlockModule()
{
onBeginRequest = new EventHandler(this.HandleBeginRequest);
}
void IHttpModule.Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += onBeginRequest;
}
void HandleBeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (ModuleEnabled())
{
if (app != null)
{
var countryCookie = app.Context.Request.Cookies["country"];
if (countryCookie == null || String.IsNullOrEmpty(countryCookie.Value))
{
var countryCode = GetCountryCode(app.Context);
countryCookie = new HttpCookie("country", countryCode);
if (countryCode == _defaultCookieValue) goto SecureLog;
countryCookie.Expires = DateTime.Now.AddMinutes(30);
app.Context.Response.Cookies.Add(countryCookie);
}
if (!string.IsNullOrEmpty(countryCookie.Value) && "ZA" == countryCookie.Value.ToUpper())
{
LogSecureAccessFile(app.Context.Request.UserHostAddress, countryCookie.Value, DateTime.Now, app.Context.Request.Path, "Deny");
app.Context.Response.Redirect("~/", true);
}
SecureLog:
LogSecureAccessFile(app.Context.Request.UserHostAddress, countryCookie.Value, DateTime.Now, app.Context.Request.Path, "Grant");
}
}
}
public static string GetCountryCode(HttpContext context)
{
return _GetCountryCodeFromIP(context.Request.UserHostAddress) ?? "_defaultCookieValue";
}
private static bool ModuleEnabled()
{
bool appSetting;
if (!bool.TryParse(ConfigurationManager.AppSettings["UseIPBlockModule"],
out appSetting))
appSetting = false;
return appSetting;
}
private static string _GetCountryCodeFromIP(string ipaddress)
{
try
{
string url = "http://freegeoip.net/json/" + ipaddress;
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
var deserializer = new JavaScriptSerializer();
var results = deserializer.Deserialize<IPAddressLocation>(jsonstring);
return String.IsNullOrEmpty(results.country_code) ? _defaultCookieValue : results.country_code;
}
catch (Exception ex)
{
return _defaultCookieValue;
}
}
private static void LogSecureAccessFile(string Ipaddress, string countryCode, DateTime date, string location, string authorize)
{
System.IO.StreamWriter sw = null;
try
{
sw = new StreamWriter(System.AppDomain.CurrentDomain.BaseDirectory + "SecureAccess.txt", true);
var str = String.Format("{0} : {1}, Country: {2}, Location {3}, Authorize {4}", date, Ipaddress, countryCode, location, authorize);
sw.WriteLine(str);
sw.WriteLine();
}
catch { }
finally { sw.Close(); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment