1
votes

I'm developing an app using Django Rest Framework. How can I extend authentication checks on user login?

For example, I need to check the is_active and created_at properties of the user that logs in, and allow or disallow the login based on their values, but only after the password was verified by Django.

I know about Django and Django Rest Framework custom authentication.

https://docs.djangoproject.com/en/2.2/topics/auth/customizing/

https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication

The problem is, that requires me to re-implement the built-in authentication checks. I would like to just add checks on top of that.

Thanks!

1

1 Answers

0
votes

You could extend an existing authentication backend, without the need to reimplement all the logic, e.g.:

from django.contrib.auth.backends import ModelBackend

class MyModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None):
        user = super().authenticate(request, username=None, password=None)
        if user and not user.is_active:
            return None
        return user

Don't forget to update your settings.py to use your custom authentication backend:

AUTHENTICATION_BACKENDS = ['myapp.backends.MyModelBackend']