matthiask / django-authlib

Utilities for passwordless authentication (using magic links, Google, Facebook and Twitter OAuth currently)
https://django-authlib.readthedocs.io/
MIT License
61 stars 11 forks source link

================================================ django-authlib - Authentication utils for Django

.. image:: https://github.com/matthiask/django-authlib/actions/workflows/tests.yml/badge.svg :target: https://github.com/matthiask/django-authlib/ :alt: CI Status

.. image:: https://readthedocs.org/projects/django-authlib/badge/?version=latest :target: https://django-authlib.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status

authlib is a collection of authentication utilities for implementing passwordless authentication. This is achieved by either sending cryptographically signed links by email, or by fetching the email address from third party providers such as Google, Facebook and Twitter. After all, what's the point in additionally requiring a password for authentication when the password can be easily resetted on most websites when an attacker has access to the email address?

Goals

Usage

The Google, Facebook and Twitter OAuth clients require the following settings:

Note that you have to configure the Twitter app to allow email access, this is not enabled by default.

.. note:: If you want to use OAuth2 providers in development mode (without HTTPS) you could add the following lines to your settings.py:

.. code-block:: python

    if DEBUG:
        # NEVER set this variable in production environments!
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

This is required because of the strictness of
`oauthlib <https://pypi.org/project/oauthlib/>`__ which only wants HTTPS
URLs (and rightly so).

Use of bundled views

The following URL patterns are an example for using the bundled views. For now you'll have to dig into the code (it's not much, at the time of writing django-authlib's Python code is less than 500 lines):

.. code-block:: python

from django.conf.urls import url
from authlib import views
from authlib.facebook import FacebookOAuth2Client
from authlib.google import GoogleOAuth2Client
from authlib.twitter import TwitterOAuthClient

urlpatterns = [
    url(
        r"^login/$",
        views.login,
        name="login",
    ),
    url(
        r"^oauth/facebook/$",
        views.oauth2,
        {
            "client_class": FacebookOAuth2Client,
        },
        name="accounts_oauth_facebook",
    ),
    url(
        r"^oauth/google/$",
        views.oauth2,
        {
            "client_class": GoogleOAuth2Client,
        },
        name="accounts_oauth_google",
    ),
    url(
        r"^oauth/twitter/$",
        views.oauth2,
        {
            "client_class": TwitterOAuthClient,
        },
        name="accounts_oauth_twitter",
    ),
    url(
        r"^email/$",
        views.email_registration,
        name="email_registration",
    ),
    url(
        r"^email/(?P<code>[^/]+)/$",
        views.email_registration,
        name="email_registration_confirm",
    ),
    url(
        r"^logout/$",
        views.logout,
        name="logout",
    ),
]

Admin OAuth2

The authlib.admin_oauth app allows using Google OAuth2 to allow all users with the same email domain to authenticate for Django's administration interface. You have to use authlib's authentication backend (EmailBackend) for this.

Installation is as follows:

.. code-block:: python

ADMIN_OAUTH_PATTERNS = [
    (r"@example\.com$", "admin@example.com"),
]

.. code-block:: python

urlpatterns = [
    url(r"", include("authlib.admin_oauth.urls")),
    # ...
]

Please note that the authlib.admin_oauth.urls module assumes that the admin site is registered at /admin/. If this is not the case you can integrate the view yourself under a different URL.

It is also allowed to use a callable instead of the email address in the ADMIN_OAUTH_PATTERNS setting; the callable is passed the result of matching the regex. If a resulting email address does not exist, authentication (of course) fails:

.. code-block:: python

ADMIN_OAUTH_PATTERNS = [
    (r"^.*@example\.org$", lambda match: match[0]),
]

If a pattern succeeds but no matching user with staff access is found processing continues with the next pattern. This means that you can authenticate users with their individual accounts (if they have one) and fall back to an account for everyone having a Google email address on your domain:

.. code-block:: python

ADMIN_OAUTH_PATTERNS = [
    (r"^.*@example\.org$", lambda match: match[0]),
    (r"@example\.com$", "admin@example.com"),
]

You could also remove the fallback line; in this case users can only authenticate if they have a personal staff account.

Little Auth

The authlib.little_auth app contains a basic user model with email as username that can be used if you do not want to write your own user model but still profit from authlib's authentication support.

Usage is as follows:

Email Registration

For email registration to work, two templates are needed:

A starting point would be:

email_registration_email.txt:

.. code-block:: text

Subject (1st line)

Body (3rd line onwards)
{{ url }}
...

email_registration.html:

.. code-block:: html

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
        {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
        {{ message }}
    </li>
    {% endfor %}
</ul>
{% endif %}

{% if form.errors and not form.non_field_errors %}
<p class="errornote">
    {% if form.errors.items|length == 1 %}
    {% translate "Please correct the error below." %}
    {% else %}
    {% translate "Please correct the errors below." %}
    {% endif %}
</p>
{% endif %}

{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
<p class="errornote">
    {{ error }}
</p>
{% endfor %}
{% endif %}

<form action='{% url "email_registration" %}' method="post" >
    {% csrf_token %}
    <table>
        {{ form }}
    </table>
    <input type="submit" value="login">
</form>

The above template is inspired from:

More details are documented in the relevant module <https://github.com/matthiask/django-authlib/blob/main/authlib/email.py>_.