Login

Email authentication backend

Author:
benjaoming
Posted:
January 4, 2016
Language:
Python
Version:
1.7
Tags:
authentication email auth username backend
Score:
2 (after 2 ratings)

Fixed minimal version, works with Django 1.7+, tested on Django 1.9.

Add the following to your settings:

AUTHENTICATION_BACKENDS = [
    'project.backends.UserModelEmailBackend',    # Login w/ email
    'django.contrib.auth.backends.ModelBackend',    # Login w/ username
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class UserModelEmailBackend(ModelBackend):

    def authenticate(self, username="", password="", **kwargs):
        try:
            user = get_user_model().objects.get(email__iexact=username)
            if check_password(password, user.password):
                return user
            else:
                return None
        except get_user_model().DoesNotExist:
            # No user was found, return None - triggers default login failed
            return None

More like this

Comments

Please login first before commenting.