美文网首页
重定义django的认证登录

重定义django的认证登录

作者: 无心文先森 | 来源:发表于2021-01-15 16:54 被阅读0次

    重定义django的认证登录

    django提供了用户认证功能,即验证用户名以及密码是否正确,一般需要usernamepassword两个关键字参数。

    如果认证成功(用户名和密码正确有效),便会返回一个 User 对象。

    authenticate()会在该 User 对象上设置一个属性来标识后端已经认证了该用户,且该信息在后续的登录过程中是需要的

    user = authenticate(username='theuser',password='thepassword')
    

    但是存在一些缺陷,只能是使用username进行验证,这不太符合我们的需求,我们希望可以同时使用emailusername等进行验证

    首先在views.py中我们需要重写authenticate方法

    from django.contrib.auth.backends import ModelBackend
    from django.db.models import Q
    
    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
            except Exception as e:
                return None
    

    settings.py中配置

    AUTHENTICATION_BACKENDS = (
        'users.views.CustomBackend',
    )
    

    相关文章

      网友评论

          本文标题:重定义django的认证登录

          本文链接:https://www.haomeiwen.com/subject/pvywaktx.html