4

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?

SaurabhM
  • 7,995
  • 1
  • 15
  • 20

1 Answers1

3

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.

computmaxer
  • 1,677
  • 17
  • 28
  • This seems like a good solution.. but suppose if the user is from the US and is on a business tour outside the US and wants to access data from the website, he may also get blocked since the IP is not from US. What would be the good solution for that? – SaurabhM Dec 10 '12 at 22:15
  • There are many ways to handle something like this. You could store a flag on the user model/profile "is_us". When the account is created you would set that to true if the person is in the US at the time. Then in the Middleware you check the request.user for is_us before blocking. This all depends on how you want your business logic to work/act. – computmaxer Dec 10 '12 at 22:22
  • `if request.user.is_authenticated:` without the brackets per Django documentation - https://docs.djangoproject.com/en/3.2/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated – JV conseil Apr 11 '21 at 20:11