Django - Add extra clause for login with AbstractUser inheritance

48 Views Asked by At

I have the following model:

employee.py

class Employee(auth_models.AbstractUser, MetadataModel):
    user = models.CharField(unique=True, primary_key=True)
    first_name = models.CharField(blank=True, null=True)
    last_name = models.CharField(blank=True, null=True)
    is_deleted = models.BooleanField(default=False)

My settings.py references to Employee model for authentication:

AUTH_USER_MODEL = 'core.Person'

By default, the user can only log in with the AbstractUser model when is_active=True. How can I change this condition so that the authentication is: is_active==True and is_deleted==False preserving the inheritance on AbstractUser in Employee?

1

There are 1 best solutions below

4
ruddra On

You can write a custom authentication backend for that, like this:

from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import check_password

class MyBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None):
        # Check the username/password and return a user.
        try:
            user = Employee.objects.get(username=username, is_active=True,is_deleted=False)
            if check_password(password, user.password):
                  return user
         except Employee.DoesNotExist():
             return None
         return None  
   

Then add this new backend in your settings.py:

AUTHENTICATION_BACKENDS =  ['yourapp.auth_backend.MyBackend']