how to check if a user has logged in from outside the US using Django middleware

django

Solution

You could use the GeoIP module included with django.

A simple middleware could 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'll notice I add a flag to the session. Checking the GeoIP on every request is unnecessary and bad for performance, so we only check it once per session. Hope this is what you were looking for.

Edit: If you only want to do this for logged in users, throw this in there:

if request.user.is_authenticated():

at the beginning.

Problem

I am pretty new to Django and wanted to know how I could check if a user logging to a django powered website is from outside the US? How would I write a class in Middleware to check the same? I want to hide particular sections of the website from users logging out of the US. I know I am not providing any details and the question might seem vague... but I needed a general idea to get started. I have not started working on the website yet. I went through the Django Middleware documentation but still did not understand how to do so. Does the user authentication https://docs.djangoproject.com/en/1.4/topics/auth/#limiting-access-to-logged-in-users provide any such functionality?

Original source

Related problems