Execution of processes and rewriting authenticate

Process

1.authenticate function call is _get_backends
def authenticate(request=None, **credentials):
    for backend, backend_path in _get_backends(return_tuples=True):
        pass
2._get_backends, default global configuration
def _get_backends(return_tuples=False):
    backends = []
    for backend_path in settings.AUTHENTICATION_BACKENDS:
        pass
3.global_settings.py ModelBackend used in class django.contrib.auth.backends

django\conf\global_settings.py

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
class ModelBackend:
    def authenticate(self, request, username=None, password=None, **kwargs):
        pass

Rewrite (achieve username or email login authentication)

You can override the settings in the setting of the project
AUTHENCICATION_BACLENDS = ['users.views.CustomBackend',]

views.py in users

from django.contrib.auth.backends import ModelBackend
from .models import UserProfile
from django.db.models import Q

class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None
# UserProfile继承AbstractUser

When the method call auth authenticate the execution of the above

from django.contrib.auth import authenticate
def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username,password=password)
        # .......

Guess you like

Origin www.cnblogs.com/notfind/p/11962162.html