customizing.txt 49 KB

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