Django-allauth email authentication tutorial

Hello internet programmers. Django-allauth is amazing package to integrate an authentication system into your app. It provides email authentication and social authentication. But in this tutorial, we’ll explore email authentication using django-allauth. Let’s jump into it.

Setting up the Environment

First, create a directory for example allauthtut. and open the terminal on this path. Now let’s set up the virtual environment.

Enter the following command to create an environment.

virtualenv env .

There are many ways to create a virtual environment. Here I’m using virtualenv. Assuming virtualenv is already installed on your PC. If not please visit this -> https://virtualenv.pypa.io/en/latest/installation.html

Now open the directory in VS Code and open the terminal inside it and activate the environment.

source bin/activate

Now let’s install Django and django-allauth package

Installation

pip install django django-allauth

Create Project

django-admin startproject core .

Setup django-allauth

Open settings.py and do following changes (Important - Please note ‘django.contrib.sites’ is required as INSTALLED_APPS)

Add following lines in INSTALLED_APPS

# core/settings.py

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    'django.contrib.sites', # new
    'allauth', # new
    'allauth.account', # new
    'allauth.socialaccount', #new
]

Then at the bottom of settings.py we need to specify that we’re using the allauth backend, add a SITE_ID since allauth uses this, and configure a redirect to the homepage upon successful login.

# core/settings.py

SITE_ID = 1

AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
]

ACCOUNT_EMAIL_VERIFICATION = 'none'

LOGIN_REDIRECT_URL = '/'

Now Open urls.py and add url paths for allauth.

# core/urls.py

from django.contrib import admin
from django.urls import path, include # new

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')), # new
]

Note that you do not necessarily need the URLs provided by django.contrib.auth.urls. Instead of the URLs loginlogout, and password_change (among others), you can use the URLs provided by allauthaccount_loginaccount_logoutaccount_set_password

Now all most done. Now migrate our changes to update the existing database. Make sure your environment is active.

python manage.py migrate

Now it’s all done, that’s it. easy right. run the server and open http://127.0.0.1:8000/accounts/login/

Template

We are not creating any app just let’s see authentication or not on the template. Cra eate templates folder in root directory (in allauthtut). Open settings.py and make this changes for templates

# core/settings.py

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"], # new
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

Create base.html and home.html inside templates and add the following code

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Django-allauth tutorial</title>
</head>
<body>
    <main>
        {% block content %}
        {% endblock content %}
    </main>
</body>
</html>

home.html

{% extends 'base.html' %}

{% block content %}

   

    {% if request.user.is_authenticated %}

        <h1>Hi {{ request.user.username }}!</h1>

        <a href="{% url 'account_logout' %}">Logout</a>

    {% else %}

        <h1>Not logged in</h1>

        <a class="btn" href="{% url 'account_login' %}">Login</a>
    {% endif %}

{% endblock content %}

Open urls.py and add the following code for template rendering.

from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('', TemplateView.as_view(template_name='home.html'), name='home'), # new
]

now run the server and open http://127.0.0.1:8000/

django-allauth email authentication

Home page

login page django allauth

Login page

signup page all auth

Sign Up page

Forget password

To reset the password we need a user email to send a password reset link. So we need to mandatory to ask email while registering. For that just add the following line in settings.py

ACCOUNT_EMAIL_REQUIRED = True #new

ACCOUNT_EMAIL_VERIFICATION = 'none'

LOGIN_REDIRECT_URL = '/'

and also we need an email setup at the backend to send emails to a user right. Here we are using gmail address and for that make app password in your email management settings. here you go: https://myaccount.google.com/apppasswords and add app password. Choose any when you Select App and enter name whatever your want and you get the password.

Now add these lines for email setup.

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #new
EMAIL_HOST = 'smtp.gmail.com' #new
EMAIL_PORT = 587 #new
EMAIL_HOST_USER = '[email protected]'  #new
EMAIL_HOST_PASSWORD = "WRITE THAT PASSWORD HERE" #new
EMAIL_USE_TLS = True #new

Now, all done. Let’s test it.

First, register the user with an email address and then log out to test forget password feature. Now open http://127.0.0.1:8000/accounts/login/ and you can see forget password link. Click on it and you can see this page http://127.0.0.1:8000/accounts/password/reset/

Forget password page django all auth

Forget password page

Now enter the registered email and it will send you the password reset link and redirect you to this page.

password reset

password reset email sent

Check email must check the spam folder. You find you get the email from the email your mentioned in the settings

password reset email

password reset email

Copy that link and open it in the new tab. You can see this page and ask you for new password.

Change password page

Change password page

Change the password and try to log in again.

Password update

If you already know the old password and just want to update with a new password then open this link http://127.0.0.1:8000/accounts/password/change/

Change password with login

Update password with login

Email verification

If you want to account verification while registering then just do this change in settings.py. Make sure ACCOUNT_EMAIL_REQUIRED is set to True. Open settings.py and change ACCOUNT_EMAIL_VERIFICATION none to mandatory like this.

ACCOUNT_EMAIL_VERIFICATION = 'mandatory'

Now while registering it will send an email verification link. Make sure you had an email setup as we did above.

Okay, now register the new user and you will see this page after submitting the registration page. And yes it will not allow the user to log in until you verify the email because it is set to 'mandatory', if you want to send a verification email but allow login without verification then set it to ‘optional'. In case of 'optional', the e-mail verification mail is still sent and allows users to log in with an unverified e-mail address.

Now open your email and you get an email verification link.

Email verification link

Email verification link

Okay notice something, open Django admin (assuming you already created superuser) and open http://127.0.0.1:8000/admin/account/emailaddress/. You can see email address is not verified.

email not verified admin

email not verified admin

Now open the link in the new tab and you get this.

confirm email address

confirm email address

Click on Confirm button and it will get verified and redirects the user to the login page. If a user cannot open the verification link within a few minutes it will expire, for the new verification link, the user needs to log in with their credential and the new verification link will send again to the user’s registered email.

Authentication method

ACCOUNT_AUTHENTICATION_METHOD (=”username” | “email” | “username_email”). Specifies the login method to use – whether the user logs in by entering their username, e-mail address, or either one of both. Setting this to “email” requires ACCOUNT_EMAIL_REQUIRED=True

So if you want the user can log in with username or email just specify this in settings.py

ACCOUNT_AUTHENTICATION_METHOD = 'username_email'

Okay explore more: https://django-allauth.readthedocs.io/en/latest/installation.html

Follow me personally on insta/twitter: @sudoarpit

Thanks and Happy Coding :)

You may also like,