customizing.txt 44 KB

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