customizing.txt 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  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 `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 syncdb <syncdb>`. 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-profiles:
  275. .. deprecated:: 1.5
  276. With the introduction of :ref:`custom User models <auth-custom-user>`,
  277. the use of :setting:`AUTH_PROFILE_MODULE` to define a single profile
  278. model is no longer supported. See the
  279. :doc:`Django 1.5 release notes</releases/1.5>` for more information.
  280. Prior to 1.5, a single profile model could be specified site-wide with the
  281. setting :setting:`AUTH_PROFILE_MODULE` with a string consisting of the
  282. following items, separated by a dot:
  283. 1. The name of the application (case sensitive) in which the user
  284. profile model is defined (in other words, the
  285. name which was passed to :djadmin:`manage.py startapp <startapp>` to create
  286. the application).
  287. 2. The name of the model (not case sensitive) class.
  288. For example, if the profile model was a class named ``UserProfile`` and was
  289. defined inside an application named ``accounts``, the appropriate setting would
  290. be::
  291. AUTH_PROFILE_MODULE = 'accounts.UserProfile'
  292. When a user profile model has been defined and specified in this manner, each
  293. :class:`~django.contrib.auth.models.User` object will have a method --
  294. :class:`~django.contrib.auth.models.User.get_profile()` -- which returns the
  295. instance of the user profile model associated with that
  296. :class:`~django.contrib.auth.models.User`.
  297. The method :class:`~django.contrib.auth.models.User.get_profile()`
  298. does not create a profile if one does not exist.
  299. .. _auth-custom-user:
  300. Substituting a custom User model
  301. ================================
  302. .. versionadded:: 1.5
  303. Some kinds of projects may have authentication requirements for which Django's
  304. built-in :class:`~django.contrib.auth.models.User` model is not always
  305. appropriate. For instance, on some sites it makes more sense to use an email
  306. address as your identification token instead of a username.
  307. Django allows you to override the default User model by providing a value for
  308. the :setting:`AUTH_USER_MODEL` setting that references a custom model::
  309. AUTH_USER_MODEL = 'myapp.MyUser'
  310. This dotted pair describes the name of the Django app (which must be in your
  311. :setting:`INSTALLED_APPS`), and the name of the Django model that you wish to
  312. use as your User model.
  313. .. warning::
  314. Changing :setting:`AUTH_USER_MODEL` has a big effect on your database
  315. structure. It changes the tables that are available, and it will affect the
  316. construction of foreign keys and many-to-many relationships. If you intend
  317. to set :setting:`AUTH_USER_MODEL`, you should set it before running
  318. ``manage.py syncdb`` for the first time.
  319. If you have an existing project and you want to migrate to using a custom
  320. User model, you may need to look into using a migration tool like South_
  321. to ease the transition.
  322. .. _South: http://south.aeracode.org
  323. Referencing the User model
  324. --------------------------
  325. .. currentmodule:: django.contrib.auth
  326. If you reference :class:`~django.contrib.auth.models.User` directly (for
  327. example, by referring to it in a foreign key), your code will not work in
  328. projects where the :setting:`AUTH_USER_MODEL` setting has been changed to a
  329. different User model.
  330. .. function:: get_user_model()
  331. Instead of referring to :class:`~django.contrib.auth.models.User` directly,
  332. you should reference the user model using
  333. ``django.contrib.auth.get_user_model()``. This method will return the
  334. currently active User model -- the custom User model if one is specified, or
  335. :class:`~django.contrib.auth.models.User` otherwise.
  336. When you define a foreign key or many-to-many relations to the User model,
  337. you should specify the custom model using the :setting:`AUTH_USER_MODEL`
  338. setting. For example::
  339. from django.conf import settings
  340. from django.db import models
  341. class Article(models.Model):
  342. author = models.ForeignKey(settings.AUTH_USER_MODEL)
  343. Specifying a custom User model
  344. ------------------------------
  345. .. admonition:: Model design considerations
  346. Think carefully before handling information not directly related to
  347. authentication in your custom User Model.
  348. It may be better to store app-specific user information in a model
  349. that has a relation with the User model. That allows each app to specify
  350. its own user data requirements without risking conflicts with other
  351. apps. On the other hand, queries to retrieve this related information
  352. will involve a database join, which may have an effect on performance.
  353. Django expects your custom User model to meet some minimum requirements.
  354. 1. Your model must have an integer primary key.
  355. 2. Your model must have a single unique field that can be used for
  356. identification purposes. This can be a username, an email address,
  357. or any other unique attribute.
  358. 3. Your model must provide a way to address the user in a "short" and
  359. "long" form. The most common interpretation of this would be to use
  360. the user's given name as the "short" identifier, and the user's full
  361. name as the "long" identifier. However, there are no constraints on
  362. what these two methods return - if you want, they can return exactly
  363. the same value.
  364. The easiest way to construct a compliant custom User model is to inherit from
  365. :class:`~django.contrib.auth.models.AbstractBaseUser`.
  366. :class:`~django.contrib.auth.models.AbstractBaseUser` provides the core
  367. implementation of a ``User`` model, including hashed passwords and tokenized
  368. password resets. You must then provide some key implementation details:
  369. .. currentmodule:: django.contrib.auth
  370. .. class:: models.CustomUser
  371. .. attribute:: USERNAME_FIELD
  372. A string describing the name of the field on the User model that is
  373. used as the unique identifier. This will usually be a username of
  374. some kind, but it can also be an email address, or any other unique
  375. identifier. The field *must* be unique (i.e., have ``unique=True``
  376. set in its definition).
  377. In the following example, the field ``identifier`` is used
  378. as the identifying field::
  379. class MyUser(AbstractBaseUser):
  380. identifier = models.CharField(max_length=40, unique=True, db_index=True)
  381. ...
  382. USERNAME_FIELD = 'identifier'
  383. .. attribute:: REQUIRED_FIELDS
  384. A list of the field names that *must* be provided when creating a user
  385. via the :djadmin:`createsuperuser` management command. The user will be
  386. prompted to supply a value for each of these fields. It should include
  387. any field for which :attr:`~django.db.models.Field.blank` is ``False``
  388. or undefined, but may include additional fields you want prompted for
  389. when a user is created interactively. However, it will not work for
  390. :class:`~django.db.models.ForeignKey` fields.
  391. For example, here is the partial definition for a ``User`` model that
  392. defines two required fields - a date of birth and height::
  393. class MyUser(AbstractBaseUser):
  394. ...
  395. date_of_birth = models.DateField()
  396. height = models.FloatField()
  397. ...
  398. REQUIRED_FIELDS = ['date_of_birth', 'height']
  399. .. note::
  400. ``REQUIRED_FIELDS`` must contain all required fields on your User
  401. model, but should *not* contain the ``USERNAME_FIELD``.
  402. .. attribute:: is_active
  403. A boolean attribute that indicates whether the user is considered
  404. "active". This attribute is provided as an attribute on
  405. ``AbstractBaseUser`` defaulting to ``True``. How you choose to
  406. implement it will depend on the details of your chosen auth backends.
  407. See the documentation of the :attr:`attribute on the builtin user model
  408. <django.contrib.auth.models.User.is_active>` for details.
  409. .. method:: get_full_name()
  410. A longer formal identifier for the user. A common interpretation
  411. would be the full name name of the user, but it can be any string that
  412. identifies the user.
  413. .. method:: get_short_name()
  414. A short, informal identifier for the user. A common interpretation
  415. would be the first name of the user, but it can be any string that
  416. identifies the user in an informal way. It may also return the same
  417. value as :meth:`django.contrib.auth.models.User.get_full_name()`.
  418. The following methods are available on any subclass of
  419. :class:`~django.contrib.auth.models.AbstractBaseUser`:
  420. .. class:: models.AbstractBaseUser
  421. .. method:: get_username()
  422. Returns the value of the field nominated by ``USERNAME_FIELD``.
  423. .. method:: models.AbstractBaseUser.is_anonymous()
  424. Always returns ``False``. This is a way of differentiating
  425. from :class:`~django.contrib.auth.models.AnonymousUser` objects.
  426. Generally, you should prefer using
  427. :meth:`~django.contrib.auth.models.AbstractBaseUser.is_authenticated()` to this
  428. method.
  429. .. method:: models.AbstractBaseUser.is_authenticated()
  430. Always returns ``True``. This is a way to tell if the user has been
  431. authenticated. This does not imply any permissions, and doesn't check
  432. if the user is active - it only indicates that the user has provided a
  433. valid username and password.
  434. .. method:: models.AbstractBaseUser.set_password(raw_password)
  435. Sets the user's password to the given raw string, taking care of the
  436. password hashing. Doesn't save the
  437. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  438. When the raw_password is ``None``, the password will be set to an
  439. unusable password, as if
  440. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()`
  441. were used.
  442. .. versionchanged:: 1.6
  443. In Django 1.4 and 1.5, a blank string was unintentionally stored
  444. as an unsable password as well.
  445. .. method:: models.AbstractBaseUser.check_password(raw_password)
  446. Returns ``True`` if the given raw string is the correct password for
  447. the user. (This takes care of the password hashing in making the
  448. comparison.)
  449. .. versionchanged:: 1.6
  450. In Django 1.4 and 1.5, a blank string was unintentionally
  451. considered to be an unusable password, resulting in this method
  452. returning ``False`` for such a password.
  453. .. method:: models.AbstractBaseUser.set_unusable_password()
  454. Marks the user as having no password set. This isn't the same as
  455. having a blank string for a password.
  456. :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password()` for this user
  457. will never return ``True``. Doesn't save the
  458. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  459. You may need this if authentication for your application takes place
  460. against an existing external source such as an LDAP directory.
  461. .. method:: models.AbstractBaseUser.has_usable_password()
  462. Returns ``False`` if
  463. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` has
  464. been called for this user.
  465. You should also define a custom manager for your ``User`` model. If your
  466. ``User`` model defines ``username`` and ``email`` fields the same as Django's
  467. default ``User``, you can just install Django's
  468. :class:`~django.contrib.auth.models.UserManager`; however, if your ``User``
  469. model defines different fields, you will need to define a custom manager that
  470. extends :class:`~django.contrib.auth.models.BaseUserManager` providing two
  471. additional methods:
  472. .. class:: models.CustomUserManager
  473. .. method:: models.CustomUserManager.create_user(*username_field*, password=None, \**other_fields)
  474. The prototype of ``create_user()`` should accept the username field,
  475. plus all required fields as arguments. For example, if your user model
  476. uses ``email`` as the username field, and has ``date_of_birth`` as a
  477. required fields, then ``create_user`` should be defined as::
  478. def create_user(self, email, date_of_birth, password=None):
  479. # create user here
  480. ...
  481. .. method:: models.CustomUserManager.create_superuser(*username_field*, password, \**other_fields)
  482. The prototype of ``create_superuser()`` should accept the username
  483. field, plus all required fields as arguments. For example, if your user
  484. model uses ``email`` as the username field, and has ``date_of_birth``
  485. as a required fields, then ``create_superuser`` should be defined as::
  486. def create_superuser(self, email, date_of_birth, password):
  487. # create superuser here
  488. ...
  489. Unlike ``create_user()``, ``create_superuser()`` *must* require the
  490. caller to provider a password.
  491. :class:`~django.contrib.auth.models.BaseUserManager` provides the following
  492. utility methods:
  493. .. class:: models.BaseUserManager
  494. .. method:: models.BaseUserManager.normalize_email(email)
  495. A classmethod that normalizes email addresses by lowercasing
  496. the domain portion of the email address.
  497. .. method:: models.BaseUserManager.get_by_natural_key(username)
  498. Retrieves a user instance using the contents of the field
  499. nominated by ``USERNAME_FIELD``.
  500. .. method:: models.BaseUserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
  501. Returns a random password with the given length and given string of
  502. allowed characters. (Note that the default value of ``allowed_chars``
  503. doesn't contain letters that can cause user confusion, including:
  504. * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
  505. letter L, uppercase letter i, and the number one)
  506. * ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o,
  507. and zero)
  508. Extending Django's default User
  509. -------------------------------
  510. If you're entirely happy with Django's :class:`~django.contrib.auth.models.User`
  511. model and you just want to add some additional profile information, you can
  512. simply subclass ``django.contrib.auth.models.AbstractUser`` and add your
  513. custom profile fields. This class provides the full implementation of the
  514. default :class:`~django.contrib.auth.models.User` as an :ref:`abstract model
  515. <abstract-base-classes>`.
  516. .. _custom-users-and-the-built-in-auth-forms:
  517. Custom users and the built-in auth forms
  518. ----------------------------------------
  519. As you may expect, built-in Django's :ref:`forms <built-in-auth-forms>` and
  520. :ref:`views <built-in-auth-views>` make certain assumptions about the user
  521. model that they are working with.
  522. If your user model doesn't follow the same assumptions, it may be necessary to define
  523. a replacement form, and pass that form in as part of the configuration of the
  524. auth views.
  525. * :class:`~django.contrib.auth.forms.UserCreationForm`
  526. Depends on the :class:`~django.contrib.auth.models.User` model.
  527. Must be re-written for any custom user model.
  528. * :class:`~django.contrib.auth.forms.UserChangeForm`
  529. Depends on the :class:`~django.contrib.auth.models.User` model.
  530. Must be re-written for any custom user model.
  531. * :class:`~django.contrib.auth.forms.AuthenticationForm`
  532. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`,
  533. and will adapt to use the field defined in `USERNAME_FIELD`.
  534. * :class:`~django.contrib.auth.forms.PasswordResetForm`
  535. Assumes that the user model has an integer primary key, has a field named
  536. ``email`` that can be used to identify the user, and a boolean field
  537. named `is_active` to prevent password resets for inactive users.
  538. * :class:`~django.contrib.auth.forms.SetPasswordForm`
  539. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  540. * :class:`~django.contrib.auth.forms.PasswordChangeForm`
  541. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  542. * :class:`~django.contrib.auth.forms.AdminPasswordChangeForm`
  543. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  544. Custom users and :mod:`django.contrib.admin`
  545. --------------------------------------------
  546. If you want your custom User model to also work with Admin, your User model must
  547. define some additional attributes and methods. These methods allow the admin to
  548. control access of the User to admin content:
  549. .. class:: models.CustomUser
  550. .. attribute:: is_staff
  551. Returns ``True`` if the user is allowed to have access to the admin site.
  552. .. attribute:: is_active
  553. Returns ``True`` if the user account is currently active.
  554. .. method:: has_perm(perm, obj=None):
  555. Returns ``True`` if the user has the named permission. If ``obj`` is
  556. provided, the permission needs to be checked against a specific object
  557. instance.
  558. .. method:: has_module_perms(app_label):
  559. Returns ``True`` if the user has permission to access models in
  560. the given app.
  561. You will also need to register your custom User model with the admin. If
  562. your custom User model extends ``django.contrib.auth.models.AbstractUser``,
  563. you can use Django's existing ``django.contrib.auth.admin.UserAdmin``
  564. class. However, if your User model extends
  565. :class:`~django.contrib.auth.models.AbstractBaseUser`, you'll need to define
  566. a custom ModelAdmin class. It may be possible to subclass the default
  567. ``django.contrib.auth.admin.UserAdmin``; however, you'll need to
  568. override any of the definitions that refer to fields on
  569. ``django.contrib.auth.models.AbstractUser`` that aren't on your
  570. custom User class.
  571. Custom users and permissions
  572. ----------------------------
  573. To make it easy to include Django's permission framework into your own User
  574. class, Django provides :class:`~django.contrib.auth.models.PermissionsMixin`.
  575. This is an abstract model you can include in the class hierarchy for your User
  576. model, giving you all the methods and database fields necessary to support
  577. Django's permission model.
  578. :class:`~django.contrib.auth.models.PermissionsMixin` provides the following
  579. methods and attributes:
  580. .. class:: models.PermissionsMixin
  581. .. attribute:: models.PermissionsMixin.is_superuser
  582. Boolean. Designates that this user has all permissions without
  583. explicitly assigning them.
  584. .. method:: models.PermissionsMixin.get_group_permissions(obj=None)
  585. Returns a set of permission strings that the user has, through his/her
  586. groups.
  587. If ``obj`` is passed in, only returns the group permissions for
  588. this specific object.
  589. .. method:: models.PermissionsMixin.get_all_permissions(obj=None)
  590. Returns a set of permission strings that the user has, both through
  591. group and user permissions.
  592. If ``obj`` is passed in, only returns the permissions for this
  593. specific object.
  594. .. method:: models.PermissionsMixin.has_perm(perm, obj=None)
  595. Returns ``True`` if the user has the specified permission, where perm is
  596. in the format ``"<app label>.<permission codename>"`` (see
  597. :ref:`permissions <topic-authorization>`). If the user is inactive, this method will
  598. always return ``False``.
  599. If ``obj`` is passed in, this method won't check for a permission for
  600. the model, but for this specific object.
  601. .. method:: models.PermissionsMixin.has_perms(perm_list, obj=None)
  602. Returns ``True`` if the user has each of the specified permissions,
  603. where each perm is in the format
  604. ``"<app label>.<permission codename>"``. If the user is inactive,
  605. this method will always return ``False``.
  606. If ``obj`` is passed in, this method won't check for permissions for
  607. the model, but for the specific object.
  608. .. method:: models.PermissionsMixin.has_module_perms(package_name)
  609. Returns ``True`` if the user has any permissions in the given package
  610. (the Django app label). If the user is inactive, this method will
  611. always return ``False``.
  612. .. admonition:: ModelBackend
  613. If you don't include the
  614. :class:`~django.contrib.auth.models.PermissionsMixin`, you must ensure you
  615. don't invoke the permissions methods on ``ModelBackend``. ``ModelBackend``
  616. assumes that certain fields are available on your user model. If your User
  617. model doesn't provide those fields, you will receive database errors when
  618. you check permissions.
  619. Custom users and Proxy models
  620. -----------------------------
  621. One limitation of custom User models is that installing a custom User model
  622. will break any proxy model extending :class:`~django.contrib.auth.models.User`.
  623. Proxy models must be based on a concrete base class; by defining a custom User
  624. model, you remove the ability of Django to reliably identify the base class.
  625. If your project uses proxy models, you must either modify the proxy to extend
  626. the User model that is currently in use in your project, or merge your proxy's
  627. behavior into your User subclass.
  628. Custom users and signals
  629. ------------------------
  630. Another limitation of custom User models is that you can't use
  631. :func:`django.contrib.auth.get_user_model()` as the sender or target of a signal
  632. handler. Instead, you must register the handler with the resulting User model.
  633. See :doc:`/topics/signals` for more information on registering an sending
  634. signals.
  635. Custom users and testing/fixtures
  636. ---------------------------------
  637. If you are writing an application that interacts with the User model, you must
  638. take some precautions to ensure that your test suite will run regardless of
  639. the User model that is being used by a project. Any test that instantiates an
  640. instance of User will fail if the User model has been swapped out. This
  641. includes any attempt to create an instance of User with a fixture.
  642. To ensure that your test suite will pass in any project configuration,
  643. ``django.contrib.auth.tests.utils`` defines a ``@skipIfCustomUser`` decorator.
  644. This decorator will cause a test case to be skipped if any User model other
  645. than the default Django user is in use. This decorator can be applied to a
  646. single test, or to an entire test class.
  647. Depending on your application, tests may also be needed to be added to ensure
  648. that the application works with *any* user model, not just the default User
  649. model. To assist with this, Django provides two substitute user models that
  650. can be used in test suites:
  651. * ``django.contrib.auth.tests.custom_user.CustomUser``, a custom user
  652. model that uses an ``email`` field as the username, and has a basic
  653. admin-compliant permissions setup
  654. * ``django.contrib.auth.tests.custom_user.ExtensionUser``, a custom
  655. user model that extends ``django.contrib.auth.models.AbstractUser``,
  656. adding a ``date_of_birth`` field.
  657. You can then use the ``@override_settings`` decorator to make that test run
  658. with the custom User model. For example, here is a skeleton for a test that
  659. would test three possible User models -- the default, plus the two User
  660. models provided by ``auth`` app::
  661. from django.contrib.auth.tests.utils import skipIfCustomUser
  662. from django.test import TestCase
  663. from django.test.utils import override_settings
  664. class ApplicationTestCase(TestCase):
  665. @skipIfCustomUser
  666. def test_normal_user(self):
  667. "Run tests for the normal user model"
  668. self.assertSomething()
  669. @override_settings(AUTH_USER_MODEL='auth.CustomUser')
  670. def test_custom_user(self):
  671. "Run tests for a custom user model with email-based authentication"
  672. self.assertSomething()
  673. @override_settings(AUTH_USER_MODEL='auth.ExtensionUser')
  674. def test_extension_user(self):
  675. "Run tests for a simple extension of the built-in User."
  676. self.assertSomething()
  677. A full example
  678. --------------
  679. Here is an example of an admin-compliant custom user app. This user model uses
  680. an email address as the username, and has a required date of birth; it
  681. provides no permission checking, beyond a simple ``admin`` flag on the user
  682. account. This model would be compatible with all the built-in auth forms and
  683. views, except for the User creation forms. This example illustrates how most of
  684. the components work together, but is not intended to be copied directly into
  685. projects for production use.
  686. This code would all live in a ``models.py`` file for a custom
  687. authentication app::
  688. from django.db import models
  689. from django.contrib.auth.models import (
  690. BaseUserManager, AbstractBaseUser
  691. )
  692. class MyUserManager(BaseUserManager):
  693. def create_user(self, email, date_of_birth, password=None):
  694. """
  695. Creates and saves a User with the given email, date of
  696. birth and password.
  697. """
  698. if not email:
  699. raise ValueError('Users must have an email address')
  700. user = self.model(
  701. email=self.normalize_email(email),
  702. date_of_birth=date_of_birth,
  703. )
  704. user.set_password(password)
  705. user.save(using=self._db)
  706. return user
  707. def create_superuser(self, email, date_of_birth, password):
  708. """
  709. Creates and saves a superuser with the given email, date of
  710. birth and password.
  711. """
  712. user = self.create_user(email,
  713. password=password,
  714. date_of_birth=date_of_birth
  715. )
  716. user.is_admin = True
  717. user.save(using=self._db)
  718. return user
  719. class MyUser(AbstractBaseUser):
  720. email = models.EmailField(
  721. verbose_name='email address',
  722. max_length=255,
  723. unique=True,
  724. db_index=True,
  725. )
  726. date_of_birth = models.DateField()
  727. is_active = models.BooleanField(default=True)
  728. is_admin = models.BooleanField(default=False)
  729. objects = MyUserManager()
  730. USERNAME_FIELD = 'email'
  731. REQUIRED_FIELDS = ['date_of_birth']
  732. def get_full_name(self):
  733. # The user is identified by their email address
  734. return self.email
  735. def get_short_name(self):
  736. # The user is identified by their email address
  737. return self.email
  738. def __unicode__(self):
  739. return self.email
  740. def has_perm(self, perm, obj=None):
  741. "Does the user have a specific permission?"
  742. # Simplest possible answer: Yes, always
  743. return True
  744. def has_module_perms(self, app_label):
  745. "Does the user have permissions to view the app `app_label`?"
  746. # Simplest possible answer: Yes, always
  747. return True
  748. @property
  749. def is_staff(self):
  750. "Is the user a member of staff?"
  751. # Simplest possible answer: All admins are staff
  752. return self.is_admin
  753. Then, to register this custom User model with Django's admin, the following
  754. code would be required in the app's ``admin.py`` file::
  755. from django import forms
  756. from django.contrib import admin
  757. from django.contrib.auth.models import Group
  758. from django.contrib.auth.admin import UserAdmin
  759. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  760. from customauth.models import MyUser
  761. class UserCreationForm(forms.ModelForm):
  762. """A form for creating new users. Includes all the required
  763. fields, plus a repeated password."""
  764. password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
  765. password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
  766. class Meta:
  767. model = MyUser
  768. fields = ('email', 'date_of_birth')
  769. def clean_password2(self):
  770. # Check that the two password entries match
  771. password1 = self.cleaned_data.get("password1")
  772. password2 = self.cleaned_data.get("password2")
  773. if password1 and password2 and password1 != password2:
  774. raise forms.ValidationError("Passwords don't match")
  775. return password2
  776. def save(self, commit=True):
  777. # Save the provided password in hashed format
  778. user = super(UserCreationForm, self).save(commit=False)
  779. user.set_password(self.cleaned_data["password1"])
  780. if commit:
  781. user.save()
  782. return user
  783. class UserChangeForm(forms.ModelForm):
  784. """A form for updating users. Includes all the fields on
  785. the user, but replaces the password field with admin's
  786. password hash display field.
  787. """
  788. password = ReadOnlyPasswordHashField()
  789. class Meta:
  790. model = MyUser
  791. fields = ['email', 'password', 'date_of_birth', 'is_active', 'is_admin']
  792. def clean_password(self):
  793. # Regardless of what the user provides, return the initial value.
  794. # This is done here, rather than on the field, because the
  795. # field does not have access to the initial value
  796. return self.initial["password"]
  797. class MyUserAdmin(UserAdmin):
  798. # The forms to add and change user instances
  799. form = UserChangeForm
  800. add_form = UserCreationForm
  801. # The fields to be used in displaying the User model.
  802. # These override the definitions on the base UserAdmin
  803. # that reference specific fields on auth.User.
  804. list_display = ('email', 'date_of_birth', 'is_admin')
  805. list_filter = ('is_admin',)
  806. fieldsets = (
  807. (None, {'fields': ('email', 'password')}),
  808. ('Personal info', {'fields': ('date_of_birth',)}),
  809. ('Permissions', {'fields': ('is_admin',)}),
  810. )
  811. add_fieldsets = (
  812. (None, {
  813. 'classes': ('wide',),
  814. 'fields': ('email', 'date_of_birth', 'password1', 'password2')}
  815. ),
  816. )
  817. search_fields = ('email',)
  818. ordering = ('email',)
  819. filter_horizontal = ()
  820. # Now register the new UserAdmin...
  821. admin.site.register(MyUser, MyUserAdmin)
  822. # ... and, since we're not using Django's builtin permissions,
  823. # unregister the Group model from admin.
  824. admin.site.unregister(Group)
  825. Finally, specify the custom model as the default user model for your project
  826. using the :setting:`AUTH_USER_MODEL` setting in your ``settings.py``::
  827. AUTH_USER_MODEL = 'customauth.MyUser'