码迷,mamicode.com
首页 > 其他好文 > 详细

自定义authenticate()认证方法 | Django

时间:2017-12-08 16:40:43      阅读:721      评论:0      收藏:0      [点我收藏+]

标签:exist   重载   models   password   cti   return   between   port   error:   

# 自定义认证方法
# authenticate()方法默认对username与password做验证
    authenticate(username=user_name, password=pass_word)
# 需求:对邮箱或者用户名,与密码共同验证;

# 1.重载settings.py的变量
    AUTHENTICATION_BACKENDS = (
        users.views.CustomBackend
    )
# 2.自定义认证方法
    from django.contrib.auth.backends import ModelBackend
    from .models import UserProfile
    
    class CustomBackend(ModelBackend):
        # 修改认证方法
        def authenticate(self, username=None, password=None, **kwargs):
            try:
                # 根据字段值获取对象
                user = UserProfile.objects.get(Q(username=username)|Q(email=username))
                # 验证密码,返回认证通过对象
                if user.check_password(password):
                    return user
            # 没有输入用户名返回None
            except Exception as e:
                return None

源码:

 

# --------------------------------------------------|ModelBackend基类源码
class ModelBackend(object):
    """
    Authenticates against settings.AUTH_USER_MODEL.
    根据系统配置中指定的User表对象里的字段做认证;
    """

    def authenticate(self, username=None, password=None, **kwargs):
        # Returns the User model that is active in this project.
        UserModel = get_user_model()
        # 如果用户名不存在...
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
            if user.check_password(password):
                return user
        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)
            
    # ----------------------------------------|get_user_model()    
    def get_user_model():
        """
        Returns the User model that is active in this project.
        """
        try:
            return django_apps.get_model(settings.AUTH_USER_MODEL)
        except ValueError:
            raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form ‘app_label.model_name‘")
        except LookupError:
            raise ImproperlyConfigured(
                "AUTH_USER_MODEL refers to model ‘%s‘ that has not been installed" % settings.AUTH_USER_MODEL
            )
# --------------------------------------------------

 

自定义authenticate()认证方法 | Django

标签:exist   重载   models   password   cti   return   between   port   error:   

原文地址:http://www.cnblogs.com/pymkl/p/8005277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!