how to login user either email or username in Django rest framework(JWT Token)

Viewed 564

I'm using:

Django==3.2.9
djangorestframework==3.12.4
djangorestframework-simplejwt==5.0.0

I want to make a login system that takes either username or email and password as a parameter from a user. After that authenticate a user with those credentials and provide access & refresh token as a response.

And I want to use access and refresh tokens use the JWT token system of djangorestframework-simplejwt.

1 Answers

simplejwt lib uses the authenticate function of django.

What you'd want to do if you allow a user to authenticate with both a username or an email, you'd need to create a custom authentication backend.

here is an example of that

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

USER = get_user_model()


class AuthentificationBackend(ModelBackend):
    """
    Define a new authentification backend for auth with username/password or email/password.
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(USER.USERNAME_FIELD)

        case_insensitive_username_field = '{}__iexact'.format(USER.USERNAME_FIELD)
        users = USER._default_manager.filter(
            Q(**{case_insensitive_username_field: username}) | Q(email__iexact=username))

        # Test whether any matched user has the provided password:
        for user in users:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user
        if not users:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a non-existing user (see
            # https://code.djangoproject.com/ticket/20760)
            USER().set_password(password)

and then in your settings.py

AUTHENTICATION_BACKENDS = [
    # Application custom auth backend
    'path_to.AuthentificationBackend',
]
Related