customizing.txt 44 KB

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