Custom Authentication Backend in Django

How to write a custom authentication backend in Django taking scenario as Phone Number & OTP(One-Time Password) to authenticate against each user.

How to authenticate each user in form of multiple conditions.

  • If email is verified and password exist ( authenticate using email and password).
  • If phone is verified and exist( authenticate using phone and otp or if password exist then auth using phone and password).

  • 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
    

    For you have to specify the authclass in settings.py

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


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

    链接地址: http://www.djcxy.com/p/33808.html

    上一篇: Django:自定义用户

    下一篇: Django中的自定义身份验证后端