customizing.txt 49 KB

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