All-Auth with Django-Allauth

Django-allauth Tutorial #PureDjango — Episode #01

J3
Jungletronics
8 min readApr 14, 2023

--

Official Documentation — django-allauth

This is a standalone Django Working App Running a simple Project of How:

All-Auth Works in Django.

Welcome!

Django-allauth is a Django package that provides a set of views, templates, and helper functions to handle user authentication, registration, and account management.

It is built on top of Django’s authentication framework and provides additional functionality to make it easier to integrate with third-party authentication providers, such as social media platforms.

Here is a high-level overview of how Django-allauth works:

  1. Installation: You can install Django-allauth using pip. Once installed, add the app to your Django project’s INSTALLED_APPS setting.
  2. Configuration: You can configure Django-allauth by specifying settings in your project’s settings.py file. Some of the settings you can configure include the authentication backends to use, the URL patterns for the authentication views, and the email backend to use for sending verification emails.
  3. URLs: You need to include Django-allauth’s URL patterns in your project’s urls.py file. These patterns include URLs for authentication, registration, and account management views.
  4. Templates: Django-allauth provides a set of default templates that you can use as a starting point for your own templates. You can customize these templates to match the look and feel of your site.
  5. Views: Django-allauth provides a set of views that handle authentication, registration, and account management. You can customize these views by subclassing them and adding your own logic.
  6. Signals: Django-allauth provides signals that you can use to customize the behavior of the authentication process. For example, you can use signals to send a welcome email to a user after they register.
  7. Providers: Django-allauth supports a variety of third-party authentication providers, such as Facebook, Google, and Twitter. You can configure these providers in your project’s settings.py file and use them to allow users to sign in with their social media accounts.

Overall, Django-allauth provides a comprehensive set of tools to handle user authentication and registration in Django projects. Its flexibility and customizability make it a popular choice among Django developers.

Let’s practice!

00#Step — Let´s Make the Django Infrastructure:

Open your prompt and type (or copy/paste/hit enter):

mkdir cws_allauth
cd cws_allauth
python -m venv ENV
source ENV/bin/activate
pip install django
pip freeze > requirement.txt
django-admin startproject cwsallauth
cd cwsallauth
code .
exit

This will create a project named cwsallauth (Community Works — All Auth), Create an Virtual Environment Directory ENV, install the latest Django module, and finally create a Django Project cwsallauth and open VSCode.

