0
votes

My goal is to have two views for login: one with email and password, and another with username and password.

Created a custom user class named MyUser extending from AbstractBaseUser. In that user class, stablished

USERNAME_FIELD = 'email'

Django by default uses the username field for authentication purposes of a user.

When i want users to login with email, that's easy now. But how can I do to create another view that logs in with just username and password (instead of the email)?

1

1 Answers

1
votes

I do this by adding another authentication backend, using AUTHENTICATION_BACKENDS. Or you can write your own Auth backend, accepting either email or username.

Here's a simple version of an email authentication backend. Note that this requires that e-mail addresses are unique in your database, and does not case fold.

class EmailAuthBackend(ModelBackend):
    """
    Email Authentication Backend

    Allows a user to sign in using an email/password pair rather than
    a username/password pair.
    """

    def authenticate(self, request, email=None, password=None, **kwargs):
        """ Authenticate a user based on email address as the user name. """
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            User().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user