| 1 |
==================================== |
| 2 |
Customizing authentication in Django |
| 3 |
==================================== |
| 4 |
|
| 5 |
The authentication that comes with Django is good enough for most common cases, |
| 6 |
but you may have needs not met by the out-of-the-box defaults. Customizing |
| 7 |
authentication in your projects requires understanding what points of the |
| 8 |
provided system are extensible or replaceable. This document provides details |
| 9 |
about how the auth system can be customized. |
| 10 |
|
| 11 |
:ref:`Authentication backends <authentication-backends>` provide an extensible |
| 12 |
system for when a username and password stored with the user model need to be |
| 13 |
authenticated against a different service than Django's default. |
| 14 |
|
| 15 |
You can give your models :ref:`custom permissions <custom-permissions>` that |
| 16 |
can be checked through Django's authorization system. |
| 17 |
|
| 18 |
You can :ref:`extend <extending-user>` the default ``User`` model, or |
| 19 |
:ref:`substitute <auth-custom-user>` a completely customized model. |
| 20 |
|
| 21 |
.. _authentication-backends: |
| 22 |
|
| 23 |
Other authentication sources |
| 24 |
============================ |
| 25 |
|
| 26 |
There may be times you have the need to hook into another authentication source |
| 27 |
-- that is, another source of usernames and passwords or authentication |
| 28 |
methods. |
| 29 |
|
| 30 |
For example, your company may already have an LDAP setup that stores a username |
| 31 |
and password for every employee. It'd be a hassle for both the network |
| 32 |
administrator and the users themselves if users had separate accounts in LDAP |
| 33 |
and the Django-based applications. |
| 34 |
|
| 35 |
So, to handle situations like this, the Django authentication system lets you |
| 36 |
plug in other authentication sources. You can override Django's default |
| 37 |
database-based scheme, or you can use the default system in tandem with other |
| 38 |
systems. |
| 39 |
|
| 40 |
See the :ref:`authentication backend reference |
| 41 |
<authentication-backends-reference>` for information on the authentication |
| 42 |
backends included with Django. |
| 43 |
|
| 44 |
Specifying authentication backends |
| 45 |
---------------------------------- |
| 46 |
|
| 47 |
Behind the scenes, Django maintains a list of "authentication backends" that it |
| 48 |
checks for authentication. When somebody calls |
| 49 |
:func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log |
| 50 |
a user in <how-to-log-a-user-in>` -- Django tries authenticating across |
| 51 |
all of its authentication backends. If the first authentication method fails, |
| 52 |
Django tries the second one, and so on, until all backends have been attempted. |
| 53 |
|
| 54 |
The list of authentication backends to use is specified in the |
| 55 |
:setting:`AUTHENTICATION_BACKENDS` setting. This should be a list of Python |
| 56 |
path names that point to Python classes that know how to authenticate. These |
| 57 |
classes can be anywhere on your Python path. |
| 58 |
|
| 59 |
By default, :setting:`AUTHENTICATION_BACKENDS` is set to:: |
| 60 |
|
| 61 |
["django.contrib.auth.backends.ModelBackend"] |
| 62 |
|
| 63 |
That's the basic authentication backend that checks the Django users database |
| 64 |
and queries the built-in permissions. It does not provide protection against |
| 65 |
brute force attacks via any rate limiting mechanism. You may either implement |
| 66 |
your own rate limiting mechanism in a custom auth backend, or use the |
| 67 |
mechanisms provided by most web servers. |
| 68 |
|
| 69 |
The order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same |
| 70 |
username and password is valid in multiple backends, Django will stop |
| 71 |
processing at the first positive match. |
| 72 |
|
| 73 |
If a backend raises a :class:`~django.core.exceptions.PermissionDenied` |
| 74 |
exception, authentication will immediately fail. Django won't check the |
| 75 |
backends that follow. |
| 76 |
|
| 77 |
.. note:: |
| 78 |
|
| 79 |
Once a user has authenticated, Django stores which backend was used to |
| 80 |
authenticate the user in the user's session, and reuses the same backend |
| 81 |
for the duration of that session whenever access to the currently |
| 82 |
authenticated user is needed. This effectively means that authentication |
| 83 |
sources are cached on a per-session basis, so if you change |
| 84 |
:setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if |
| 85 |
you need to force users to re-authenticate using different methods. A |
| 86 |
simple way to do that is to execute ``Session.objects.all().delete()``. |
| 87 |
|
| 88 |
Writing an authentication backend |
| 89 |
--------------------------------- |
| 90 |
|
| 91 |
An authentication backend is a class that implements two required methods: |
| 92 |
``get_user(user_id)`` and ``authenticate(request, **credentials)``, as well as |
| 93 |
a set of optional permission related :ref:`authorization methods |
| 94 |
<authorization_methods>`. |
| 95 |
|
| 96 |
The ``get_user`` method takes a ``user_id`` -- which could be a username, |
| 97 |
database ID or whatever, but has to be the primary key of your user object -- |
| 98 |
and returns a user object or ``None``. |
| 99 |
|
| 100 |
The ``authenticate`` method takes a ``request`` argument and credentials as |
| 101 |
keyword arguments. Most of the time, it'll look like this:: |
| 102 |
|
| 103 |
from django.contrib.auth.backends import BaseBackend |
| 104 |
|
| 105 |
|
| 106 |
class MyBackend(BaseBackend): |
| 107 |
def authenticate(self, request, username=None, password=None): |
| 108 |
# Check the username/password and return a user. |
| 109 |
... |
| 110 |
|
| 111 |
But it could also authenticate a token, like so:: |
| 112 |
|
| 113 |
from django.contrib.auth.backends import BaseBackend |
| 114 |
|
| 115 |
|
| 116 |
class MyBackend(BaseBackend): |
| 117 |
def authenticate(self, request, token=None): |
| 118 |
# Check the token and return a user. |
| 119 |
... |
| 120 |
|
| 121 |
Either way, ``authenticate()`` should check the credentials it gets and return |
| 122 |
a user object that matches those credentials if the credentials are valid. If |
| 123 |
they're not valid, it should return ``None``. |
| 124 |
|
| 125 |
``request`` is an :class:`~django.http.HttpRequest` and may be ``None`` if it |
| 126 |
wasn't provided to :func:`~django.contrib.auth.authenticate` (which passes it |
| 127 |
on to the backend). |
| 128 |
|
| 129 |
The Django admin is tightly coupled to the Django :ref:`User object |
| 130 |
<user-objects>`. For example, for a user to access the admin, |
| 131 |
:attr:`.User.is_staff` and :attr:`.User.is_active` must be ``True`` (see |
| 132 |
:meth:`.AdminSite.has_permission` for details). |
| 133 |
|
| 134 |
The best way to deal with this is to create a Django ``User`` object for each |
| 135 |
user that exists for your backend (e.g., in your LDAP directory, your external |
| 136 |
SQL database, etc.). You can either write a script to do this in advance, or |
| 137 |
your ``authenticate`` method can do it the first time a user logs in. |
| 138 |
|
| 139 |
Here's an example backend that authenticates against a username and password |
| 140 |
variable defined in your ``settings.py`` file and creates a Django ``User`` |
| 141 |
object the first time a user authenticates. In this example, the created Django |
| 142 |
``User`` object is a superuser who will have full access to the admin:: |
| 143 |
|
| 144 |
from django.conf import settings |
| 145 |
from django.contrib.auth.backends import BaseBackend |
| 146 |
from django.contrib.auth.hashers import check_password |
| 147 |
from django.contrib.auth.models import User |
| 148 |
|
| 149 |
|
| 150 |
class SettingsBackend(BaseBackend): |
| 151 |
""" |
| 152 |
Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD. |
| 153 |
|
| 154 |
Use the login name and a hash of the password. For example: |
| 155 |
|
| 156 |
ADMIN_LOGIN = 'admin' |
| 157 |
ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M=' |
| 158 |
""" |
| 159 |
|
| 160 |
def authenticate(self, request, username=None, password=None): |
| 161 |
login_valid = settings.ADMIN_LOGIN == username |
| 162 |
pwd_valid = check_password(password, settings.ADMIN_PASSWORD) |
| 163 |
if login_valid and pwd_valid: |
| 164 |
try: |
| 165 |
user = User.objects.get(username=username) |
| 166 |
except User.DoesNotExist: |
| 167 |
# Create a new user. There's no need to set a password |
| 168 |
# because only the password from settings.py is checked. |
| 169 |
user = User(username=username) # is_active defaults to True. |
| 170 |
user.is_staff = True |
| 171 |
user.is_superuser = True |
| 172 |
user.save() |
| 173 |
return user |
| 174 |
return None |
| 175 |
|
| 176 |
def get_user(self, user_id): |
| 177 |
try: |
| 178 |
return User.objects.get(pk=user_id) |
| 179 |
except User.DoesNotExist: |
| 180 |
return None |
| 181 |
|
| 182 |
.. _authorization_methods: |
| 183 |
|
| 184 |
Handling authorization in custom backends |
| 185 |
----------------------------------------- |
| 186 |
|
| 187 |
Custom auth backends can provide their own permissions. |
| 188 |
|
| 189 |
The user model and its manager will delegate permission lookup functions |
| 190 |
(:meth:`~django.contrib.auth.models.User.get_user_permissions()`, |
| 191 |
:meth:`~django.contrib.auth.models.User.get_group_permissions()`, |
| 192 |
:meth:`~django.contrib.auth.models.User.get_all_permissions()`, |
| 193 |
:meth:`~django.contrib.auth.models.User.has_perm()`, |
| 194 |
:meth:`~django.contrib.auth.models.User.has_module_perms()`, and |
| 195 |
:meth:`~django.contrib.auth.models.UserManager.with_perm()`) to any |
| 196 |
authentication backend that implements these functions. |
| 197 |
|
| 198 |
The permissions given to the user will be the superset of all permissions |
| 199 |
returned by all backends. That is, Django grants a permission to a user that |
| 200 |
any one backend grants. |
| 201 |
|
| 202 |
If a backend raises a :class:`~django.core.exceptions.PermissionDenied` |
| 203 |
exception in :meth:`~django.contrib.auth.models.User.has_perm()` or |
| 204 |
:meth:`~django.contrib.auth.models.User.has_module_perms()`, the authorization |
| 205 |
will immediately fail and Django won't check the backends that follow. |
| 206 |
|
| 207 |
A backend could implement permissions for the magic admin like this:: |
| 208 |
|
| 209 |
from django.contrib.auth.backends import BaseBackend |
| 210 |
|
| 211 |
|
| 212 |
class MagicAdminBackend(BaseBackend): |
| 213 |
def has_perm(self, user_obj, perm, obj=None): |
| 214 |
return user_obj.username == settings.ADMIN_LOGIN |
| 215 |
|
| 216 |
This gives full permissions to the user granted access in the above example. |
| 217 |
Notice that in addition to the same arguments given to the associated |
| 218 |
:class:`django.contrib.auth.models.User` functions, the backend auth functions |
| 219 |
all take the user object, which may be an anonymous user, as an argument. |
| 220 |
|
| 221 |
A full authorization implementation can be found in the ``ModelBackend`` class |
| 222 |
in :source:`django/contrib/auth/backends.py`, which is the default backend and |
| 223 |
queries the ``auth_permission`` table most of the time. |
| 224 |
|
| 225 |
.. _anonymous_auth: |
| 226 |
|
| 227 |
Authorization for anonymous users |
| 228 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 229 |
|
| 230 |
An anonymous user is one that is not authenticated i.e. they have provided no |
| 231 |
valid authentication details. However, that does not necessarily mean they are |
| 232 |
not authorized to do anything. At the most basic level, most websites |
| 233 |
authorize anonymous users to browse most of the site, and many allow anonymous |
| 234 |
posting of comments etc. |
| 235 |
|
| 236 |
Django's permission framework does not have a place to store permissions for |
| 237 |
anonymous users. However, the user object passed to an authentication backend |
| 238 |
may be an :class:`django.contrib.auth.models.AnonymousUser` object, allowing |
| 239 |
the backend to specify custom authorization behavior for anonymous users. This |
| 240 |
is especially useful for the authors of reusable apps, who can delegate all |
| 241 |
questions of authorization to the auth backend, rather than needing settings, |
| 242 |
for example, to control anonymous access. |
| 243 |
|
| 244 |
.. _inactive_auth: |
| 245 |
|
| 246 |
Authorization for inactive users |
| 247 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 248 |
|
| 249 |
An inactive user is one that has its |
| 250 |
:attr:`~django.contrib.auth.models.User.is_active` field set to ``False``. The |
| 251 |
:class:`~django.contrib.auth.backends.ModelBackend` and |
| 252 |
:class:`~django.contrib.auth.backends.RemoteUserBackend` authentication |
| 253 |
backends prohibits these users from authenticating. If a custom user model |
| 254 |
doesn't have an :attr:`~django.contrib.auth.models.CustomUser.is_active` field, |
| 255 |
all users will be allowed to authenticate. |
| 256 |
|
| 257 |
You can use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend` |
| 258 |
or :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend` if you |
| 259 |
want to allow inactive users to authenticate. |
| 260 |
|
| 261 |
The support for anonymous users in the permission system allows for a scenario |
| 262 |
where anonymous users have permissions to do something while inactive |
| 263 |
authenticated users do not. |
| 264 |
|
| 265 |
Do not forget to test for the ``is_active`` attribute of the user in your own |
| 266 |
backend permission methods. |
| 267 |
|
| 268 |
Handling object permissions |
| 269 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 270 |
|
| 271 |
Django's permission framework has a foundation for object permissions, though |
| 272 |
there is no implementation for it in the core. That means that checking for |
| 273 |
object permissions will always return ``False`` or an empty list (depending on |
| 274 |
the check performed). An authentication backend will receive the keyword |
| 275 |
parameters ``obj`` and ``user_obj`` for each object related authorization |
| 276 |
method and can return the object level permission as appropriate. |
| 277 |
|
| 278 |
.. _custom-permissions: |
| 279 |
|
| 280 |
Custom permissions |
| 281 |
================== |
| 282 |
|
| 283 |
To create custom permissions for a given model object, use the ``permissions`` |
| 284 |
:ref:`model Meta attribute <meta-options>`. |
| 285 |
|
| 286 |
This example ``Task`` model creates two custom permissions, i.e., actions users |
| 287 |
can or cannot do with ``Task`` instances, specific to your application:: |
| 288 |
|
| 289 |
class Task(models.Model): |
| 290 |
... |
| 291 |
|
| 292 |
class Meta: |
| 293 |
permissions = [ |
| 294 |
("change_task_status", "Can change the status of tasks"), |
| 295 |
("close_task", "Can remove a task by setting its status as closed"), |
| 296 |
] |
| 297 |
|
| 298 |
The only thing this does is create those extra permissions when you run |
| 299 |
:djadmin:`manage.py migrate <migrate>` (the function that creates permissions |
| 300 |
is connected to the :data:`~django.db.models.signals.post_migrate` signal). |
| 301 |
Your code is in charge of checking the value of these permissions when a user |
| 302 |
is trying to access the functionality provided by the application (changing the |
| 303 |
status of tasks or closing tasks.) Continuing the above example, the following |
| 304 |
checks if a user may close tasks:: |
| 305 |
|
| 306 |
user.has_perm("app.close_task") |
| 307 |
|
| 308 |
.. _extending-user: |
| 309 |
|
| 310 |
Extending the existing ``User`` model |
| 311 |
===================================== |
| 312 |
|
| 313 |
There are two ways to extend the default |
| 314 |
:class:`~django.contrib.auth.models.User` model without substituting your own |
| 315 |
model. If the changes you need are purely behavioral, and don't require any |
| 316 |
change to what is stored in the database, you can create a :ref:`proxy model |
| 317 |
<proxy-models>` based on :class:`~django.contrib.auth.models.User`. This |
| 318 |
allows for any of the features offered by proxy models including default |
| 319 |
ordering, custom managers, or custom model methods. |
| 320 |
|
| 321 |
If you wish to store information related to ``User``, you can use a |
| 322 |
:class:`~django.db.models.OneToOneField` to a model containing the fields for |
| 323 |
additional information. This one-to-one model is often called a profile model, |
| 324 |
as it might store non-auth related information about a site user. For example |
| 325 |
you might create an Employee model:: |
| 326 |
|
| 327 |
from django.contrib.auth.models import User |
| 328 |
|
| 329 |
|
| 330 |
class Employee(models.Model): |
| 331 |
user = models.OneToOneField(User, on_delete=models.CASCADE) |
| 332 |
department = models.CharField(max_length=100) |
| 333 |
|
| 334 |
Assuming an existing Employee Fred Smith who has both a User and Employee |
| 335 |
model, you can access the related information using Django's standard related |
| 336 |
model conventions: |
| 337 |
|
| 338 |
.. code-block:: pycon |
| 339 |
|
| 340 |
>>> u = User.objects.get(username="fsmith") |
| 341 |
>>> freds_department = u.employee.department |
| 342 |
|
| 343 |
To add a profile model's fields to the user page in the admin, define an |
| 344 |
:class:`~django.contrib.admin.InlineModelAdmin` (for this example, we'll use a |
| 345 |
:class:`~django.contrib.admin.StackedInline`) in your app's ``admin.py`` and |
| 346 |
add it to a ``UserAdmin`` class which is registered with the |
| 347 |
:class:`~django.contrib.auth.models.User` class:: |
| 348 |
|
| 349 |
from django.contrib import admin |
| 350 |
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin |
| 351 |
from django.contrib.auth.models import User |
| 352 |
|
| 353 |
from my_user_profile_app.models import Employee |
| 354 |
|
| 355 |
|
| 356 |
# Define an inline admin descriptor for Employee model |
| 357 |
# which acts a bit like a singleton |
| 358 |
class EmployeeInline(admin.StackedInline): |
| 359 |
model = Employee |
| 360 |
can_delete = False |
| 361 |
verbose_name_plural = "employee" |
| 362 |
|
| 363 |
|
| 364 |
# Define a new User admin |
| 365 |
class UserAdmin(BaseUserAdmin): |
| 366 |
inlines = [EmployeeInline] |
| 367 |
|
| 368 |
|
| 369 |
# Re-register UserAdmin |
| 370 |
admin.site.unregister(User) |
| 371 |
admin.site.register(User, UserAdmin) |
| 372 |
|
| 373 |
These profile models are not special in any way - they are just Django models |
| 374 |
that happen to have a one-to-one link with a user model. As such, they aren't |
| 375 |
auto created when a user is created, but |
| 376 |
a :attr:`django.db.models.signals.post_save` could be used to create or update |
| 377 |
related models as appropriate. |
| 378 |
|
| 379 |
Using related models results in additional queries or joins to retrieve the |
| 380 |
related data. Depending on your needs, a custom user model that includes the |
| 381 |
related fields may be your better option, however, existing relations to the |
| 382 |
default user model within your project's apps may justify the extra database |
| 383 |
load. |
| 384 |
|
| 385 |
.. _auth-custom-user: |
| 386 |
|
| 387 |
Substituting a custom ``User`` model |
| 388 |
==================================== |
| 389 |
|
| 390 |
Some kinds of projects may have authentication requirements for which Django's |
| 391 |
built-in :class:`~django.contrib.auth.models.User` model is not always |
| 392 |
appropriate. For instance, on some sites it makes more sense to use an email |
| 393 |
address as your identification token instead of a username. |
| 394 |
|
| 395 |
Django allows you to override the default user model by providing a value for |
| 396 |
the :setting:`AUTH_USER_MODEL` setting that references a custom model:: |
| 397 |
|
| 398 |
AUTH_USER_MODEL = "myapp.MyUser" |
| 399 |
|
| 400 |
This dotted pair describes the :attr:`~django.apps.AppConfig.label` of the |
| 401 |
Django app (which must be in your :setting:`INSTALLED_APPS`), and the name of |
| 402 |
the Django model that you wish to use as your user model. |
| 403 |
|
| 404 |
Using a custom user model when starting a project |
| 405 |
------------------------------------------------- |
| 406 |
|
| 407 |
If you're starting a new project, you can set up a custom user model that |
| 408 |
behaves identically to the default user model by subclassing |
| 409 |
:class:`~django.contrib.auth.models.AbstractUser`:: |
| 410 |
|
| 411 |
from django.contrib.auth.models import AbstractUser |
| 412 |
|
| 413 |
|
| 414 |
class User(AbstractUser): |
| 415 |
pass |
| 416 |
|
| 417 |
Don't forget to point :setting:`AUTH_USER_MODEL` to it. Do this before creating |
| 418 |
any migrations or running ``manage.py migrate`` for the first time. |
| 419 |
|
| 420 |
Also, register the model in the app's ``admin.py``:: |
| 421 |
|
| 422 |
from django.contrib import admin |
| 423 |
from django.contrib.auth.admin import UserAdmin |
| 424 |
from .models import User |
| 425 |
|
| 426 |
admin.site.register(User, UserAdmin) |
| 427 |
|
| 428 |
Changing to a custom user model mid-project |
| 429 |
------------------------------------------- |
| 430 |
|
| 431 |
Changing :setting:`AUTH_USER_MODEL` after you've created database tables is |
| 432 |
possible, but can be complex, since it affects foreign keys and many-to-many |
| 433 |
relationships, for example. |
| 434 |
|
| 435 |
This change can't be done automatically and requires manually fixing your |
| 436 |
schema, moving your data from the old user table, and possibly manually |
| 437 |
reapplying some migrations. See :ticket:`25313` for an outline of the steps. |
| 438 |
|
| 439 |
Due to limitations of Django's dynamic dependency feature for swappable |
| 440 |
models, the model referenced by :setting:`AUTH_USER_MODEL` must be created in |
| 441 |
the first migration of its app (usually called ``0001_initial``); otherwise, |
| 442 |
you'll have dependency issues. |
| 443 |
|
| 444 |
In addition, you may run into a ``CircularDependencyError`` when running your |
| 445 |
migrations as Django won't be able to automatically break the dependency loop |
| 446 |
due to the dynamic dependency. If you see this error, you should break the loop |
| 447 |
by moving the models depended on by your user model into a second migration. |
| 448 |
(You can try making two normal models that have a ``ForeignKey`` to each other |
| 449 |
and seeing how ``makemigrations`` resolves that circular dependency if you want |
| 450 |
to see how it's usually done.) |
| 451 |
|
| 452 |
Reusable apps and ``AUTH_USER_MODEL`` |
| 453 |
------------------------------------- |
| 454 |
|
| 455 |
Reusable apps shouldn't implement a custom user model. A project may use many |
| 456 |
apps, and two reusable apps that implemented a custom user model couldn't be |
| 457 |
used together. If you need to store per user information in your app, use |
| 458 |
a :class:`~django.db.models.ForeignKey` or |
| 459 |
:class:`~django.db.models.OneToOneField` to ``settings.AUTH_USER_MODEL`` |
| 460 |
as described below. |
| 461 |
|
| 462 |
Referencing the ``User`` model |
| 463 |
------------------------------ |
| 464 |
|
| 465 |
.. currentmodule:: django.contrib.auth |
| 466 |
|
| 467 |
If you reference :class:`~django.contrib.auth.models.User` directly (for |
| 468 |
example, by referring to it in a foreign key), your code will not work in |
| 469 |
projects where the :setting:`AUTH_USER_MODEL` setting has been changed to a |
| 470 |
different user model. |
| 471 |
|
| 472 |
.. function:: get_user_model() |
| 473 |
|
| 474 |
Instead of referring to :class:`~django.contrib.auth.models.User` directly, |
| 475 |
you should reference the user model using |
| 476 |
``django.contrib.auth.get_user_model()``. This method will return the |
| 477 |
currently active user model -- the custom user model if one is specified, or |
| 478 |
:class:`~django.contrib.auth.models.User` otherwise. |
| 479 |
|
| 480 |
When you define a foreign key or many-to-many relations to the user model, |
| 481 |
you should specify the custom model using the :setting:`AUTH_USER_MODEL` |
| 482 |
setting. For example:: |
| 483 |
|
| 484 |
from django.conf import settings |
| 485 |
from django.db import models |
| 486 |
|
| 487 |
|
| 488 |
class Article(models.Model): |
| 489 |
author = models.ForeignKey( |
| 490 |
settings.AUTH_USER_MODEL, |
| 491 |
on_delete=models.CASCADE, |
| 492 |
) |
| 493 |
|
| 494 |
When connecting to signals sent by the user model, you should specify |
| 495 |
the custom model using the :setting:`AUTH_USER_MODEL` setting. For example:: |
| 496 |
|
| 497 |
from django.conf import settings |
| 498 |
from django.db.models.signals import post_save |
| 499 |
|
| 500 |
|
| 501 |
def post_save_receiver(sender, instance, created, **kwargs): |
| 502 |
pass |
| 503 |
|
| 504 |
|
| 505 |
post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL) |
| 506 |
|
| 507 |
Generally speaking, it's easiest to refer to the user model with the |
| 508 |
:setting:`AUTH_USER_MODEL` setting in code that's executed at import time, |
| 509 |
however, it's also possible to call ``get_user_model()`` while Django |
| 510 |
is importing models, so you could use |
| 511 |
``models.ForeignKey(get_user_model(), ...)``. |
| 512 |
|
| 513 |
If your app is tested with multiple user models, using |
| 514 |
``@override_settings(AUTH_USER_MODEL=...)`` for example, and you cache the |
| 515 |
result of ``get_user_model()`` in a module-level variable, you may need to |
| 516 |
listen to the :data:`~django.test.signals.setting_changed` signal to clear |
| 517 |
the cache. For example:: |
| 518 |
|
| 519 |
from django.apps import apps |
| 520 |
from django.contrib.auth import get_user_model |
| 521 |
from django.core.signals import setting_changed |
| 522 |
from django.dispatch import receiver |
| 523 |
|
| 524 |
|
| 525 |
@receiver(setting_changed) |
| 526 |
def user_model_swapped(*, setting, **kwargs): |
| 527 |
if setting == "AUTH_USER_MODEL": |
| 528 |
apps.clear_cache() |
| 529 |
from myapp import some_module |
| 530 |
|
| 531 |
some_module.UserModel = get_user_model() |
| 532 |
|
| 533 |
.. _specifying-custom-user-model: |
| 534 |
|
| 535 |
Specifying a custom user model |
| 536 |
------------------------------ |
| 537 |
|
| 538 |
When you start your project with a custom user model, stop to consider if this |
| 539 |
is the right choice for your project. |
| 540 |
|
| 541 |
Keeping all user related information in one model removes the need for |
| 542 |
additional or more complex database queries to retrieve related models. On the |
| 543 |
other hand, it may be more suitable to store app-specific user information in a |
| 544 |
model that has a relation with your custom user model. That allows each app to |
| 545 |
specify its own user data requirements without potentially conflicting or |
| 546 |
breaking assumptions by other apps. It also means that you would keep your user |
| 547 |
model as simple as possible, focused on authentication, and following the |
| 548 |
minimum requirements Django expects custom user models to meet. |
| 549 |
|
| 550 |
If you use the default authentication backend, then your model must have a |
| 551 |
single unique field that can be used for identification purposes. This can |
| 552 |
be a username, an email address, or any other unique attribute. A non-unique |
| 553 |
username field is allowed if you use a custom authentication backend that |
| 554 |
can support it. |
| 555 |
|
| 556 |
The easiest way to construct a compliant custom user model is to inherit from |
| 557 |
:class:`~django.contrib.auth.models.AbstractBaseUser`. |
| 558 |
:class:`~django.contrib.auth.models.AbstractBaseUser` provides the core |
| 559 |
implementation of a user model, including hashed passwords and tokenized |
| 560 |
password resets. You must then provide some key implementation details: |
| 561 |
|
| 562 |
.. currentmodule:: django.contrib.auth |
| 563 |
|
| 564 |
.. class:: models.CustomUser |
| 565 |
|
| 566 |
.. attribute:: USERNAME_FIELD |
| 567 |
|
| 568 |
A string describing the name of the field on the user model that is |
| 569 |
used as the unique identifier. This will usually be a username of some |
| 570 |
kind, but it can also be an email address, or any other unique |
| 571 |
identifier. The field *must* be unique (e.g. have ``unique=True`` set |
| 572 |
in its definition), unless you use a custom authentication backend that |
| 573 |
can support non-unique usernames. |
| 574 |
|
| 575 |
In the following example, the field ``identifier`` is used |
| 576 |
as the identifying field:: |
| 577 |
|
| 578 |
class MyUser(AbstractBaseUser): |
| 579 |
identifier = models.CharField(max_length=40, unique=True) |
| 580 |
... |
| 581 |
USERNAME_FIELD = "identifier" |
| 582 |
|
| 583 |
.. attribute:: EMAIL_FIELD |
| 584 |
|
| 585 |
A string describing the name of the email field on the ``User`` model. |
| 586 |
This value is returned by |
| 587 |
:meth:`~models.AbstractBaseUser.get_email_field_name`. |
| 588 |
|
| 589 |
.. attribute:: REQUIRED_FIELDS |
| 590 |
|
| 591 |
A list of the field names that will be prompted for when creating a |
| 592 |
user via the :djadmin:`createsuperuser` management command. The user |
| 593 |
will be prompted to supply a value for each of these fields. It must |
| 594 |
include any field for which :attr:`~django.db.models.Field.blank` is |
| 595 |
``False`` or undefined and may include additional fields you want |
| 596 |
prompted for when a user is created interactively. |
| 597 |
``REQUIRED_FIELDS`` has no effect in other parts of Django, like |
| 598 |
creating a user in the admin. |
| 599 |
|
| 600 |
For example, here is the partial definition for a user model that |
| 601 |
defines two required fields - a date of birth and height:: |
| 602 |
|
| 603 |
class MyUser(AbstractBaseUser): |
| 604 |
... |
| 605 |
date_of_birth = models.DateField() |
| 606 |
height = models.FloatField() |
| 607 |
... |
| 608 |
REQUIRED_FIELDS = ["date_of_birth", "height"] |
| 609 |
|
| 610 |
.. note:: |
| 611 |
|
| 612 |
``REQUIRED_FIELDS`` must contain all required fields on your user |
| 613 |
model, but should *not* contain the ``USERNAME_FIELD`` or |
| 614 |
``password`` as these fields will always be prompted for. |
| 615 |
|
| 616 |
.. attribute:: is_active |
| 617 |
|
| 618 |
A boolean attribute that indicates whether the user is considered |
| 619 |
"active". This attribute is provided as an attribute on |
| 620 |
``AbstractBaseUser`` defaulting to ``True``. How you choose to |
| 621 |
implement it will depend on the details of your chosen auth backends. |
| 622 |
See the documentation of the :attr:`is_active attribute on the built-in |
| 623 |
user model <django.contrib.auth.models.User.is_active>` for details. |
| 624 |
|
| 625 |
.. method:: get_full_name() |
| 626 |
|
| 627 |
Optional. A longer formal identifier for the user such as their full |
| 628 |
name. If implemented, this appears alongside the username in an |
| 629 |
object's history in :mod:`django.contrib.admin`. |
| 630 |
|
| 631 |
.. method:: get_short_name() |
| 632 |
|
| 633 |
Optional. A short, informal identifier for the user such as their |
| 634 |
first name. If implemented, this replaces the username in the greeting |
| 635 |
to the user in the header of :mod:`django.contrib.admin`. |
| 636 |
|
| 637 |
.. admonition:: Importing ``AbstractBaseUser`` |
| 638 |
|
| 639 |
``AbstractBaseUser`` and ``BaseUserManager`` are importable from |
| 640 |
``django.contrib.auth.base_user`` so that they can be imported without |
| 641 |
including ``django.contrib.auth`` in :setting:`INSTALLED_APPS`. |
| 642 |
|
| 643 |
The following attributes and methods are available on any subclass of |
| 644 |
:class:`~django.contrib.auth.models.AbstractBaseUser`: |
| 645 |
|
| 646 |
.. class:: models.AbstractBaseUser |
| 647 |
|
| 648 |
.. method:: get_username() |
| 649 |
|
| 650 |
Returns the value of the field nominated by ``USERNAME_FIELD``. |
| 651 |
|
| 652 |
.. method:: clean() |
| 653 |
|
| 654 |
Normalizes the username by calling :meth:`normalize_username`. If you |
| 655 |
override this method, be sure to call ``super()`` to retain the |
| 656 |
normalization. |
| 657 |
|
| 658 |
.. classmethod:: get_email_field_name() |
| 659 |
|
| 660 |
Returns the name of the email field specified by the |
| 661 |
:attr:`~models.CustomUser.EMAIL_FIELD` attribute. Defaults to |
| 662 |
``'email'`` if ``EMAIL_FIELD`` isn't specified. |
| 663 |
|
| 664 |
.. classmethod:: normalize_username(username) |
| 665 |
|
| 666 |
Applies NFKC Unicode normalization to usernames so that visually |
| 667 |
identical characters with different Unicode code points are considered |
| 668 |
identical. |
| 669 |
|
| 670 |
.. attribute:: models.AbstractBaseUser.is_authenticated |
| 671 |
|
| 672 |
Read-only attribute which is always ``True`` (as opposed to |
| 673 |
``AnonymousUser.is_authenticated`` which is always ``False``). |
| 674 |
This is a way to tell if the user has been authenticated. This does not |
| 675 |
imply any permissions and doesn't check if the user is active or has |
| 676 |
a valid session. Even though normally you will check this attribute on |
| 677 |
``request.user`` to find out whether it has been populated by the |
| 678 |
:class:`~django.contrib.auth.middleware.AuthenticationMiddleware` |
| 679 |
(representing the currently logged-in user), you should know this |
| 680 |
attribute is ``True`` for any :class:`~models.User` instance. |
| 681 |
|
| 682 |
.. attribute:: models.AbstractBaseUser.is_anonymous |
| 683 |
|
| 684 |
Read-only attribute which is always ``False``. This is a way of |
| 685 |
differentiating :class:`~models.User` and :class:`~models.AnonymousUser` |
| 686 |
objects. Generally, you should prefer using |
| 687 |
:attr:`~models.User.is_authenticated` to this attribute. |
| 688 |
|
| 689 |
.. method:: models.AbstractBaseUser.set_password(raw_password) |
| 690 |
|
| 691 |
Sets the user's password to the given raw string, taking care of the |
| 692 |
password hashing. Doesn't save the |
| 693 |
:class:`~django.contrib.auth.models.AbstractBaseUser` object. |
| 694 |
|
| 695 |
When the raw_password is ``None``, the password will be set to an |
| 696 |
unusable password, as if |
| 697 |
:meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` |
| 698 |
were used. |
| 699 |
|
| 700 |
.. method:: models.AbstractBaseUser.check_password(raw_password) |
| 701 |
.. method:: models.AbstractBaseUser.acheck_password(raw_password) |
| 702 |
|
| 703 |
*Asynchronous version*: ``acheck_password()`` |
| 704 |
|
| 705 |
Returns ``True`` if the given raw string is the correct password for |
| 706 |
the user. (This takes care of the password hashing in making the |
| 707 |
comparison.) |
| 708 |
|
| 709 |
.. method:: models.AbstractBaseUser.set_unusable_password() |
| 710 |
|
| 711 |
Marks the user as having no password set. This isn't the same as |
| 712 |
having a blank string for a password. |
| 713 |
:meth:`~django.contrib.auth.models.AbstractBaseUser.check_password()` for this user |
| 714 |
will never return ``True``. Doesn't save the |
| 715 |
:class:`~django.contrib.auth.models.AbstractBaseUser` object. |
| 716 |
|
| 717 |
You may need this if authentication for your application takes place |
| 718 |
against an existing external source such as an LDAP directory. |
| 719 |
|
| 720 |
.. method:: models.AbstractBaseUser.has_usable_password() |
| 721 |
|
| 722 |
Returns ``False`` if |
| 723 |
:meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` has |
| 724 |
been called for this user. |
| 725 |
|
| 726 |
.. method:: models.AbstractBaseUser.get_session_auth_hash() |
| 727 |
|
| 728 |
Returns an HMAC of the password field. Used for |
| 729 |
:ref:`session-invalidation-on-password-change`. |
| 730 |
|
| 731 |
.. method:: models.AbstractBaseUser.get_session_auth_fallback_hash() |
| 732 |
|
| 733 |
Yields the HMAC of the password field using |
| 734 |
:setting:`SECRET_KEY_FALLBACKS`. Used by ``get_user()``. |
| 735 |
|
| 736 |
:class:`~models.AbstractUser` subclasses :class:`~models.AbstractBaseUser`: |
| 737 |
|
| 738 |
.. class:: models.AbstractUser |
| 739 |
|
| 740 |
.. method:: clean() |
| 741 |
|
| 742 |
Normalizes the email by calling |
| 743 |
:meth:`.BaseUserManager.normalize_email`. If you override this method, |
| 744 |
be sure to call ``super()`` to retain the normalization. |
| 745 |
|
| 746 |
Writing a manager for a custom user model |
| 747 |
----------------------------------------- |
| 748 |
|
| 749 |
You should also define a custom manager for your user model. If your user model |
| 750 |
defines ``username``, ``email``, ``is_staff``, ``is_active``, ``is_superuser``, |
| 751 |
``last_login``, and ``date_joined`` fields the same as Django's default user, |
| 752 |
you can install Django's :class:`~django.contrib.auth.models.UserManager`; |
| 753 |
however, if your user model defines different fields, you'll need to define a |
| 754 |
custom manager that extends :class:`~django.contrib.auth.models.BaseUserManager` |
| 755 |
providing two additional methods: |
| 756 |
|
| 757 |
.. class:: models.CustomUserManager |
| 758 |
|
| 759 |
.. method:: models.CustomUserManager.create_user(username_field, password=None, **other_fields) |
| 760 |
|
| 761 |
The prototype of ``create_user()`` should accept the username field, |
| 762 |
plus all required fields as arguments. For example, if your user model |
| 763 |
uses ``email`` as the username field, and has ``date_of_birth`` as a |
| 764 |
required field, then ``create_user`` should be defined as:: |
| 765 |
|
| 766 |
def create_user(self, email, date_of_birth, password=None): |
| 767 |
# create user here |
| 768 |
... |
| 769 |
|
| 770 |
.. method:: models.CustomUserManager.create_superuser(username_field, password=None, **other_fields) |
| 771 |
|
| 772 |
The prototype of ``create_superuser()`` should accept the username |
| 773 |
field, plus all required fields as arguments. For example, if your user |
| 774 |
model uses ``email`` as the username field, and has ``date_of_birth`` |
| 775 |
as a required field, then ``create_superuser`` should be defined as:: |
| 776 |
|
| 777 |
def create_superuser(self, email, date_of_birth, password=None): |
| 778 |
# create superuser here |
| 779 |
... |
| 780 |
|
| 781 |
For a :class:`~.ForeignKey` in :attr:`.USERNAME_FIELD` or |
| 782 |
:attr:`.REQUIRED_FIELDS`, these methods receive the value of the |
| 783 |
:attr:`~.ForeignKey.to_field` (the :attr:`~django.db.models.Field.primary_key` |
| 784 |
by default) of an existing instance. |
| 785 |
|
| 786 |
:class:`~django.contrib.auth.models.BaseUserManager` provides the following |
| 787 |
utility methods: |
| 788 |
|
| 789 |
.. class:: models.BaseUserManager |
| 790 |
|
| 791 |
.. classmethod:: models.BaseUserManager.normalize_email(email) |
| 792 |
|
| 793 |
Normalizes email addresses by lowercasing the domain portion of the |
| 794 |
email address. |
| 795 |
|
| 796 |
.. method:: models.BaseUserManager.get_by_natural_key(username) |
| 797 |
.. method:: models.BaseUserManager.aget_by_natural_key(username) |
| 798 |
|
| 799 |
*Asynchronous version*: ``aget_by_natural_key()`` |
| 800 |
|
| 801 |
Retrieves a user instance using the contents of the field |
| 802 |
nominated by ``USERNAME_FIELD``. |
| 803 |
|
| 804 |
.. versionchanged:: 5.2 |
| 805 |
|
| 806 |
``aget_by_natural_key()`` method was added. |
| 807 |
|
| 808 |
Extending Django's default ``User`` |
| 809 |
----------------------------------- |
| 810 |
|
| 811 |
If you're entirely happy with Django's :class:`~django.contrib.auth.models.User` |
| 812 |
model, but you want to add some additional profile information, you could |
| 813 |
subclass :class:`django.contrib.auth.models.AbstractUser` and add your custom |
| 814 |
profile fields, although we'd recommend a separate model as described in |
| 815 |
:ref:`specifying-custom-user-model`. ``AbstractUser`` provides the full |
| 816 |
implementation of the default :class:`~django.contrib.auth.models.User` as an |
| 817 |
:ref:`abstract model <abstract-base-classes>`. |
| 818 |
|
| 819 |
.. _custom-users-and-the-built-in-auth-forms: |
| 820 |
|
| 821 |
Custom users and the built-in auth forms |
| 822 |
---------------------------------------- |
| 823 |
|
| 824 |
Django's built-in :ref:`forms <built-in-auth-forms>` and :ref:`views |
| 825 |
<built-in-auth-views>` make certain assumptions about the user model that they |
| 826 |
are working with. |
| 827 |
|
| 828 |
The following forms are compatible with any subclass of |
| 829 |
:class:`~django.contrib.auth.models.AbstractBaseUser`: |
| 830 |
|
| 831 |
* :class:`~django.contrib.auth.forms.AuthenticationForm`: Uses the username |
| 832 |
field specified by :attr:`~models.CustomUser.USERNAME_FIELD`. |
| 833 |
* :class:`~django.contrib.auth.forms.SetPasswordForm` |
| 834 |
* :class:`~django.contrib.auth.forms.PasswordChangeForm` |
| 835 |
* :class:`~django.contrib.auth.forms.AdminPasswordChangeForm` |
| 836 |
|
| 837 |
The following forms make assumptions about the user model and can be used as-is |
| 838 |
if those assumptions are met: |
| 839 |
|
| 840 |
* :class:`~django.contrib.auth.forms.PasswordResetForm`: Assumes that the user |
| 841 |
model has a field that stores the user's email address with the name returned |
| 842 |
by :meth:`~models.AbstractBaseUser.get_email_field_name` (``email`` by |
| 843 |
default) that can be used to identify the user and a boolean field named |
| 844 |
``is_active`` to prevent password resets for inactive users. |
| 845 |
|
| 846 |
Finally, the following forms are tied to |
| 847 |
:class:`~django.contrib.auth.models.User` and need to be rewritten or extended |
| 848 |
to work with a custom user model: |
| 849 |
|
| 850 |
* :class:`~django.contrib.auth.forms.UserCreationForm` |
| 851 |
* :class:`~django.contrib.auth.forms.UserChangeForm` |
| 852 |
|
| 853 |
If your custom user model is a subclass of ``AbstractUser``, then you can |
| 854 |
extend these forms in this manner:: |
| 855 |
|
| 856 |
from django.contrib.auth.forms import UserCreationForm |
| 857 |
from myapp.models import CustomUser |
| 858 |
|
| 859 |
|
| 860 |
class CustomUserCreationForm(UserCreationForm): |
| 861 |
class Meta(UserCreationForm.Meta): |
| 862 |
model = CustomUser |
| 863 |
fields = UserCreationForm.Meta.fields + ("custom_field",) |
| 864 |
|
| 865 |
Custom users and :mod:`django.contrib.admin` |
| 866 |
-------------------------------------------- |
| 867 |
|
| 868 |
If you want your custom user model to also work with the admin, your user model |
| 869 |
must define some additional attributes and methods. These methods allow the |
| 870 |
admin to control access of the user to admin content: |
| 871 |
|
| 872 |
.. class:: models.CustomUser |
| 873 |
:noindex: |
| 874 |
|
| 875 |
.. attribute:: is_staff |
| 876 |
|
| 877 |
Returns ``True`` if the user is allowed to have access to the admin site. |
| 878 |
|
| 879 |
.. attribute:: is_active |
| 880 |
|
| 881 |
Returns ``True`` if the user account is currently active. |
| 882 |
|
| 883 |
.. method:: has_perm(perm, obj=None): |
| 884 |
|
| 885 |
Returns ``True`` if the user has the named permission. If ``obj`` is |
| 886 |
provided, the permission needs to be checked against a specific object |
| 887 |
instance. |
| 888 |
|
| 889 |
.. method:: has_module_perms(app_label): |
| 890 |
|
| 891 |
Returns ``True`` if the user has permission to access models in |
| 892 |
the given app. |
| 893 |
|
| 894 |
You will also need to register your custom user model with the admin. If |
| 895 |
your custom user model extends ``django.contrib.auth.models.AbstractUser``, |
| 896 |
you can use Django's existing ``django.contrib.auth.admin.UserAdmin`` |
| 897 |
class. However, if your user model extends |
| 898 |
:class:`~django.contrib.auth.models.AbstractBaseUser`, you'll need to define |
| 899 |
a custom ``ModelAdmin`` class. It may be possible to subclass the default |
| 900 |
``django.contrib.auth.admin.UserAdmin``; however, you'll need to |
| 901 |
override any of the definitions that refer to fields on |
| 902 |
``django.contrib.auth.models.AbstractUser`` that aren't on your |
| 903 |
custom user class. |
| 904 |
|
| 905 |
.. note:: |
| 906 |
|
| 907 |
If you are using a custom ``ModelAdmin`` which is a subclass of |
| 908 |
``django.contrib.auth.admin.UserAdmin``, then you need to add your custom |
| 909 |
fields to ``fieldsets`` (for fields to be used in editing users) and to |
| 910 |
``add_fieldsets`` (for fields to be used when creating a user). For |
| 911 |
example:: |
| 912 |
|
| 913 |
from django.contrib.auth.admin import UserAdmin |
| 914 |
|
| 915 |
|
| 916 |
class CustomUserAdmin(UserAdmin): |
| 917 |
... |
| 918 |
fieldsets = UserAdmin.fieldsets + ((None, {"fields": ["custom_field"]}),) |
| 919 |
add_fieldsets = UserAdmin.add_fieldsets + ((None, {"fields": ["custom_field"]}),) |
| 920 |
|
| 921 |
See :ref:`a full example <custom-users-admin-full-example>` for more |
| 922 |
details. |
| 923 |
|
| 924 |
Custom users and permissions |
| 925 |
---------------------------- |
| 926 |
|
| 927 |
To make it easy to include Django's permission framework into your own user |
| 928 |
class, Django provides :class:`~django.contrib.auth.models.PermissionsMixin`. |
| 929 |
This is an abstract model you can include in the class hierarchy for your user |
| 930 |
model, giving you all the methods and database fields necessary to support |
| 931 |
Django's permission model. |
| 932 |
|
| 933 |
:class:`~django.contrib.auth.models.PermissionsMixin` provides the following |
| 934 |
methods and attributes: |
| 935 |
|
| 936 |
.. class:: models.PermissionsMixin |
| 937 |
|
| 938 |
.. attribute:: models.PermissionsMixin.is_superuser |
| 939 |
|
| 940 |
Boolean. Designates that this user has all permissions without |
| 941 |
explicitly assigning them. |
| 942 |
|
| 943 |
.. method:: models.PermissionsMixin.get_user_permissions(obj=None) |
| 944 |
|
| 945 |
Returns a set of permission strings that the user has directly. |
| 946 |
|
| 947 |
If ``obj`` is passed in, only returns the user permissions for this |
| 948 |
specific object. |
| 949 |
|
| 950 |
.. method:: models.PermissionsMixin.get_group_permissions(obj=None) |
| 951 |
|
| 952 |
Returns a set of permission strings that the user has, through their |
| 953 |
groups. |
| 954 |
|
| 955 |
If ``obj`` is passed in, only returns the group permissions for |
| 956 |
this specific object. |
| 957 |
|
| 958 |
.. method:: models.PermissionsMixin.get_all_permissions(obj=None) |
| 959 |
|
| 960 |
Returns a set of permission strings that the user has, both through |
| 961 |
group and user permissions. |
| 962 |
|
| 963 |
If ``obj`` is passed in, only returns the permissions for this |
| 964 |
specific object. |
| 965 |
|
| 966 |
.. method:: models.PermissionsMixin.has_perm(perm, obj=None) |
| 967 |
|
| 968 |
Returns ``True`` if the user has the specified permission, where |
| 969 |
``perm`` is in the format ``"<app label>.<permission codename>"`` (see |
| 970 |
:ref:`permissions <topic-authorization>`). If :attr:`.User.is_active` |
| 971 |
and :attr:`~.User.is_superuser` are both ``True``, this method always |
| 972 |
returns ``True``. |
| 973 |
|
| 974 |
If ``obj`` is passed in, this method won't check for a permission for |
| 975 |
the model, but for this specific object. |
| 976 |
|
| 977 |
.. method:: models.PermissionsMixin.has_perms(perm_list, obj=None) |
| 978 |
|
| 979 |
Returns ``True`` if the user has each of the specified permissions, |
| 980 |
where each perm is in the format |
| 981 |
``"<app label>.<permission codename>"``. If :attr:`.User.is_active` and |
| 982 |
:attr:`~.User.is_superuser` are both ``True``, this method always |
| 983 |
returns ``True``. |
| 984 |
|
| 985 |
If ``obj`` is passed in, this method won't check for permissions for |
| 986 |
the model, but for the specific object. |
| 987 |
|
| 988 |
.. method:: models.PermissionsMixin.has_module_perms(package_name) |
| 989 |
|
| 990 |
Returns ``True`` if the user has any permissions in the given package |
| 991 |
(the Django app label). If :attr:`.User.is_active` and |
| 992 |
:attr:`~.User.is_superuser` are both ``True``, this method always |
| 993 |
returns ``True``. |
| 994 |
|
| 995 |
.. admonition:: ``PermissionsMixin`` and ``ModelBackend`` |
| 996 |
|
| 997 |
If you don't include the |
| 998 |
:class:`~django.contrib.auth.models.PermissionsMixin`, you must ensure you |
| 999 |
don't invoke the permissions methods on ``ModelBackend``. ``ModelBackend`` |
| 1000 |
assumes that certain fields are available on your user model. If your user |
| 1001 |
model doesn't provide those fields, you'll receive database errors when |
| 1002 |
you check permissions. |
| 1003 |
|
| 1004 |
Custom users and proxy models |
| 1005 |
----------------------------- |
| 1006 |
|
| 1007 |
One limitation of custom user models is that installing a custom user model |
| 1008 |
will break any proxy model extending :class:`~django.contrib.auth.models.User`. |
| 1009 |
Proxy models must be based on a concrete base class; by defining a custom user |
| 1010 |
model, you remove the ability of Django to reliably identify the base class. |
| 1011 |
|
| 1012 |
If your project uses proxy models, you must either modify the proxy to extend |
| 1013 |
the user model that's in use in your project, or merge your proxy's behavior |
| 1014 |
into your :class:`~django.contrib.auth.models.User` subclass. |
| 1015 |
|
| 1016 |
.. _custom-users-admin-full-example: |
| 1017 |
|
| 1018 |
A full example |
| 1019 |
-------------- |
| 1020 |
|
| 1021 |
Here is an example of an admin-compliant custom user app. This user model uses |
| 1022 |
an email address as the username, and has a required date of birth; it |
| 1023 |
provides no permission checking beyond an ``admin`` flag on the user account. |
| 1024 |
This model would be compatible with all the built-in auth forms and views, |
| 1025 |
except for the user creation forms. This example illustrates how most of the |
| 1026 |
components work together, but is not intended to be copied directly into |
| 1027 |
projects for production use. |
| 1028 |
|
| 1029 |
This code would all live in a ``models.py`` file for a custom |
| 1030 |
authentication app:: |
| 1031 |
|
| 1032 |
from django.db import models |
| 1033 |
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser |
| 1034 |
|
| 1035 |
|
| 1036 |
class MyUserManager(BaseUserManager): |
| 1037 |
def create_user(self, email, date_of_birth, password=None): |
| 1038 |
""" |
| 1039 |
Creates and saves a User with the given email, date of |
| 1040 |
birth and password. |
| 1041 |
""" |
| 1042 |
if not email: |
| 1043 |
raise ValueError("Users must have an email address") |
| 1044 |
|
| 1045 |
user = self.model( |
| 1046 |
email=self.normalize_email(email), |
| 1047 |
date_of_birth=date_of_birth, |
| 1048 |
) |
| 1049 |
|
| 1050 |
user.set_password(password) |
| 1051 |
user.save(using=self._db) |
| 1052 |
return user |
| 1053 |
|
| 1054 |
def create_superuser(self, email, date_of_birth, password=None): |
| 1055 |
""" |
| 1056 |
Creates and saves a superuser with the given email, date of |
| 1057 |
birth and password. |
| 1058 |
""" |
| 1059 |
user = self.create_user( |
| 1060 |
email, |
| 1061 |
password=password, |
| 1062 |
date_of_birth=date_of_birth, |
| 1063 |
) |
| 1064 |
user.is_admin = True |
| 1065 |
user.save(using=self._db) |
| 1066 |
return user |
| 1067 |
|
| 1068 |
|
| 1069 |
class MyUser(AbstractBaseUser): |
| 1070 |
email = models.EmailField( |
| 1071 |
verbose_name="email address", |
| 1072 |
max_length=255, |
| 1073 |
unique=True, |
| 1074 |
) |
| 1075 |
date_of_birth = models.DateField() |
| 1076 |
is_active = models.BooleanField(default=True) |
| 1077 |
is_admin = models.BooleanField(default=False) |
| 1078 |
|
| 1079 |
objects = MyUserManager() |
| 1080 |
|
| 1081 |
USERNAME_FIELD = "email" |
| 1082 |
REQUIRED_FIELDS = ["date_of_birth"] |
| 1083 |
|
| 1084 |
def __str__(self): |
| 1085 |
return self.email |
| 1086 |
|
| 1087 |
def has_perm(self, perm, obj=None): |
| 1088 |
"Does the user have a specific permission?" |
| 1089 |
# Simplest possible answer: Yes, always |
| 1090 |
return True |
| 1091 |
|
| 1092 |
def has_module_perms(self, app_label): |
| 1093 |
"Does the user have permissions to view the app `app_label`?" |
| 1094 |
# Simplest possible answer: Yes, always |
| 1095 |
return True |
| 1096 |
|
| 1097 |
@property |
| 1098 |
def is_staff(self): |
| 1099 |
"Is the user a member of staff?" |
| 1100 |
# Simplest possible answer: All admins are staff |
| 1101 |
return self.is_admin |
| 1102 |
|
| 1103 |
Then, to register this custom user model with Django's admin, the following |
| 1104 |
code would be required in the app's ``admin.py`` file:: |
| 1105 |
|
| 1106 |
from django import forms |
| 1107 |
from django.contrib import admin |
| 1108 |
from django.contrib.auth.models import Group |
| 1109 |
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin |
| 1110 |
from django.contrib.auth.forms import ReadOnlyPasswordHashField |
| 1111 |
from django.core.exceptions import ValidationError |
| 1112 |
|
| 1113 |
from customauth.models import MyUser |
| 1114 |
|
| 1115 |
|
| 1116 |
class UserCreationForm(forms.ModelForm): |
| 1117 |
"""A form for creating new users. Includes all the required |
| 1118 |
fields, plus a repeated password.""" |
| 1119 |
|
| 1120 |
password1 = forms.CharField(label="Password", widget=forms.PasswordInput) |
| 1121 |
password2 = forms.CharField( |
| 1122 |
label="Password confirmation", widget=forms.PasswordInput |
| 1123 |
) |
| 1124 |
|
| 1125 |
class Meta: |
| 1126 |
model = MyUser |
| 1127 |
fields = ["email", "date_of_birth"] |
| 1128 |
|
| 1129 |
def clean_password2(self): |
| 1130 |
# Check that the two password entries match |
| 1131 |
password1 = self.cleaned_data.get("password1") |
| 1132 |
password2 = self.cleaned_data.get("password2") |
| 1133 |
if password1 and password2 and password1 != password2: |
| 1134 |
raise ValidationError("Passwords don't match") |
| 1135 |
return password2 |
| 1136 |
|
| 1137 |
def save(self, commit=True): |
| 1138 |
# Save the provided password in hashed format |
| 1139 |
user = super().save(commit=False) |
| 1140 |
user.set_password(self.cleaned_data["password1"]) |
| 1141 |
if commit: |
| 1142 |
user.save() |
| 1143 |
return user |
| 1144 |
|
| 1145 |
|
| 1146 |
class UserChangeForm(forms.ModelForm): |
| 1147 |
"""A form for updating users. Includes all the fields on |
| 1148 |
the user, but replaces the password field with admin's |
| 1149 |
disabled password hash display field. |
| 1150 |
""" |
| 1151 |
|
| 1152 |
password = ReadOnlyPasswordHashField() |
| 1153 |
|
| 1154 |
class Meta: |
| 1155 |
model = MyUser |
| 1156 |
fields = ["email", "password", "date_of_birth", "is_active", "is_admin"] |
| 1157 |
|
| 1158 |
|
| 1159 |
class UserAdmin(BaseUserAdmin): |
| 1160 |
# The forms to add and change user instances |
| 1161 |
form = UserChangeForm |
| 1162 |
add_form = UserCreationForm |
| 1163 |
|
| 1164 |
# The fields to be used in displaying the User model. |
| 1165 |
# These override the definitions on the base UserAdmin |
| 1166 |
# that reference specific fields on auth.User. |
| 1167 |
list_display = ["email", "date_of_birth", "is_admin"] |
| 1168 |
list_filter = ["is_admin"] |
| 1169 |
fieldsets = [ |
| 1170 |
(None, {"fields": ["email", "password"]}), |
| 1171 |
("Personal info", {"fields": ["date_of_birth"]}), |
| 1172 |
("Permissions", {"fields": ["is_admin"]}), |
| 1173 |
] |
| 1174 |
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin |
| 1175 |
# overrides get_fieldsets to use this attribute when creating a user. |
| 1176 |
add_fieldsets = [ |
| 1177 |
( |
| 1178 |
None, |
| 1179 |
{ |
| 1180 |
"classes": ["wide"], |
| 1181 |
"fields": ["email", "date_of_birth", "password1", "password2"], |
| 1182 |
}, |
| 1183 |
), |
| 1184 |
] |
| 1185 |
search_fields = ["email"] |
| 1186 |
ordering = ["email"] |
| 1187 |
filter_horizontal = [] |
| 1188 |
|
| 1189 |
|
| 1190 |
# Now register the new UserAdmin... |
| 1191 |
admin.site.register(MyUser, UserAdmin) |
| 1192 |
# ... and, since we're not using Django's built-in permissions, |
| 1193 |
# unregister the Group model from admin. |
| 1194 |
admin.site.unregister(Group) |
| 1195 |
|
| 1196 |
Finally, specify the custom model as the default user model for your project |
| 1197 |
using the :setting:`AUTH_USER_MODEL` setting in your ``settings.py``:: |
| 1198 |
|
| 1199 |
AUTH_USER_MODEL = "customauth.MyUser" |
| 1200 |
|
| 1201 |
.. _writing-authentication-backends-async-interface: |
| 1202 |
|
| 1203 |
Adding an async interface |
| 1204 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1205 |
|
| 1206 |
.. versionadded:: 5.2 |
| 1207 |
|
| 1208 |
To optimize performance when called from an async context authentication, |
| 1209 |
backends can implement async versions of each function - ``aget_user(user_id)`` |
| 1210 |
and ``aauthenticate(request, **credentials)``. When an authentication backend |
| 1211 |
extends ``BaseBackend`` and async versions of these functions are not provided, |
| 1212 |
they will be automatically synthesized with ``sync_to_async``. This has |
| 1213 |
:ref:`performance penalties <async_performance>`. |
| 1214 |
|
| 1215 |
While an async interface is optional, a synchronous interface is always |
| 1216 |
required. There is no automatic synthesis for a synchronous interface if an |
| 1217 |
async interface is implemented. |
| 1218 |
|
| 1219 |
Django's out-of-the-box authentication backends have native async support. If |
| 1220 |
these native backends are extended take special care to make sure the async |
| 1221 |
versions of modified functions are modified as well. |