[important: run in your Vs-code Terminal:

Python packages:

pip install --upgrade pip
pip install django-allauth

Please go to this post to setup and customize your VS Code!

Here is the scaffolding created magically by Django Machinery 🤗️

01#Step — Open cwsallauth/settings.py and type:

INSTALLED_APPS = [
...

'django.contrib.sites',

'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.github',
]

02#Step — Inside cwsallauth/settings.py , right after ALLOWED_HOSTS list type:

....
ALLOWED_HOSTS = []

SITE_ID = 1

# Provider specific settings
SOCIALACCOUNT_PROVIDERS = {
'github': {
# For each OAuth based provider, either add a ''SocialApp''
# (''socialaccount'' app) containing the required client
# credentials, or list them here:
'APP': {
'client_id': '<your_client_id>',
'secret': '<your_secret_key>',
'key': ''
}
}
}

AUTHENTICATION_BACKENDS = [

'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]

Save cwsallauth/settings.py.

03#Step —Now Go to cwsallauth/urls.py:

from django.contrib import admin
from django.urls import path, include
from django.shortcuts import render


def home(request):
return render(request, 'home.html')


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

Although it is not the best practice we can make a function inside this file :/

The urlpatterns is a list of URL patterns that maps URLs to views in a Django application.

Each URL pattern is defined using the path() function, which takes two arguments: the URL pattern and the view function that should be called when the URL is requested.

In the example we provided, the urlpatterns list contains three URL patterns:

  1. The first pattern path('', home) maps the root URL ('/') to a view function called home. This means that when the user navigates to the root URL of the website, the home view function will be called to render the response.
  2. The second pattern path('admin/', admin.site.urls) maps the URL /admin/ to the Django admin site. This means that when the user navigates to the /admin/ URL, they will be redirected to the Django admin site where they can log in and manage the site's content.
  3. The third pattern path('accounts/', include('allauth.urls')) maps the URL /accounts/ to the allauth.urls module, which contains URL patterns provided by Django-allauth for user authentication and registration. This means that when the user navigates to the /accounts/ URL, they will be directed to the Django-allauth authentication and registration views.
URL patterns list (and its respective view's names) available to use 🧤️.

In summary, the urlpatterns list maps specific URLs to the corresponding view functions or modules that handle the requests and responses for those URLs in a Django application.

04#Step — Now it’s time to migrate everything! In Terminal, type:

python manage.py migrate
Migrations output in Vs Code Terminal.

05#Step — Now the last step until here, create a super user:

python manage.py createsuperuser

06#Step — Run the server:

python manage.py runserver

Go to Admin dashboard.

You will see all this apps installed! 😲️

From now on we will override all accounts templates in django.

07#Step —But first let’s set the email backend to test inside a email folder.

Open cwsallauth/settings.py again and at the very end of it, type:

# Email File Based Test

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = BASE_DIR / 'emails'

In Django, the EMAIL_BACKEND setting specifies the backend used to send email messages. In the example we provided, the EMAIL_BACKEND is set to django.core.mail.backends.filebased.EmailBackend, which is a backend that writes emails to a file on the filesystem.

The EMAIL_FILE_PATH setting specifies the path where the email messages will be written. In the example, it is set to BASE_DIR / 'emails', which means that the emails will be written to a directory named emails located in the project's base directory.

Using the filebased email back-end can be useful during development or testing when you don't want to send real emails to users. Instead, you can configure Django to write the emails to a file, which you can then inspect to verify that the correct emails are being sent.

Note that in production, you would typically use a different email backend, such as SMTPBackend, to send real emails to users.

Now you can test all this links in admin dashboard (docs, find .pngs):

accounts/ password/reset/ [name='account_reset_password']
accounts/ password/reset/done/ [name='account_reset_password_done']
accounts/ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$ [name='account_reset_password_from_key']
accounts/ password/reset/key/done/ [name='account_reset_password_from_key_done']

08#Step — Create a folder in the root named templates and save inside this home.html:

{% load socialaccount %}
<h1>CWS All Auth Tutorial</h1>
</h1>
<p>Based on:</p>
<a href="https://youtu.be/RyB_wdEZhOw">code with stein</a>

<hr>
{% if request.user.is_authenticated %}
<h2>CONGRATS :)</h2>
<h3>You Are Logged in!</h3>
<h4> WELCOME TO DASHBOARD!</h4>
button for log out
<a href="{% url 'account_logout' %}"> Log Out</a>
{% else %}
<h2>SORRY :/</h2>
<h3>You Are Logged Out!</h3>
<p>Link to log in:
<p>By Django Admin Dashboard [w/ username/password or github credentials]:</p>
<p>using url -> .../accounts/login/</p>

<a href="{% url 'account_login' %}"> LogIn</a>
<hr>
<p>Or via Github:</p>
<p>using url ->.../accounts/github/login/</p>
<a href="{% provider_login_url 'github' %}"> LogIn via Github</a>
{% endif %}

The HTML code we provided is a Django template that displays a message and provides links for users to log in or log out of the website.

The first line {% load socialaccount %} is a Django template tag that loads the socialaccount template tags provided by Django-allauth. These tags can be used to render social authentication buttons on the website.

The next lines display a heading and a link to the source of the tutorial Code With Stein we are based on 😇️🤗️.

The {% if request.user.is_authenticated %} statement checks if the user is authenticated (i.e., logged in) using the request.user.is_authenticated attribute. If the user is authenticated, the template displays a message and a button to log out of the website using the {% url 'account_logout' %} template tag.

If the user is not authenticated, the template displays a message and links for the user to log in using either their Django admin credentials or their GitHub account. The links are created using the {% url 'account_login' %} and {% provider_login_url 'github' %} template tags respectively.

Overall, this template provides a simple way to display different messages and links to users based on their authentication status.

09#Step — Now Github

Login to your account and go to this link:

https://github.com/settings/applications/new

The purpose of https://github.com/settings/applications/new is to create a new OAuth application on GitHub.

OAuth is an open standard for authorization that allows third-party applications to access a user’s resources on a web service (in this case, GitHub) without having to know the user’s login credentials.

By creating a new OAuth application on GitHub, you can obtain a client_id and client_secret that can be used to authenticate your application when it interacts with the GitHub API on behalf of a user. This allows your application to access the user's resources, such as their repositories, without the need for the user to share their GitHub login credentials with your application.

When you create a new OAuth application on GitHub, you will need to provide some basic information about your application, such as the application name, a description, and a homepage URL. You will also need to specify the URL where GitHub should redirect users after they grant access to your application.

Once you have created your OAuth application on GitHub, you can use the client_id and client_secret to authenticate your application with the GitHub API and start accessing user resources.

Use this hints to fill the gaps:

1-Click Button Generate a New Client Secret;


2-fill in the blanks in cwsallauth/settings.py:

SOCIALACCOUNT_PROVIDERS = {
'github': {
...
'APP': {
'client_id': '<your_client_id>',
'secret': '<your_secret_key>',
'key': ''
}
}
}

3-Application name:
CWS Social Auth

4-Homepage URL:
https://127.0.0.1:8000/

5-Authorization callback URL:
https://127.0.0.1:8000/accounts/github/login/callback

6-Goto to your app login (http://127.0.0.1:8000/) and authorize app.

Here are the result pages:

Logged out 🙃️
Login in via the first link 😄️
Or via GitHub link 🥰️ Click on Continue button and…
🎉️🎉️🎉️TA-DA!🎉️🎉️🎉️
🎉️🎉️🎉️ Successfully signed in as giljr. When click Sign Out, we return to the first page…☝️
Here is my GitHub configurations for my CWS Social Auth app.

That’s all folks!

Hope this helps!

Bye!

👉️github

Credits:

Code with Stein — Python Django Social Authentication | Django AllAuth Tutorial

References:

https://docs.djangoproject.com/en/4.1/topics/auth/default/#using-the-django-authentication-system

LoginView — Classy CBV

pennersr/django-allauth

Related Posts:

#Pure Django Series:

00#Episode: How Django Signals Work — Stand-alone Project to show how-to

01#Episode: All-Auth with Django-Allauth — Django AllAuth Tutorial #PureDjango (this one)

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!