While working on the sign up process I noticed it takes to many steps for a user to login to their new account. Where I wanted to get to was once the user completes the sign up process they're automatically redirected in to their account, and logged in. In order to make this work with django.contrib.auth it requires us to write a custom auth backend. Due to the clean api this is very trivial to do. Here is what my auth backend looks like:
from django.contrib.auth.backends import ModelBackend
class UserObjectAuthBackend(ModelBackend):
def authenticate(self, username=None, password=None, user=None):
if not user:
try:
user = self.user_class.login.get(username=username)
except self.user_class.DoesNotExist:
pass
if user and user.check_password(password):
return user
return None
return user
If you‘ve ever created a auth backend you will notice something a little different about my version, I will explain this a little later. First a little explanation of what the backend is doing.
In order to implement a backend we will need to over write one method, authenticate. This method is suppose to take a username and password, and using this information it needs to look up the user and then verify that the password is correct, if its correct return the user object. Our goal is to login a user using only the User object, to reach our goal we will change the default api just a little to allow us to pass in a user object to authenticate. In this version the only time we need to check the users password is when we don’t already have a user object, and if we do we just return it. To wrap up the work on the auth backend we will need to let the auth app we want to use our custom backend, to do this we need to add the following to our settings.py file:
AUTHENTICATION_BACKENDS = (
'lib.UserObjectAuthBackend',
)
Now its time to see the view that will login in a user and redirect them to where ever they need to be:
from django.contrib.auth import authenticate, login
def signup(request):
# ...
# Sign up process
# `user` is the new user that just signed up.
# ...
user = authenticate(user=user)
login(request, user)
return HttpResponseRedirect('/my_account')
That’s it folks, when the user see the next page they will be logged in. For more information also check out the great Django documentation. If you got any question or suggestions leave them below.




