0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

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']
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Thanks a lot, that's a quite interesting approach. I am having an additional issue: when including the `AUTHENTIFICATION_BACKENDS` variable, I have included traces and my backend is never reached when authentificating. I suspect that the path is not being held correctly. My path is as follows: `src/core/backends/auth_backend.py` - MyBackend and in `settings.py` I have tried with several combinations, the last one is as follows: `AUTHENTICATION_BACKENDS = ['core.backends.auth_backend.MyBackend', 'django.contrib.auth.backends.ModelBackend']`. Is this correct? – Adrian Gil Moral Feb 22 '23 at 11:20
  • There was one mistake from my side, I added additional argument `request`, which was not necessary. I have removed it, so can you try the updated answer? – ruddra Feb 22 '23 at 11:26
  • Hi, I've just tried but it happens the same thing, it does not enter in `MyBackend` – Adrian Gil Moral Feb 22 '23 at 11:34
  • What happens if you remove the ModelBackend? Also how are you calling the authentication method? – ruddra Feb 22 '23 at 12:12