views:

28

answers:

1

Is it possible to only let a user log in while using a specific IP address? This IP address would be different for all users so simply writing an htaccess rule in Apache would not solve my problem. I also looked into writing a custom authentication backend but I don't see any way I could check the user's current IP address since there is no request variable provided.

It is not absolutely critical to have this feature, but it might be nice. I just need to see if it is possible to do without severely hacking up Django's authentication framework.

Thanks, Cory

+2  A: 

It's quite simple actually.

  1. create a custom authentication backend that takes an IP address as an argument (and others if you want more than that to authenticate).
  2. create a custom authentication view

Example of the view:

from django.contrib.auth import authenticate, login

def login(request):
    user = authenticate(ip=request.META['REMOTE_ADDR'])
    if user is not None:
        login(request, user)
        # Redirect to a success page.
    else:
        # Return an 'invalid login' error message.

Example of the auth backend:

class IPAuthBackend:
    def authenticate(self, ip=None):
        try:
            return SomeModel.objects.get(ip=ip).user
        except SomeModel.DoesNotExist:
            pass
WoLpH
Thanks for the answer. I was too used to using the built-in login view that I didn't realize this was a possibility.
Cory Walker