Mukul Mantosh
Mukul Mantosh

Reputation: 368

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.

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

Upvotes: 1

Views: 2889

Answers (2)

Nakul Narayanan
Nakul Narayanan

Reputation: 1452

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', )

Upvotes: 3

Mauricio Cortazar
Mauricio Cortazar

Reputation: 4213

There are many ways to extend user model, here I leave you this page and you can choose which of them is better for you https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

Upvotes: 0

Related Questions