Skip to content

Commit

Permalink
[geo ip] determine country using geoip; added country info in session…
Browse files Browse the repository at this point in the history
… and cookies
  • Loading branch information
anandpdoshi committed Apr 18, 2013
1 parent 72a4b83 commit 2078d52
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 16 deletions.
Binary file added data/GeoIP.dat
Binary file not shown.
2 changes: 2 additions & 0 deletions webnotes/auth.py
Expand Up @@ -259,6 +259,8 @@ def set_cookies(self):
webnotes.cookies[b'sid'] = webnotes.session['sid'].encode('utf-8')
webnotes.cookies[b'sid'][b'expires'] = expires.encode('utf-8')

webnotes.cookies[b'country'] = webnotes.session.get("session_country")

def set_remember_me(self):
from webnotes.utils import cint

Expand Down
30 changes: 14 additions & 16 deletions webnotes/sessions.py
Expand Up @@ -115,10 +115,7 @@ def start(self):
self.data['data']['session_ip'] = os.environ.get('REMOTE_ADDR')
self.data['data']['last_updated'] = webnotes.utils.now()
self.data['data']['session_expiry'] = self.get_expiry_period()

# get ipinfo
if webnotes.conn.get_global('get_ip_info'):
self.get_ipinfo()
self.data['data']['session_country'] = get_geo_ip_country(os.environ.get('REMOTE_ADDR'))

# insert session
webnotes.conn.begin()
Expand All @@ -131,7 +128,6 @@ def start(self):

# set cookies to write
webnotes.session = self.data
webnotes.cookie_manager.set_cookies()

def insert_session_record(self):
webnotes.conn.sql("""insert into tabSessions
Expand Down Expand Up @@ -255,15 +251,17 @@ def get_expiry_period(self):
exp_sec = "2:00:00"

return exp_sec

def get_ipinfo(self):
import os

try:
import pygeoip
except:
return

gi = pygeoip.GeoIP('data/GeoIP.dat')
self.data['data']['ipinfo'] = {'countryName': gi.country_name_by_addr(os.environ.get('REMOTE_ADDR'))}

def get_geo_ip_country(ip_addr):
try:
import pygeoip
except ImportError:
return

import os
from webnotes.utils import get_base_path

geo_ip_file = os.path.join(get_base_path(), "lib", "data", "GeoIP.dat")
geo_ip = pygeoip.GeoIP(geo_ip_file, pygeoip.MEMORY_CACHE)

return geo_ip.country_name_by_addr(ip_addr)
10 changes: 10 additions & 0 deletions webnotes/tests/test_geo_ip.py
@@ -0,0 +1,10 @@
import webnotes
import unittest

class TestGeoIP(unittest.TestCase):
def test_geo_ip(self):
from webnotes.sessions import get_geo_ip_country
self.assertEquals(get_geo_ip_country("5.10.83.223"), "India")
self.assertEquals(get_geo_ip_country("223.29.223.255"), "India")
self.assertEquals(get_geo_ip_country("4.18.32.80"), "United States")
self.assertEquals(get_geo_ip_country("217.194.147.25"), "United States")

0 comments on commit 2078d52

Please sign in to comment.