cannot underustand django custom authenticaton backend

Viewed 26

I am trying to learn from book django 3 by example but i cannot understand few points in django custom authentication like why username and password is passed None and email=username and why we are using get_user

Here is the code

from django.contrib.auth.models import User
class EmailAuthBackend(object):
     #Authenticate using an e-mail address
    def authenticate(self,request,username=None,password=None):
        try:
            user=User.objects.get(email=username)
            if user.check_password(password):
                return user
            return None
        except User.DoesNotExit:
            return None
    def get_user(self,user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExit:
            return None
1 Answers

in this line:

def authenticate(self,request,username=None,password=None):

username and password are None by default, this is done to make sure if user didn't send any username or password here, it will be None by default. Otherwise if user didn't send here any username or password, and there will be no default variable statement, it will return error, that this variable doesn't exist

actually here if you will remove assining to default statment by None, nothing will change, it will work the same, because if user wouldn't send username or password, try will work the same way so this is actually equal to:

def authenticate(self,request,username,password):

(but with default statements it is considered safer)

this line:

def get_user(self,user_id):

is a handy method to get particular User object, you'll meet this method a lot. This is just trying to find User object in database, if it finds User, it will return this user object, if it doesn't find User object, it will return None

But in this particular part of code get_user method isn't used

Related