BAE
BAE

Reputation: 8936

How does Django ModelBackend.authenticate work?

I am looking into the ModelBackend.

def authenticate(self, username=None, password=None, **kwargs):
    UserModel = get_user_model()
    if username is None:
        username = kwargs.get(UserModel.USERNAME_FIELD)
    try:
        user = UserModel._default_manager.get_by_natural_key(username)
    except UserModel.DoesNotExist:
        # Run the default password hasher once to reduce the timing
        # difference between an existing and a non-existing user (#20760).
        UserModel().set_password(password)
    else:
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

I am confused.

  1. Where is authenticate() is called.
  2. What is passing username and password to authenticate()?

Sometimes, the code works, but I have no idea how it works.

UPDATE

I am reading the source code of one project. I found the definition of authenticate(), but I cannot find where it is called.

grep -r "authenticate" .

./src/myproject/views.py:   if request.user.is_authenticated():
./src/lib/backend.py:   def authenticate(self, username = None, password = None, **kwargs):
./src/lib/middleware.py:        if not request.user.is_authenticated():
./src/lib/decorators.py:        if request.user.is_authenticated():

Upvotes: 1

Views: 2351

Answers (1)

markwalker_
markwalker_

Reputation: 12859

authenticate() doesn't 'work' by itself.

If your project or application implements a login form then you, or the developer of the app you use for authentication, will call authenticate().

For example, if you have a login form with a username & password field then you'd call authenticate(username, password) in your post() method.

For example;

if request.method == 'POST':
    # Gather the username and password provided by the user.
    # This information is obtained from the login form.
    username = request.POST['username']
    password = request.POST['password']

    # Use Django's machinery to attempt to see if the username/password
    # combination is valid - a User object is returned if it is.
    user = authenticate(username=username, password=password)
    # If we have a User object, the details are correct.
    # If None (Python's way of representing the absence of a value), no user
    # with matching credentials was found.
    if user:
        # Is the account active? It could have been disabled.
        if user.is_active:
            # If the account is valid and active, we can log the user in.
            # We'll send the user back to the homepage.
            login(request, user)
            return HttpResponseRedirect('/rango/')
        else:
            # An inactive account was used - no logging in!
            return HttpResponse("Your Rango account is disabled.")
    else:
        # Bad login details were provided. So we can't log the user in.
        print "Invalid login details: {0}, {1}".format(username, password)
        return HttpResponse("Invalid login details supplied.")

See here for the full write up on this code, or check out the official django docs on authenticate().

Upvotes: 2

Related Questions