customizing.txt 48 KB

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