首页 文章

Django中的自定义身份验证后端

提问于
浏览
0

如何在Django中编写自定义身份验证后端,将方案作为电话号码和OTP(一次性密码)对每个用户进行身份验证 .

如何以多种条件的形式验证每个用户 .

  • 如果验证了电子邮件并且存在密码(使用电子邮件和密码进行身份验证) .

  • 如果手机已验证并存在(使用手机和otp进行身份验证或存在密码,则使用手机和密码进行身份验证) .

2 回答

  • 1
    from django.contrib.auth import backends, get_user_model
    from django.db.models import Q
    
    class AuthenticationBackend(backends.ModelBackend):
    """
    Custom authentication Backend for login using email,phone,username 
    with password
    """
    
    def authenticate(self, username=None, password=None, **kwargs):
        usermodel = get_user_model()
        try:
            user = usermodel.objects.get(
                Q(username__iexact=username) | Q(email__iexact=username) | Q(phone__iexact=username)
    
            if user.check_password(password):
                return user
        except usermodel.DoesNotExist:
            pass
    

    因为你必须在settings.py中指定authclass

    AUTHENTICATION_BACKENDS =('applications.accounts.auth_backends.AuthenticationBackend',)

  • 0

    有很多方法可以扩展用户模型,在这里我给你留下这个页面,你可以选择哪一个更适合你https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

相关问题