Search code examples
djangopermissions

Trying to prevent international users from accessing my Django site


I don't want to have a cookie policy, so for legal issues, I want to block international users from my site - basically redirect them to a "sorry not available to international users page" and prevent them from accessing the main site. How should do I prevent them from accessing the main site? There is no authentication system for the main site currently. This is mostly a design question.

This is how I thought about doing it, but it would be hard. Is there an easier way?

First, I pull their country from their IP (which I already have). Then, I force them into a first level login page, that they need a username and password to login. However, this is painful, since I already have a user authentication system for paying users. Is there a better way to do this?


Solution

  • You can write a middleware for this. For example:

    from django.http import HttpResponseNotFound
    
    class RestrictUserMiddleware(object):
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    
            if x_forwarded_for:
                ipaddress = x_forwarded_for.split(',')[-1].strip()
            else:
               ipaddress = request.META.get('REMOTE_ADDR')
    
            country = get_country(ipaddress) # Your implementation of getting country
            if country != 'your country':
                return HttpResponseNotFound("not available in your country")
    
            response = self.get_response(request)
            return response
    

    And add it in MIDDLEWARE settings:

    MIDDLEWARE = [
       # rest of the middlewares 
       'pathTo.RestrictUserMiddleware',
    ]