How to check if a user is logged in from outside the US using Django middleware

I am new to Django and wanted to know how I can check if a user is registered on the django website from outside the US?

How do I write a class in Middleware to test it? I want to hide certain sections of the website from users leaving the USA.

I know that I am not providing any details, and the question may seem vague ... but I needed a general idea to get started. I have not started working on the website yet.

I looked at the Django Middleware documentation, but still have not figured out how to do this. Does user authentication https://docs.djangoproject.com/en/1.4/topics/auth/#limiting-access-to-logged-in-users provide any such features?

+4
source share
1 answer

You can use the GeoIP module included in django .

Simple middleware might look something like this:

class GeoLocationMiddleware: def process_request(self, request): if 'geoip_check' not in request.session: g = GeoIP() country = g.country(request.META.get('REMOTE_ADDR')) do_something(country) #Do something with country result. request.session['geoip_check'] = True #Could store country result return None 

You will notice that I am adding a flag to the session. GeoIP verification for each request is not needed and is inefficient for performance, therefore we only check it once per session. Hope this is what you were looking for.

Edit: If you want to do this only for registered users, drop there:

 if request.user.is_authenticated(): 

at the beginning.

+3
source

All Articles