首页 > 其他 > 详细

authenticate的执行流程与重写

时间:2019-11-30 14:28:53      阅读:123      评论:0      收藏:0      [点我收藏+]

流程

1.authenticate调用的是_get_backends函数
def authenticate(request=None, **credentials):
    for backend, backend_path in _get_backends(return_tuples=True):
        pass
2._get_backends,默认使用全局配置
def _get_backends(return_tuples=False):
    backends = []
    for backend_path in settings.AUTHENTICATION_BACKENDS:
        pass
3.global_settings.py 使用django.contrib.auth.backends下的ModelBackend的类

django\conf\global_settings.py

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

重写(实现username或email登录验证)

可以在项目的setting中重写设定
AUTHENCICATION_BACLENDS = ['users.views.CustomBackend',]

users下的views.py

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

当调用auth中的authenticate将执行上面的方法

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)
        # .......

authenticate的执行流程与重写

原文:https://www.cnblogs.com/notfind/p/11962162.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!