DEV Community

Cover image for Auth via E-mail: Overriding Django's default auth system
Mohamed
Mohamed

Posted on

Auth via E-mail: Overriding Django's default auth system

Django framework provides a great mechanism to authenticate users via their username and password, but what if you need to implement a custom auth where you have to authenticate via the email instead?
This Guide covers the steps to create a custom user auth for you project

  1. Creating your auth.py: first of all inside you app directory create a file named auth.py, that's where we're gonna override the default authentication behavior.
  2. *** Overriding the default authenticate method***: inside you auth.py file paste the following code:
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth import get_user_model

class CustomUserAuth(BaseBackend):
    def __init__(self) :
        # get the custom user model we've already created
        self.UserModel = get_user_model()
        # overriding the authenticate  method to include our own logic for authentication
    def authenticate(self, request, username=None,password=None,**kwargs):
        # retrieve the username
        username = kwargs.get('username')
        if username:
            try :
                # treat the username as email if it contain @
                if '@' in username:
                    user = self.UserModel.objects.get(email=username)
                # if it doesnt treat it as a username
                else:
                    user = self.UserModel.objects.get(username=username)
                # check the password that's included on the request 
                # and return user object if its true
                if user.check_password(password):
                    return user
                else :
                    return None
            except Exception as e:
                return None
    # a function to get the user object
    def get_user(self, user_id):
        try:
            return self.UserModel.objects.get(pk=user_id)
        except self.UserModel.DoesNotExist:
            return None
Enter fullscreen mode Exit fullscreen mode
  1. Tell django about the new settings: return to your settings.py and add this line:

AUTHENTICATION_BACKENDS = [
    'relative/path/tp/your/auth.py'
]

Enter fullscreen mode Exit fullscreen mode

this line will tell django that we've created our own authentication login and that we're going to use it

And that it, your custom authentication should now work either by email or useraname

Top comments (0)