customizing.txt 47 KB

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