We can do this by implementing our own email authentication server.
You can do something like below:
Step 1 Adjust the user model of the user in the settings:
Since we would not use the Django default User model for authentication, we need to define our user model MyUser in settings.py . Set MyUser as AUTH_USER_MODEL in the project settings.
AUTH_USER_MODEL = 'myapp.MyUser'
Step-2 Write down the logic for your own authentication server:
To write our own authentication server, we need to implement at least two methods, i.e. get_user(user_id) and authenticate(**credentials) .
from django.contrib.auth import get_user_model from django.contrib.auth.models import check_password class MyEmailBackend(object): """ Custom Email Backend to perform authentication via email """ def authenticate(self, username=None, password=None): my_user_model = get_user_model() try: user = my_user_model.objects.get(email=username) if user.check_password(password): return user
Step-3 Specify your own authentication server in the settings:
After writing your own authentication backend, specify this authentication server in the AUTHENTICATION_BACKENDS setting.
AUTHENTICATION_BACKENDS contains a list of servers used for authentication. Django tries to authenticate with all of its authentication servers. If the first authentication method fails, Django tries to execute the second, etc., until all the backends are attempted.
AUTHENTICATION_BACKENDS = ( 'my_app.backends.MyEmailBackend', # our custom authentication backend 'django.contrib.auth.backends.ModelBackend' # fallback to default authentication backend if first fails )
If authentication with MyEmailBackend fails, i.e. the user cannot be authenticated via email , we use the default authentication Django ModelBackend , which will try to authenticate through the username field of the MyUser model.