A significant percentage of modern, interactive websites allow some form of user interaction – from allowing simple comments on a blog, to full editorial control of articles on a news site. If a site offers any sort of ecommerce, authentication and authorization of paying customers is essential.
Just managing users – lost usernames, forgotten passwords and keeping information up to date – can be a real pain. As a programmer, writing an authentication system can be even worse.
Lucky for us, Django provides a default implementation for managing user accounts, groups, permissions and cookie-based user sessions out of the box. Like most things in Django, the default implementation is fully extensible and customizable to suit your project’s needs. So let’s jump right in.
Overview
The Django authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do. Here the term authentication is used to refer to both tasks.
The authentication system consists of:
- Users
- Permissions: Binary (yes/no) flags designating whether a user may perform a certain task
- Groups: A generic way of applying labels and permissions to more than one user
- A configurable password hashing system
- Forms for managing user authentication and authorization
- View tools for logging in users, or restricting content
- A pluggable backend system
The authentication system in Django aims to be very generic and doesn’t provide some features commonly found in web authentication systems. Solutions for some of these common problems have been implemented in third-party packages:
- Password strength checking
- Throttling of login attempts
- Authentication against third-parties (OAuth, for example)
Using The Django Authentication System – Django’s authentication system in its default configuration has evolved to serve the most common project needs, handling a reasonably wide range of tasks, and has a careful implementation of passwords and permissions. For projects where authentication needs differ from the default, Django also supports extensive extension and customization of authentication.
User Objects – User objects are the core of the authentication system. They typically represent the people interacting with your site and are used to enable things like restricting access, registering user profiles, associating content with creators etc. Only one class of user exists in Django’s authentication framework, i.e., superusers or admin staff users are just user objects with special attributes set, not different classes of user objects. The primary attributes of the default user are:
- username
- password
- first_name
- last_name
Creating Superusers – Create superusers using the createsuperuser command:
python manage.py createsuperuser –username=joe –[email protected]
You will be prompted for a password. After you enter one, the user will be created immediately. If you leave off the –username or the –email options, it will prompt you for those values.
Creating Users – The simplest, and least error prone way to create and manage users is through the Django admin. Django also provides built in views and forms to allow users to log in and out and change their own password. We will be looking at user management via the admin and generic user forms a bit later in this chapter, but first, let’s look at how we would handle user authentication directly.
The most direct way to create users is to use the included create_user() helper function:
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user(‘john’, ‘[email protected]’, ‘johnpassword’)
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = ‘Lennon’
>>> user.save()
Changing Passwords – Django does not store raw (clear text) passwords on the user model, but only a hash. Because of this, do not attempt to manipulate the password attribute of the user directly. This is why a helper function is used when creating a user. To change a user’s password, you have two options:
- manage.py changepassword username offers a method of changing a User’s password from the command line. It prompts you to change the password of a given user which you must enter twice. If they both match, the new password will be changed immediately. If you do not supply a user, the command will attempt to change the password of the user whose username matches the current system user.
- You can also change a password programmatically, using set_password():
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username=’john’)
>>> u.set_password(‘new password’)
>>> u.save()
Changing a user’s password will log out all their sessions if the SessionAuthenticationMiddleware is enabled.
Authentication in Web Requests
Django uses sessions and middleware to hook the authentication system into request objects. These provide a request.user attribute on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of AnonymousUser, otherwise it will be an instance of User. You can tell them apart with is_authenticated(), like so:
if request.user.is_authenticated():
# Do something for authenticated users.
else:
# Do something for anonymous users.
How to Log a User In – To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework. Note that any data set during the anonymous session is retained in the session after a user logs in. This example shows how you might use both authenticate() and login():
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST[‘username’]
password = request.POST[‘password’]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
else:
# Return a ‘disabled account’ error message
else:
# Return an ‘invalid login’ error message.
Calling authenticate() firstWhen you’re manually logging a user in, you must call authenticate() before you call login(). authenticate() sets an attribute on the User noting which authentication backend successfully authenticated that user, and this information is needed later during the login process. An error will be raised if you try to login a user object retrieved from the database directly.
How to Log a User Out – To log out a user who has been logged in via login(), use logout() within your view. It takes an HttpRequest object and has no return value. Example:
from django.contrib.auth import logout
def logout_view(request):
logout(request)
# Redirect to a success page.
Note that logout() doesn’t throw any errors if the user wasn’t logged in. When you call logout(), the session data for the current request is completely cleaned out. All existing data is removed. This is to prevent another person from using the same Web browser to log in and have access to the previous user’s session data.
If you want to put anything into the session that will be available to the user immediately after logging out, do that after calling logout().
Limiting Access to Logged-In Users
The raw way – The simple, raw way to limit access to pages is to check request.user.is_authenticated() and either redirect to a login page:
from django.shortcuts import redirect
def my_view(request):
if not request.user.is_authenticated():
return redirect(‘/login/?next=%s’ % request.path)
# …
… or display an error message:
from django.shortcuts import render
def my_view(request):
if not request.user.is_authenticated():
return render(request, ‘books/login_error.html’)
# …
The login_required decorator – As a shortcut, you can use the convenient login_required() decorator:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
…login_required() does the following:
- If the user isn’t logged in, redirect to LOGIN_URL, passing the current absolute path in the query string. Example: /accounts/login/?next=/reviews/3/.
- If the user is logged in, execute the view normally. The view code is free to assume the user is logged in.
By default, the path that the user should be redirected to upon successful authentication is stored in a query string parameter called “next”. If you would prefer to use a different name for this parameter, login_required() takes an optional redirect_field_name parameter:
from django.contrib.auth.decorators import login_required
@login_required(redirect_field_name=’my_redirect_field’)
def my_view(request):
…
Note that if you provide a value to redirect_field_name, you will most likely need to customize your login template as well, since the template context variable which stores the redirect path will use the value of redirect_field_name as its key rather than “next” (the default). login_required() also takes an optional login_url parameter. Example:
from django.contrib.auth.decorators import login_required
@login_required(login_url=’/accounts/login/’)
def my_view(request):
…
Note that if you don’t specify the login_url parameter, you’ll need to ensure that the LOGIN_URL and your login view are properly associated. For example, using the defaults, add the following lines to your URLconf:
from django.contrib.auth import views as auth_views
url(r’^accounts/login/$’, auth_views.login),
The LOGIN_URL also accepts view function names and named URL patterns. This allows you to freely remap your login view within your URLconf without having to update the setting. The login_required decorator does NOT check the is_active flag on a user.
Limiting access to logged-in users that pass a test – To limit access based on certain permissions or some other test, you’d do essentially the same thing as described in the previous section. The simple way is to run your test on request.user in the view directly. For example, this view checks to make sure the user has an email in the desired domain:
def my_view(request):
if not request.user.email.endswith(‘@example.com’):
return HttpResponse(“You can’t leave a review for this book.”)
# …
As a shortcut, you can use the convenient user_passes_test decorator:
from django.contrib.auth.decorators import user_passes_test
def email_check(user):
return user.email.endswith(‘@example.com’)
@user_passes_test(email_check)
def my_view(request):
…
user_passes_test() takes a required argument: a callable that takes a User object and returns True if the user is allowed to view the page. Note that user_passes_test() does not automatically check that the User is not anonymous. user_passes_test() takes two optional arguments:
- login_url. Lets you specify the URL that users who don’t pass the test will be redirected to. It may be a login page and defaults to LOGIN_URL if you don’t specify one.
- redirect_field_name. Same as for login_required(). Setting it to None removes it from the URL, which you may want to do if you are redirecting users that don’t pass the test to a non-login page where there’s no “next page”.
For example:
@user_passes_test(email_check, login_url=’/login/’)
def my_view(request):
…
The permission_required decorator – It’s a relatively common task to check whether a user has a particular permission. For that reason, Django provides a shortcut for that case – the permission_required() decorator:
from django.contrib.auth.decorators import permission_required
@permission_required(‘reviews.can_vote’)
def my_view(request):
…
Just like the has_perm() method, permission names take the form “<app label>.<permission codename>” (i.e. reviews.can_vote for a permission on a model in the reviews application). The decorator may also take a list of permissions. Note that permission_required() also takes an optional login_url parameter. Example:
from django.contrib.auth.decorators import permission_required
@permission_required(‘reviews.can_vote’, login_url=’/loginpage/’)
def my_view(request):
…
As in the login_required() decorator, login_url defaults to LOGIN_URL. If the raise_exception parameter is given, the decorator will raise PermissionDenied, prompting the 403 (HTTP Forbidden) view instead of redirecting to the login page.
Session invalidation on password change – If your AUTH_USER_MODEL inherits from AbstractBaseUser, or implements its own get_session_auth_hash()
method, authenticated sessions will include the hash returned by this function. In the AbstractBaseUser case, this is an Hash Message Authentication Code (HMAC) of the password field.
If the SessionAuthenticationMiddleware is enabled, Django verifies that the hash sent along with each request matches the one that’s computed server-side. This allows a user to log out of all of their sessions by changing their password.
The default password change views included with Django, django.contrib.auth.views.password_change() and the user_change_password view in the django.contrib.auth admin, update the session with the new password hash so that a user changing their own password won’t log themselves out. If you have a custom password change view and wish to have similar behavior, use this function:
django.contrib.auth.decorators.update_session_auth_hash (request, user)
This function takes the current request and the updated user object from which the new session hash will be derived and updates the session hash appropriately. Example usage:
from django.contrib.auth import update_session_auth_hash
def password_change(request):
if request.method == ‘POST’:
form = PasswordChangeForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
else:
…
Since get_session_auth_hash() is based on SECRET_KEY, updating your site to use a new secret will invalidate all existing sessions.
Authentication Views
Django provides several views that you can use for handling login, logout, and password management. These make use of the built-in auth forms but you can pass in your own forms as well. Django provides no default template for the authentication views – however the template context is documented for each view below.
There are different methods to implement these views in your project, however the easiest and most common way is to include the provided URLconf in django.contrib.auth.urls in your own URLconf, for example:
urlpatterns = [url(‘^’, include(‘django.contrib.auth.urls’))]
This will make each of the views available at a default URL (detailed below).
The built-in views all return a TemplateResponse instance, which allows you to easily customize the response data before rendering. Most built-in authentication views provide a URL name for easier reference.
login – Logs a user in. Default URL: /login/
Optional arguments:
- template_name: The name of a template to display for the view used to log the user in. Defaults to registration/login.html.
- redirect_field_name: The name of a GET field containing the URL to redirect to after login. Defaults to next.
- authentication_form: A callable (typically just a form class) to use for authentication. Defaults to AuthenticationForm.
- current_app: A hint indicating which application contains the current view.
- extra_context: A dictionary of context data that will be added to the default context data passed to the template.
Here’s what login does:
- If called via GET, it displays a login form that POSTs to the same URL. More on this in a bit.
- If called via POST with user submitted credentials, it tries to log the user in. If login is successful, the view redirects to the URL specified in next. If next isn’t provided, it redirects to LOGIN_REDIRECT_URL (which defaults to /accounts/profile/). If login isn’t successful, it redisplays the login form.
It’s your responsibility to provide the html for the login template, called registration/login.html by default.
Template Context
- form: A Form object representing the AuthenticationForm.
- next: The URL to redirect to after successful login. This may contain a query string, too.
- site: The current Site, according to the SITE_ID setting. If you don’t have the site framework installed, this will be set to an instance of RequestSite, which derives the site name and domain from the current HttpRequest.
- site_name: An alias for site.name. If you don’t have the site framework installed, this will be set to the value of request.META[‘SERVER_NAME’]. If you’d prefer not to call the template registration/login.html, you can pass the template_name parameter via the extra arguments to the view in your URLconf.
logout – Logs a user out. Default URL: /logout/
Optional arguments:
- next_page: The URL to redirect to after logout.
- template_name: The full name of a template to display after logging the user out. Defaults to registration/logged_out.html if no argument is supplied.
- redirect_field_name: The name of a GET field containing the URL to redirect to after log out. Defaults to next. Overrides the next_page URL if the given GET parameter is passed.
- current_app: A hint indicating which application contains the current view.
- extra_context: A dictionary of context data that will be added to the default context data passed to the template.
Template context: - title: The string “Logged out”, localized.
- site: The current Site, according to the SITE_ID setting. If you don’t have the site framework installed, this will be set to an instance of RequestSite, which derives the site name and domain from the current HttpRequest.
- site_name: An alias for site.name. If you don’t have the site framework installed, this will be set to the value of request.META[‘SERVER_NAME’].
- current_app: A hint indicating which application contains the current view.
- extra_context: A dictionary of context data that will be added to the default context data passed to the template.
logout_then_login – Logs a user out, then redirects to the login page. Default URL: None provided.
Optional arguments:
- login_url: The URL of the login page to redirect to. Defaults to LOGIN_URL if not supplied.
- current_app: A hint indicating which application contains the current view.
- extra_context: A dictionary of context data that will be added to the default context data passed to the template.
password_change – Allows a user to change their password. Default URL: /password_change/
Optional arguments:
- template_name: The full name of a template to use for displaying the password change form. Defaults to registration/password_change_form.html if not supplied.
- post_change_redirect: The URL to redirect to after a successful password change.
- password_change_form: A custom “change password” form which must accept a user keyword argument. The form is responsible for actually changing the user’s password. Defaults to PasswordChangeForm.
- current_app: A hint indicating which application contains the current view.
- extra_context: A dictionary of context data that will be added to the default context data passed to the template.
Template context:
- form: The password change form
password_change_done – The page shown after a user has changed their password. Default URL: /password_change_done/
Optional arguments:
- template_name: The full name of a template to use. Defaults to registration/password_change_done.html if not supplied.
- current_app: A hint indicating which application contains the current view.
- extra_context: A dictionary of context data that will be added to the default context data passed to the template.
password_reset – Default URL: /password_reset/. Allows a user to reset their password by generating a one-time use link that can be used to reset the password, and sending that link to the user’s registered email address.
If the email address provided does not exist in the system, this view won’t send an email, but the user won’t receive any error message either. This prevents information leaking to potential attackers.
If you want to provide an error message in this case, you can subclass PasswordResetForm and use the password_reset_form argument.
Users flagged with an unusable password aren’t allowed to request a password reset to prevent misuse when using an external authentication source like LDAP. Note that they won’t receive any error message since this would expose their account’s existence but no mail will be sent either.
Optional arguments:
- template_name: The full name of a template to use for displaying the password reset form. Defaults to registration/password_reset_form.html if not supplied.
- email_template_name: The full name of a template to use for generating the email with the reset password link. Defaults to registration/password_reset_email.html if not supplied.
- subject_template_name: The full name of a template to use for the subject of the email with the reset password link. Defaults to registration/password_reset_subject.txt if not supplied.
- password_reset_form: Form that will be used to get the email of the user to reset the password for. Defaults to PasswordResetForm.
- token_generator: Instance of the class to check the one-time link. This will default to default_token_generator, it’s an instance of django.contrib.auth.tokens.PasswordResetTokenGenerator.
- post_reset_redirect: The URL to redirect to after a successful password reset request.
- from_email: A valid email address. By default, Django uses the DEFAULT_FROM_EMAIL.
- current_app: A hint indicating which application contains the current view.
- extra_context: A dictionary of context data that will be added to the default context data passed to the template.
- html_email_template_name: The full name of a template to use for generating a text/html multipart email with the password reset link. By default, HTML email is not sent.
Template context:
- form: The form (see password_reset_form above) for resetting the user’s password.
Email template context:
- email: An alias for user.email
- user: The current User, according to the email form field. Only active users are able to reset their passwords (User.is_active is True).
- site_name: An alias for site.name. If you don’t have the site framework installed, this will be set to the value of request.META[‘SERVER_NAME’].
- domain: An alias for site.domain. If you don’t have the site framework installed, this will be set to the value of request.get_host().
- protocol: http or https
- uid: The user’s primary key encoded in base 64.
- token: Token to check that the reset link is valid.
Sample registration/password_reset_email.html (email body template):
Someone asked for password reset for email {{ email }}. Follow the link below:
{{ protocol}}://{{ domain }}{% url ‘password_reset_confirm’ uidb64=uid token=token %}
The same template context is used for subject template. Subject must be single line plain text string.
password_reset_done – The page shown after a user has been emailed a link to reset their password. This view is called by default if the password_reset() view doesn’t have an explicit post_reset_redirect URL set. Default URL: /password_reset_done/
If the email address provided does not exist in the system, the user is inactive, or has an unusable password, the user will still be redirected to this view but no email will be sent.
Optional arguments:
template_name: The full name of a template to use. Defaults to registration/password_reset_done.html if not supplied.
current_app: A hint indicating which application contains the current view.
extra_context: A dictionary of context data that will be added to the default context data passed to the template.
password_reset_confirm – Presents a form for entering a new password. Default URL: /password_reset_confirm/
Optional arguments:
uidb64: The user’s id encoded in base 64. Defaults to None.
token: Token to check that the password is valid. Defaults to None.
template_name: The full name of a template to display the confirm password view. Default value is registration/password_reset_confirm.html.
token_generator: Instance of the class to check the password. This will default to default_token_generator, it’s an instance of django.contrib.auth.tokens.PasswordResetTokenGenerator.
set_password_form: Form that will be used to set the password. Defaults to SetPasswordForm
post_reset_redirect: URL to redirect after the password reset done. Defaults to None.
current_app: A hint indicating which application contains the current view.
extra_context: A dictionary of context data that will be added to the default context data passed to the template.
Template context:
- form: The form (see set_password_form above) for setting the new user’s password.
- validlink: Boolean, True if the link (combination of uidb64 and token) is valid or unused yet.
password_reset_complete – Presents a view which informs the user that the password has been successfully changed. Default URL: /password_reset_complete/
Optional arguments:
- template_name: The full name of a template to display the view. Defaults to registration/password_reset_complete.html.
- current_app: A hint indicating which application contains the current view.
- extra_context: A dictionary of context data that will be added to the default context data passed to the template.
The redirect_to_login helper function – Django provides a convenient function, redirect_to_login that can be used in a view for implementing custom access control. It redirects to the login page, and then back to another URL after a successful login.
- Required arguments:
next: The URL to redirect to after a successful login.
Optional arguments:
- login_url: The URL of the login page to redirect to. Defaults to LOGIN_URL if not supplied.
- redirect_field_name: The name of a GET field containing the URL to redirect to after log out. Overrides next if the given GET parameter is passed.
Authentication Forms and Templates
Built-in forms – If you don’t want to use the built-in views, but want the convenience of not having to write forms for this functionality, the authentication system provides several built-in forms located in django.contrib.auth.forms in table below.
The built-in authentication forms make certain assumptions about the user model that they are working with. If you’re using a custom User model, it may be necessary to define your own forms for the authentication system.
Django’s built-in authentication forms
AdminPasswordChangeForm | A form used in the admin interface to change a user’s password. Takes the user as the first positional argument. |
AuthenticationForm | A form for logging a user in. Takes request as its first positional argument, which is stored on the form instance for use by sub-classes. |
PasswordChangeForm | A form for allowing a user to change their password. |
PasswordResetForm | A form for generating and emailing a one-time use link to reset a user’s password. |
SetPasswordForm | A form that lets a user change their password without entering the old password. |
UserChangeForm | A form used in the admin interface to change a user’s information and permissions. |
UserCreationForm | A form for creating a new user. |
Authentication Data in Templates – The currently logged-in user and their permissions are made available in the template context when you use RequestContext.
Users – When rendering a template RequestContext, the currently logged-in user, either a User instance or an AnonymousUser instance, is stored in the template variable
{{ user }}:
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
This template context variable is not available if a RequestContext is not being used.
Permissions – The currently logged-in user’s permissions are stored in the template variable {{ perms }}. This is an instance of django.contrib.auth.context_processors.PermWrapper, which is a template-friendly proxy of permissions. In the {{ perms }} object, single-attribute lookup is a proxy to User.has_module_perms. This example would display True if the logged-in user had any permissions in the foo app:
{{ perms.foo }}
Two-level-attribute lookup is a proxy to User.has_perm. This example would display True if the logged-in user had the permission foo.can_vote:
{{ perms.foo.can_vote }}
Thus, you can check permissions in template {% if %} statements:
{% if perms.foo %}
<p>You have permission to do something in the foo app.</p>
{% if perms.foo.can_vote %}
<p>You can vote!</p>
{% endif %}
{% if perms.foo.can_drive %}
<p>You can drive!</p>
{% endif %}
{% else %}
<p>You don’t have permission to do anything in the foo app.</p>
{% endif %}
It is possible to also look permissions up by {% if in %} statements. For example:
{% if ‘foo’ in perms %}
{% if ‘foo.can_vote’ in perms %}
<p>In lookup works, too.</p>
{% endif %}
{% endif %}
Customizing Authentication in Django
The authentication that comes with Django is good enough for most common cases, but you may have needs not met by the out-of-the-box defaults. To customize authentication to your projects needs involves understanding what points of the provided system are extensible or replaceable.
Authentication backends provide an extensible system for when a username and password stored with the User model need to be authenticated against a different service than Django’s default. You can give your models custom permissions that can be checked through Django’s authorization system. You can extend the default User model, or substitute a completely customized model.
Other Authentication Sources – There may be times you have the need to hook into another authentication source – that is, another source of usernames and passwords or authentication methods.
For example, your company may already have an LDAP setup that stores a username and password for every employee. It’d be a hassle for both the network administrator and the users themselves if users had separate accounts in LDAP and the Django-based applications.
So, to handle situations like this, the Django authentication system lets you plug in other authentication sources. You can override Django’s default database-based scheme, or you can use the default system in tandem with other systems.
Specifying Authentication Backends – Behind the scenes, Django maintains a list of authentication backends that it checks for authentication. When somebody calls authenticate() – as described in the previous section on logging a user in – Django tries authenticating across all of its authentication backends. If the first authentication method fails, Django tries the second one, and so on, until all backends have been attempted.
The list of authentication backends to use is specified in the AUTHENTICATION_BACKENDS setting. This should be a list of Python path names that point to Python classes that know how to authenticate. These classes can be anywhere on your Python path. By default, AUTHENTICATION_BACKENDS
is set to:
[‘django.contrib.auth.backends.ModelBackend’]
That’s the basic authentication backend that checks the Django users database and queries the built-in permissions. It does not provide protection against brute force attacks via any rate limiting mechanism. You may either implement your own rate limiting mechanism in a custom authorization backend, or use the mechanisms provided by most Web servers. The order of AUTHENTICATION_BACKENDS matters, so if the same username and password is valid in multiple backends, Django will stop processing at the first positive match. If a backend raises a PermissionDenied exception, authentication will immediately fail. Django won’t check the backends that follow.
Once a user has authenticated, Django stores which backend was used to authenticate the user in the user’s session, and re-uses the same backend for the duration of that session whenever access to the currently authenticated user is needed. This effectively means that authentication sources are cached on a per-session basis, so if you change AUTHENTICATION_BACKENDS, you’ll need to clear out session data if you need to force users to re-authenticate using different methods. A simple way to do that is simply to execute Session.objects.all().delete().
Writing an Authentication Backend – An authentication backend is a class that implements two required methods: get_user(user_id) and authenticate(**credentials), as well as a set of optional permission related authorization methods. The get_user method takes a user_id – which could be a username, database ID or whatever, but has to be the primary key of your User object – and returns a User object. The authenticate method takes credentials as keyword arguments. Most of the time, it’ll just look like this:
class MyBackend(object):
def authenticate(self, username=None, password=None):
# Check the username/password and return a User.
…
But it could also authenticate a token, like so:
class MyBackend(object):
def authenticate(self, token=None):
# Check the token and return a User.
…
Either way, authenticate should check the credentials it gets, and it should return a User object that matches those credentials, if the credentials are valid. If they’re not valid, it should return None.
The Django admin system is tightly coupled to the Django User object.
For now, the best way to deal with this is to create a Django User object for each user that exists for your backend (e.g., in your LDAP directory, your external SQL database, etc.) You can either write a script to do this in advance, or your authenticate method can do it the first time a user logs in.
Here’s an example backend that authenticates against a username and password variable defined in your settings.py file and creates a Django User object the first time a user authenticates:
from django.conf import settings
from django.contrib.auth.models import User, check_password
class SettingsBackend(object):
“””
Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
Use the login name, and a hash of the password. For example:
ADMIN_LOGIN = ‘admin’
ADMIN_PASSWORD = ‘sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de’
“””
def authenticate(self, username=None, password=None):
login_valid = (settings.ADMIN_LOGIN == username)
pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
if login_valid and pwd_valid:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user. Note that we can set password
# to anything, because it won’t be checked; the password
# from settings.py will.
user = User(username=username, password=’password’)
user.is_staff = True
user.is_superuser = True
user.save()
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Handling Authorization in Custom Backends – Custom authorization backends can provide their own permissions. The user model will delegate permission lookup functions (get_group_permissions(), get_all_permissions(), has_perm(), and has_module_perms()) to any authentication backend that implements these functions. The permissions given to the user will be the superset of all permissions returned by all backends. That is, Django grants a permission to a user that any one backend grants.
If a backend raises a PermissionDenied exception in has_perm() or has_module_perms(), the authorization will immediately fail and Django won’t check the backends that follow. The simple backend above could implement permissions for the admin fairly simply:
class SettingsBackend(object):
…
def has_perm(self, user_obj, perm, obj=None):
if user_obj.username == settings.ADMIN_LOGIN:
return True
else:
return False
This gives full permissions to the user granted access in the above example. Notice that in addition to the same arguments given to the associated User functions, the backend authorization functions all take the user object, which may be an anonymous user, as an argument.
A full authorization implementation can be found in the ModelBackend class in django/contrib/auth/backends.py, which is the default backend and it queries the auth_permission table most of the time. If you wish to provide custom behavior for only part of the backend API, you can take advantage of Python inheritance and subclass ModelBackend instead of implementing the complete API in a custom backend.
Authorization for Anonymous Users – An anonymous user is one that is not authenticated i.e. they have provided no valid authentication details. However, that does not necessarily mean they are not authorized to do anything. At the most basic level, most Web sites authorize anonymous users to browse most of the site, and many allow anonymous posting of comments etc.
Django’s permission framework does not have a place to store permissions for anonymous users. However, the user object passed to an authentication backend may be an django.contrib.auth.models.AnonymousUser object, allowing the backend to specify custom authorization behavior for anonymous users.
This is especially useful for the authors of re-usable apps, who can delegate all questions of authorization to the auth backend, rather than needing settings, for example, to control anonymous access.
Authorization for Inactive Users – An inactive user is a one that is authenticated but has its attribute is_active set to False. However, this does not mean they are not authorized to do anything. For example, they are allowed to activate their account.
The support for anonymous users in the permission system allows for a scenario where anonymous users have permissions to do something while inactive authenticated users do not. Do not forget to test for the is_active attribute of the user in your own backend permission methods.
Handling Object Permissions – Django’s permission framework has a foundation for object permissions, though there is no implementation for it in the core. That means that checking for object permissions will always return False or an empty list (depending on the check performed). An authentication backend will receive the keyword parameters obj and user_obj for each object related authorization method and can return the object level permission as appropriate.
Custom Permissions – To create custom permissions for a given model object, use the permissions model Meta attribute. This example Task model creates three custom permissions, i.e. actions users can or cannot do with Task instances, specific to your application:
class Task(models.Model):
…
class Meta:
permissions = (
(“view_task”, “Can see available tasks”),
(“change_task_status”, “Can change the status of tasks”),
(“close_task”, “Can remove a task by setting its status as
closed”),
)
The only thing this does is create those extra permissions when you run manage.py migrate. Your code is in charge of checking the value of these permissions when a user is trying to access the functionality provided by the application (viewing tasks, changing the status of tasks, closing tasks.) Continuing the above example, the following checks if a user may view tasks:
user.has_perm(‘app.view_task’)
Extending The Existing User Model – There are two ways to extend the default User model without substituting your own model. If the changes you need are purely behavioral, and don’t require any change to what is stored in the database, you can create a proxy model based on User. This allows for any of the features offered by proxy models including default ordering, custom managers, or custom model methods.
If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user. For example, you might create an Employee model:
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
Assuming an existing Employee Fred Smith who has both a User and Employee model, you can access the related information using Django’s standard related model conventions:
>>> u = User.objects.get(username=’fsmith’)
>>> freds_department = u.employee.department
To add a profile model’s fields to the user page in the admin, define an InlineModelAdmin (for this example, we’ll use a StackedInline) in your app’s admin.py and add it to a UserAdmin class which is registered with the User class:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_user_profile_app.models import Employee
# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
model = Employee
can_delete = False
verbose_name_plural = ’employee’
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (EmployeeInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
These profile models are not special in any way – they are just Django models that happen to have a one-to-one link with a User model. As such, they do not get auto created when a user is created, but a django.db.models.signals.post_save could be used to create or update related models as appropriate.
Note that using related models results in additional queries or joins to retrieve the related data, and depending on your needs substituting the User model and adding the related fields may be your better option. However existing links to the default User model within your project’s apps may justify the extra database load.
Substituting A Custom User Model – Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username. Django allows you to override the default User model by providing a value for the AUTH_USER_MODEL setting that references a custom model:
`AUTH_USER_MODEL = ‘books.MyUser’`
This dotted pair describes the name of the Django app (which must be in your INSTALLED_APPS), and the name of the Django model that you wish to use as your User model.
Changing AUTH_USER_MODEL has a big effect on your Django project, particularly your database structure. For example, if you change your AUTH_USER_MODEL after you have run migrations, you will have to manually update your database because it affects the construction of many database table relationships. Unless there is a very good reason to do so, you should not change your AUTH_USER_MODEL.
Notwithstanding the warning above, Django does fully support custom user models, however a full explanation is beyond the scope of this book.