auth.txt 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  1. =============================
  2. User authentication in Django
  3. =============================
  4. .. module:: django.contrib.auth
  5. :synopsis: Django's authentication framework.
  6. Django comes with a user authentication system. It handles user accounts,
  7. groups, permissions and cookie-based user sessions. This document explains how
  8. things work.
  9. Overview
  10. ========
  11. The auth system consists of:
  12. * Users
  13. * Permissions: Binary (yes/no) flags designating whether a user may perform
  14. a certain task.
  15. * Groups: A generic way of applying labels and permissions to more than one
  16. user.
  17. Installation
  18. ============
  19. Authentication support is bundled as a Django application in
  20. ``django.contrib.auth``. To install it, do the following:
  21. 1. Put ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
  22. your :setting:`INSTALLED_APPS` setting.
  23. (The :class:`~django.contrib.auth.models.Permission` model in
  24. :mod:`django.contrib.auth` depends on :mod:`django.contrib.contenttypes`.)
  25. 2. Run the command ``manage.py syncdb``.
  26. Note that the default :file:`settings.py` file created by
  27. :djadmin:`django-admin.py startproject <startproject>` includes
  28. ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
  29. :setting:`INSTALLED_APPS` for convenience. If your :setting:`INSTALLED_APPS`
  30. already contains these apps, feel free to run :djadmin:`manage.py syncdb
  31. <syncdb>` again; you can run that command as many times as you'd like, and each
  32. time it'll only install what's needed.
  33. The :djadmin:`syncdb` command creates the necessary database tables, creates
  34. permission objects for all installed apps that need 'em, and prompts you to
  35. create a superuser account the first time you run it.
  36. Once you've taken those steps, that's it.
  37. Users
  38. =====
  39. .. class:: models.User
  40. API reference
  41. -------------
  42. Fields
  43. ~~~~~~
  44. .. class:: models.User
  45. :class:`~django.contrib.auth.models.User` objects have the following
  46. fields:
  47. .. attribute:: models.User.username
  48. Required. 30 characters or fewer. Alphanumeric characters only
  49. (letters, digits and underscores).
  50. .. versionchanged:: 1.2
  51. Usernames may now contain ``@``, ``+``, ``.`` and ``-`` characters.
  52. .. attribute:: models.User.first_name
  53. Optional. 30 characters or fewer.
  54. .. attribute:: models.User.last_name
  55. Optional. 30 characters or fewer.
  56. .. attribute:: models.User.email
  57. Optional. Email address.
  58. .. attribute:: models.User.password
  59. Required. A hash of, and metadata about, the password. (Django doesn't
  60. store the raw password.) Raw passwords can be arbitrarily long and can
  61. contain any character. See the "Passwords" section below.
  62. .. attribute:: models.User.is_staff
  63. Boolean. Designates whether this user can access the admin site.
  64. .. attribute:: models.User.is_active
  65. Boolean. Designates whether this user account should be considered
  66. active. We recommend that you set this flag to ``False`` instead of
  67. deleting accounts; that way, if your applications have any foreign keys
  68. to users, the foreign keys won't break.
  69. This doesn't necessarily control whether or not the user can log in.
  70. Authentication backends aren't required to check for the ``is_active``
  71. flag, so if you want to reject a login based on ``is_active`` being
  72. ``False``, it's up to you to check that in your own login view.
  73. However, the :class:`~django.contrib.auth.forms.AuthenticationForm`
  74. used by the :func:`~django.contrib.auth.views.login` view *does*
  75. perform this check, as do the permission-checking methods such as
  76. :meth:`~models.User.has_perm` and the authentication in the Django
  77. admin. All of those functions/methods will return ``False`` for
  78. inactive users.
  79. .. attribute:: models.User.is_superuser
  80. Boolean. Designates that this user has all permissions without
  81. explicitly assigning them.
  82. .. attribute:: models.User.last_login
  83. A datetime of the user's last login. Is set to the current date/time by
  84. default.
  85. .. attribute:: models.User.date_joined
  86. A datetime designating when the account was created. Is set to the
  87. current date/time by default when the account is created.
  88. Methods
  89. ~~~~~~~
  90. .. class:: models.User
  91. :class:`~django.contrib.auth.models.User` objects have two many-to-many
  92. fields: ``groups`` and ``user_permissions``.
  93. :class:`~django.contrib.auth.models.User` objects can access their related
  94. objects in the same way as any other :doc:`Django model
  95. </topics/db/models>`:
  96. .. code-block:: python
  97. myuser.groups = [group_list]
  98. myuser.groups.add(group, group, ...)
  99. myuser.groups.remove(group, group, ...)
  100. myuser.groups.clear()
  101. myuser.user_permissions = [permission_list]
  102. myuser.user_permissions.add(permission, permission, ...)
  103. myuser.user_permissions.remove(permission, permission, ...)
  104. myuser.user_permissions.clear()
  105. In addition to those automatic API methods,
  106. :class:`~django.contrib.auth.models.User` objects have the following custom
  107. methods:
  108. .. method:: models.User.is_anonymous()
  109. Always returns ``False``. This is a way of differentiating
  110. :class:`~django.contrib.auth.models.User` and
  111. :class:`~django.contrib.auth.models.AnonymousUser` objects.
  112. Generally, you should prefer using
  113. :meth:`~django.contrib.auth.models.User.is_authenticated()` to this
  114. method.
  115. .. method:: models.User.is_authenticated()
  116. Always returns ``True``. This is a way to tell if the user has been
  117. authenticated. This does not imply any permissions, and doesn't check
  118. if the user is active - it only indicates that the user has provided a
  119. valid username and password.
  120. .. method:: models.User.get_full_name()
  121. Returns the :attr:`~django.contrib.auth.models.User.first_name` plus
  122. the :attr:`~django.contrib.auth.models.User.last_name`, with a space in
  123. between.
  124. .. method:: models.User.set_password(raw_password)
  125. Sets the user's password to the given raw string, taking care of the
  126. password hashing. Doesn't save the
  127. :class:`~django.contrib.auth.models.User` object.
  128. .. method:: models.User.check_password(raw_password)
  129. Returns ``True`` if the given raw string is the correct password for
  130. the user. (This takes care of the password hashing in making the
  131. comparison.)
  132. .. method:: models.User.set_unusable_password()
  133. Marks the user as having no password set. This isn't the same as
  134. having a blank string for a password.
  135. :meth:`~django.contrib.auth.models.User.check_password()` for this user
  136. will never return ``True``. Doesn't save the
  137. :class:`~django.contrib.auth.models.User` object.
  138. You may need this if authentication for your application takes place
  139. against an existing external source such as an LDAP directory.
  140. .. method:: models.User.has_usable_password()
  141. Returns ``False`` if
  142. :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
  143. been called for this user.
  144. .. method:: models.User.get_group_permissions(obj=None)
  145. Returns a set of permission strings that the user has, through his/her
  146. groups.
  147. .. versionadded:: 1.2
  148. If ``obj`` is passed in, only returns the group permissions for
  149. this specific object.
  150. .. method:: models.User.get_all_permissions(obj=None)
  151. Returns a set of permission strings that the user has, both through
  152. group and user permissions.
  153. .. versionadded:: 1.2
  154. If ``obj`` is passed in, only returns the permissions for this
  155. specific object.
  156. .. method:: models.User.has_perm(perm, obj=None)
  157. Returns ``True`` if the user has the specified permission, where perm is
  158. in the format ``"<app label>.<permission codename>"``. (see
  159. `permissions`_ section below). If the user is inactive, this method will
  160. always return ``False``.
  161. .. versionadded:: 1.2
  162. If ``obj`` is passed in, this method won't check for a permission for
  163. the model, but for this specific object.
  164. .. method:: models.User.has_perms(perm_list, obj=None)
  165. Returns ``True`` if the user has each of the specified permissions,
  166. where each perm is in the format
  167. ``"<app label>.<permission codename>"``. If the user is inactive,
  168. this method will always return ``False``.
  169. .. versionadded:: 1.2
  170. If ``obj`` is passed in, this method won't check for permissions for
  171. the model, but for the specific object.
  172. .. method:: models.User.has_module_perms(package_name)
  173. Returns ``True`` if the user has any permissions in the given package
  174. (the Django app label). If the user is inactive, this method will
  175. always return ``False``.
  176. .. method:: models.User.email_user(subject, message, from_email=None)
  177. Sends an email to the user. If
  178. :attr:`~django.contrib.auth.models.User.from_email` is ``None``, Django
  179. uses the :setting:`DEFAULT_FROM_EMAIL`.
  180. .. method:: models.User.get_profile()
  181. Returns a site-specific profile for this user. Raises
  182. :exc:`django.contrib.auth.models.SiteProfileNotAvailable` if the
  183. current site doesn't allow profiles, or
  184. :exc:`django.core.exceptions.ObjectDoesNotExist` if the user does not
  185. have a profile. For information on how to define a site-specific user
  186. profile, see the section on `storing additional user information`_ below.
  187. .. _storing additional user information: #storing-additional-information-about-users
  188. Manager functions
  189. ~~~~~~~~~~~~~~~~~
  190. .. class:: models.UserManager
  191. The :class:`~django.contrib.auth.models.User` model has a custom manager
  192. that has the following helper functions:
  193. .. method:: models.UserManager.create_user(username, email=None, password=None)
  194. .. versionchanged:: 1.4
  195. The ``email`` parameter was made optional. The username
  196. parameter is now checked for emptiness and raises a
  197. :exc:`ValueError` in case of a negative result.
  198. Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
  199. The :attr:`~django.contrib.auth.models.User.username` and
  200. :attr:`~django.contrib.auth.models.User.password` are set as given. The
  201. domain portion of :attr:`~django.contrib.auth.models.User.email` is
  202. automatically converted to lowercase, and the returned
  203. :class:`~django.contrib.auth.models.User` object will have
  204. :attr:`~models.User.is_active` set to ``True``.
  205. If no password is provided,
  206. :meth:`~django.contrib.auth.models.User.set_unusable_password()` will
  207. be called.
  208. See `Creating users`_ for example usage.
  209. .. method:: models.UserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
  210. Returns a random password with the given length and given string of
  211. allowed characters. (Note that the default value of ``allowed_chars``
  212. doesn't contain letters that can cause user confusion, including:
  213. * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
  214. letter L, uppercase letter i, and the number one)
  215. * ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o,
  216. and zero)
  217. Basic usage
  218. -----------
  219. .. _topics-auth-creating-users:
  220. Creating users
  221. ~~~~~~~~~~~~~~
  222. The most basic way to create users is to use the
  223. :meth:`~django.contrib.auth.models.UserManager.create_user` helper function
  224. that comes with Django::
  225. >>> from django.contrib.auth.models import User
  226. >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
  227. # At this point, user is a User object that has already been saved
  228. # to the database. You can continue to change its attributes
  229. # if you want to change other fields.
  230. >>> user.is_staff = True
  231. >>> user.save()
  232. You can also create users using the Django admin site. Assuming you've enabled
  233. the admin site and hooked it to the URL ``/admin/``, the "Add user" page is at
  234. ``/admin/auth/user/add/``. You should also see a link to "Users" in the "Auth"
  235. section of the main admin index page. The "Add user" admin page is different
  236. than standard admin pages in that it requires you to choose a username and
  237. password before allowing you to edit the rest of the user's fields.
  238. Also note: if you want your own user account to be able to create users using
  239. the Django admin site, you'll need to give yourself permission to add users
  240. *and* change users (i.e., the "Add user" and "Change user" permissions). If
  241. your account has permission to add users but not to change them, you won't be
  242. able to add users. Why? Because if you have permission to add users, you have
  243. the power to create superusers, which can then, in turn, change other users. So
  244. Django requires add *and* change permissions as a slight security measure.
  245. Changing passwords
  246. ~~~~~~~~~~~~~~~~~~
  247. .. versionadded:: 1.2
  248. The ``manage.py changepassword`` command was added.
  249. :djadmin:`manage.py changepassword *username* <changepassword>` offers a method
  250. of changing a User's password from the command line. It prompts you to
  251. change the password of a given user which you must enter twice. If
  252. they both match, the new password will be changed immediately. If you
  253. do not supply a user, the command will attempt to change the password
  254. whose username matches the current user.
  255. You can also change a password programmatically, using
  256. :meth:`~django.contrib.auth.models.User.set_password()`:
  257. .. code-block:: python
  258. >>> from django.contrib.auth.models import User
  259. >>> u = User.objects.get(username__exact='john')
  260. >>> u.set_password('new password')
  261. >>> u.save()
  262. Don't set the :attr:`~django.contrib.auth.models.User.password` attribute
  263. directly unless you know what you're doing. This is explained in the next
  264. section.
  265. .. _auth_password_storage:
  266. How Django stores passwords
  267. ---------------------------
  268. .. versionadded:: 1.4
  269. Django 1.4 introduces a new flexible password storage system and uses
  270. PBKDF2 by default. Previous versions of Django used SHA1, and other
  271. algorithms couldn't be chosen.
  272. The :attr:`~django.contrib.auth.models.User.password` attribute of a
  273. :class:`~django.contrib.auth.models.User` object is a string in this format::
  274. algorithm$hash
  275. That's a storage algorithm, and hash, separated by the dollar-sign
  276. character. The algorithm is one of a number of one way hashing or password
  277. storage algorithms Django can use; see below. The hash is the result of the one-
  278. way function.
  279. By default, Django uses the PBKDF2_ algorithm with a SHA256 hash, a
  280. password stretching mechanism recommended by NIST_. This should be
  281. sufficient for most users: it's quite secure, requiring massive
  282. amounts of computing time to break.
  283. However, depending on your requirements, you may choose a different
  284. algorithm, or even use a custom algorithm to match your specific
  285. security situation. Again, most users shouldn't need to do this -- if
  286. you're not sure, you probably don't. If you do, please read on:
  287. Django chooses the an algorithm by consulting the :setting:`PASSWORD_HASHERS`
  288. setting. This is a list of hashing algorithm classes that this Django
  289. installation supports. The first entry in this list (that is,
  290. ``settings.PASSWORD_HASHERS[0]``) will be used to store passwords, and all the
  291. other entries are valid hashers that can be used to check existing passwords.
  292. This means that if you want to use a different algorithm, you'll need to modify
  293. :setting:`PASSWORD_HASHERS` to list your prefered algorithm first in the list.
  294. The default for :setting:`PASSWORD_HASHERS` is::
  295. PASSWORD_HASHERS = (
  296. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  297. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  298. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  299. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  300. 'django.contrib.auth.hashers.MD5PasswordHasher',
  301. 'django.contrib.auth.hashers.CryptPasswordHasher',
  302. )
  303. This means that Django will use PBKDF2_ to store all passwords, but will support
  304. checking passwords stored with PBKDF2SHA1, bcrypt_, SHA1_, etc. The next few
  305. sections describe a couple of common ways advanced users may want to modify this
  306. setting.
  307. .. _bcrypt_usage:
  308. Using bcrypt with Django
  309. ~~~~~~~~~~~~~~~~~~~~~~~~
  310. Bcrypt_ is a popular password storage algorithm that's specifically designed
  311. for long-term password storage. It's not the default used by Django since it
  312. requires the use of third-party libraries, but since many people may want to
  313. use it Django supports bcrypt with minimal effort.
  314. To use Bcrypt as your default storage algorithm, do the following:
  315. 1. Install the `py-bcrypt`_ library (probably by running ``sudo pip install
  316. py-bcrypt``, or downloading the library and installing it with ``python
  317. setup.py install``).
  318. 2. Modify :setting:`PASSWORD_HASHERS` to list ``BCryptPasswordHasher``
  319. first. That is, in your settings file, you'd put::
  320. PASSWORD_HASHERS = (
  321. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  322. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  323. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  324. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  325. 'django.contrib.auth.hashers.MD5PasswordHasher',
  326. 'django.contrib.auth.hashers.CryptPasswordHasher',
  327. )
  328. (You need to keep the other entries in this list, or else Django won't
  329. be able to upgrade passwords; see below).
  330. That's it -- now your Django install will use Bcrypt as the default storage
  331. algorithm.
  332. .. admonition:: Other bcrypt implementations
  333. There are several other implementations that allow bcrypt to be
  334. used with Django. Django's bcrypt support is NOT directly
  335. compatible with these. To upgrade, you will need to modify the
  336. hashes in your database to be in the form `bcrypt$(raw bcrypt
  337. output)`. For example:
  338. `bcrypt$$2a$12$NT0I31Sa7ihGEWpka9ASYrEFkhuTNeBQ2xfZskIiiJeyFXhRgS.Sy`.
  339. Increasing the work factor
  340. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  341. The PDKDF2 and bcrypt algorithms use a number of iterations or rounds of
  342. hashing. This deliberately slows down attackers, making attacks against hashed
  343. passwords harder. However, as computing power increases, the number of
  344. iterations needs to be increased. We've chosen a reasonable default (and will
  345. increase it with each release of Django), but you may wish to tune it up or
  346. down, depending on your security needs and available processing power. To do so,
  347. you'll subclass the appropriate algorithm and override the ``iterations``
  348. parameters. For example, to increase the number of iterations used by the
  349. default PDKDF2 algorithm:
  350. 1. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::
  351. from django.contrib.auth.hashers import PBKDF2PasswordHasher
  352. class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
  353. """
  354. A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
  355. """
  356. iterations = PBKDF2PasswordHasher.iterations * 100
  357. Save this somewhere in your project. For example, you might put this in
  358. a file like ``myproject/hashers.py``.
  359. 2. Add your new hasher as the first entry in :setting:`PASSWORD_HASHERS`::
  360. PASSWORD_HASHERS = (
  361. 'myproject.hashers.MyPBKDF2PasswordHasher',
  362. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  363. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  364. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  365. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  366. 'django.contrib.auth.hashers.MD5PasswordHasher',
  367. 'django.contrib.auth.hashers.CryptPasswordHasher',
  368. )
  369. That's it -- now your Django install will use more iterations when it
  370. stores passwords using PBKDF2.
  371. Password upgrading
  372. ~~~~~~~~~~~~~~~~~~
  373. When users log in, if their passwords are stored with anything other than
  374. the preferred algorithm, Django will automatically upgrade the algorithm
  375. to the preferred one. This means that old installs of Django will get
  376. automatically more secure as users log in, and it also means that you
  377. can switch to new (and better) storage algorithms as they get invented.
  378. However, Django can only upgrade passwords that use algorithms mentioned in
  379. :setting:`PASSWORD_HASHERS`, so as you upgrade to new systems you should make
  380. sure never to *remove* entries from this list. If you do, users using un-
  381. mentioned algorithms won't be able to upgrade.
  382. .. _sha1: http://en.wikipedia.org/wiki/SHA1
  383. .. _pbkdf2: http://en.wikipedia.org/wiki/PBKDF2
  384. .. _nist: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
  385. .. _bcrypt: http://en.wikipedia.org/wiki/Bcrypt
  386. .. _py-bcrypt: http://pypi.python.org/pypi/py-bcrypt/
  387. Anonymous users
  388. ---------------
  389. .. class:: models.AnonymousUser
  390. :class:`django.contrib.auth.models.AnonymousUser` is a class that
  391. implements the :class:`django.contrib.auth.models.User` interface, with
  392. these differences:
  393. * :attr:`~django.contrib.auth.models.User.id` is always ``None``.
  394. * :attr:`~django.contrib.auth.models.User.is_staff` and
  395. :attr:`~django.contrib.auth.models.User.is_superuser` are always
  396. ``False``.
  397. * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
  398. * :attr:`~django.contrib.auth.models.User.groups` and
  399. :attr:`~django.contrib.auth.models.User.user_permissions` are always
  400. empty.
  401. * :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
  402. instead of ``False``.
  403. * :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
  404. ``False`` instead of ``True``.
  405. * :meth:`~django.contrib.auth.models.User.set_password()`,
  406. :meth:`~django.contrib.auth.models.User.check_password()`,
  407. :meth:`~django.contrib.auth.models.User.save()`,
  408. :meth:`~django.contrib.auth.models.User.delete()`,
  409. :meth:`~django.contrib.auth.models.User.set_groups()` and
  410. :meth:`~django.contrib.auth.models.User.set_permissions()` raise
  411. :exc:`NotImplementedError`.
  412. In practice, you probably won't need to use
  413. :class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
  414. they're used by Web requests, as explained in the next section.
  415. .. _topics-auth-creating-superusers:
  416. Creating superusers
  417. -------------------
  418. :djadmin:`manage.py syncdb <syncdb>` prompts you to create a superuser the
  419. first time you run it after adding ``'django.contrib.auth'`` to your
  420. :setting:`INSTALLED_APPS`. If you need to create a superuser at a later date,
  421. you can use a command line utility::
  422. manage.py createsuperuser --username=joe --email=joe@example.com
  423. You will be prompted for a password. After you enter one, the user will be
  424. created immediately. If you leave off the :djadminopt:`--username` or the
  425. :djadminopt:`--email` options, it will prompt you for those values.
  426. If you're using an older release of Django, the old way of creating a superuser
  427. on the command line still works::
  428. python /path/to/django/contrib/auth/create_superuser.py
  429. ...where :file:`/path/to` is the path to the Django codebase on your
  430. filesystem. The ``manage.py`` command is preferred because it figures out the
  431. correct path and environment for you.
  432. .. _auth-profiles:
  433. Storing additional information about users
  434. ------------------------------------------
  435. If you'd like to store additional information related to your users, Django
  436. provides a method to specify a site-specific related model -- termed a "user
  437. profile" -- for this purpose.
  438. To make use of this feature, define a model with fields for the
  439. additional information you'd like to store, or additional methods
  440. you'd like to have available, and also add a
  441. :class:`~django.db.models.Field.OneToOneField` named ``user`` from your model
  442. to the :class:`~django.contrib.auth.models.User` model. This will ensure only
  443. one instance of your model can be created for each
  444. :class:`~django.contrib.auth.models.User`. For example::
  445. from django.contrib.auth.models import User
  446. class UserProfile(models.Model):
  447. # This field is required.
  448. user = models.OneToOneField(User)
  449. # Other fields here
  450. accepted_eula = models.BooleanField()
  451. favorite_animal = models.CharField(max_length=20, default="Dragons.")
  452. To indicate that this model is the user profile model for a given site, fill in
  453. the setting :setting:`AUTH_PROFILE_MODULE` with a string consisting of the
  454. following items, separated by a dot:
  455. 1. The name of the application (case sensitive) in which the user
  456. profile model is defined (in other words, the
  457. name which was passed to :djadmin:`manage.py startapp <startapp>` to create
  458. the application).
  459. 2. The name of the model (not case sensitive) class.
  460. For example, if the profile model was a class named ``UserProfile`` and was
  461. defined inside an application named ``accounts``, the appropriate setting would
  462. be::
  463. AUTH_PROFILE_MODULE = 'accounts.UserProfile'
  464. When a user profile model has been defined and specified in this manner, each
  465. :class:`~django.contrib.auth.models.User` object will have a method --
  466. :class:`~django.contrib.auth.models.User.get_profile()` -- which returns the
  467. instance of the user profile model associated with that
  468. :class:`~django.contrib.auth.models.User`.
  469. The method :class:`~django.contrib.auth.models.User.get_profile()`
  470. does not create a profile if one does not exist. You need to register a handler
  471. for the User model's :attr:`django.db.models.signals.post_save` signal and, in
  472. the handler, if ``created`` is ``True``, create the associated user profile::
  473. # in models.py
  474. from django.contrib.auth.models import User
  475. from django.db.models.signals import post_save
  476. # definition of UserProfile from above
  477. # ...
  478. def create_user_profile(sender, instance, created, **kwargs):
  479. if created:
  480. UserProfile.objects.create(user=instance)
  481. post_save.connect(create_user_profile, sender=User)
  482. .. seealso:: :doc:`/topics/signals` for more information on Django's signal
  483. dispatcher.
  484. Authentication in Web requests
  485. ==============================
  486. Until now, this document has dealt with the low-level APIs for manipulating
  487. authentication-related objects. On a higher level, Django can hook this
  488. authentication framework into its system of
  489. :class:`request objects <django.http.HttpRequest>`.
  490. First, install the
  491. :class:`~django.contrib.sessions.middleware.SessionMiddleware` and
  492. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  493. middlewares by adding them to your :setting:`MIDDLEWARE_CLASSES` setting. See
  494. the :doc:`session documentation </topics/http/sessions>` for more information.
  495. Once you have those middlewares installed, you'll be able to access
  496. :attr:`request.user <django.http.HttpRequest.user>` in views.
  497. :attr:`request.user <django.http.HttpRequest.user>` will give you a
  498. :class:`~django.contrib.auth.models.User` object representing the currently
  499. logged-in user. If a user isn't currently logged in,
  500. :attr:`request.user <django.http.HttpRequest.user>` will be set to an instance
  501. of :class:`~django.contrib.auth.models.AnonymousUser` (see the previous
  502. section). You can tell them apart with
  503. :meth:`~django.contrib.auth.models.User.is_authenticated()`, like so::
  504. if request.user.is_authenticated():
  505. # Do something for authenticated users.
  506. else:
  507. # Do something for anonymous users.
  508. .. _how-to-log-a-user-in:
  509. How to log a user in
  510. --------------------
  511. Django provides two functions in :mod:`django.contrib.auth`:
  512. :func:`~django.contrib.auth.authenticate()` and
  513. :func:`~django.contrib.auth.login()`.
  514. .. function:: authenticate()
  515. To authenticate a given username and password, use
  516. :func:`~django.contrib.auth.authenticate()`. It takes two keyword
  517. arguments, ``username`` and ``password``, and it returns a
  518. :class:`~django.contrib.auth.models.User` object if the password is valid
  519. for the given username. If the password is invalid,
  520. :func:`~django.contrib.auth.authenticate()` returns ``None``. Example::
  521. from django.contrib.auth import authenticate
  522. user = authenticate(username='john', password='secret')
  523. if user is not None:
  524. if user.is_active:
  525. print("You provided a correct username and password!")
  526. else:
  527. print("Your account has been disabled!")
  528. else:
  529. print("Your username and password were incorrect.")
  530. .. function:: login()
  531. To log a user in, in a view, use :func:`~django.contrib.auth.login()`. It
  532. takes an :class:`~django.http.HttpRequest` object and a
  533. :class:`~django.contrib.auth.models.User` object.
  534. :func:`~django.contrib.auth.login()` saves the user's ID in the session,
  535. using Django's session framework, so, as mentioned above, you'll need to
  536. make sure to have the session middleware installed.
  537. Note that data set during the anonymous session is retained when the user
  538. logs in.
  539. This example shows how you might use both
  540. :func:`~django.contrib.auth.authenticate()` and
  541. :func:`~django.contrib.auth.login()`::
  542. from django.contrib.auth import authenticate, login
  543. def my_view(request):
  544. username = request.POST['username']
  545. password = request.POST['password']
  546. user = authenticate(username=username, password=password)
  547. if user is not None:
  548. if user.is_active:
  549. login(request, user)
  550. # Redirect to a success page.
  551. else:
  552. # Return a 'disabled account' error message
  553. else:
  554. # Return an 'invalid login' error message.
  555. .. admonition:: Calling ``authenticate()`` first
  556. When you're manually logging a user in, you *must* call
  557. :func:`~django.contrib.auth.authenticate()` before you call
  558. :func:`~django.contrib.auth.login()`.
  559. :func:`~django.contrib.auth.authenticate()`
  560. sets an attribute on the :class:`~django.contrib.auth.models.User` noting
  561. which authentication backend successfully authenticated that user (see the
  562. `backends documentation`_ for details), and this information is needed
  563. later during the login process.
  564. .. _backends documentation: #other-authentication-sources
  565. Manually managing a user's password
  566. -----------------------------------
  567. .. currentmodule:: django.contrib.auth.hashers
  568. .. versionadded:: 1.4
  569. The :mod:`django.contrib.auth.hashers` module provides a set of functions
  570. to create and validate hashed password. You can use them independently
  571. from the ``User`` model.
  572. .. function:: check_password(password, encoded)
  573. .. versionadded:: 1.4
  574. If you'd like to manually authenticate a user by comparing a plain-text
  575. password to the hashed password in the database, use the convenience
  576. function :func:`django.contrib.auth.hashers.check_password`. It takes two
  577. arguments: the plain-text password to check, and the full value of a
  578. user's ``password`` field in the database to check against, and returns
  579. ``True`` if they match, ``False`` otherwise.
  580. .. function:: make_password(password[, salt, hashers])
  581. .. versionadded:: 1.4
  582. Creates a hashed password in the format used by this application. It takes
  583. one mandatory argument: the password in plain-text. Optionally, you can
  584. provide a salt and a hashing algorithm to use, if you don't want to use the
  585. defaults (first entry of ``PASSWORD_HASHERS`` setting).
  586. Currently supported algorithms are: ``'pbkdf2_sha256'``, ``'pbkdf2_sha1'``,
  587. ``'bcrypt'`` (see :ref:`bcrypt_usage`), ``'sha1'``, ``'md5'``,
  588. ``'unsalted_md5'`` (only for backward compatibility) and ``'crypt'``
  589. if you have the ``crypt`` library installed. If the password argument is
  590. ``None``, an unusable password is returned (a one that will be never
  591. accepted by :func:`django.contrib.auth.hashers.check_password`).
  592. .. function:: is_password_usable(encoded_password)
  593. .. versionadded:: 1.4
  594. Checks if the given string is a hashed password that has a chance
  595. of being verified against :func:`django.contrib.auth.hashers.check_password`.
  596. How to log a user out
  597. ---------------------
  598. .. currentmodule:: django.contrib.auth
  599. .. function:: logout()
  600. To log out a user who has been logged in via
  601. :func:`django.contrib.auth.login()`, use
  602. :func:`django.contrib.auth.logout()` within your view. It takes an
  603. :class:`~django.http.HttpRequest` object and has no return value.
  604. Example::
  605. from django.contrib.auth import logout
  606. def logout_view(request):
  607. logout(request)
  608. # Redirect to a success page.
  609. Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
  610. the user wasn't logged in.
  611. When you call :func:`~django.contrib.auth.logout()`, the session data for
  612. the current request is completely cleaned out. All existing data is
  613. removed. This is to prevent another person from using the same Web browser
  614. to log in and have access to the previous user's session data. If you want
  615. to put anything into the session that will be available to the user
  616. immediately after logging out, do that *after* calling
  617. :func:`django.contrib.auth.logout()`.
  618. .. _topics-auth-signals:
  619. Login and logout signals
  620. ------------------------
  621. .. versionadded:: 1.3
  622. The auth framework uses two :doc:`signals </topics/signals>` that can be used
  623. for notification when a user logs in or out.
  624. .. data:: django.contrib.auth.signals.user_logged_in
  625. Sent when a user logs in successfully.
  626. Arguments sent with this signal:
  627. ``sender``
  628. As above: the class of the user that just logged in.
  629. ``request``
  630. The current :class:`~django.http.HttpRequest` instance.
  631. ``user``
  632. The user instance that just logged in.
  633. .. data:: django.contrib.auth.signals.user_logged_out
  634. Sent when the logout method is called.
  635. ``sender``
  636. As above: the class of the user that just logged out or ``None``
  637. if the user was not authenticated.
  638. ``request``
  639. The current :class:`~django.http.HttpRequest` instance.
  640. ``user``
  641. The user instance that just logged out or ``None`` if the
  642. user was not authenticated.
  643. Limiting access to logged-in users
  644. ----------------------------------
  645. The raw way
  646. ~~~~~~~~~~~
  647. The simple, raw way to limit access to pages is to check
  648. :meth:`request.user.is_authenticated()
  649. <django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
  650. login page::
  651. from django.http import HttpResponseRedirect
  652. def my_view(request):
  653. if not request.user.is_authenticated():
  654. return HttpResponseRedirect('/login/?next=%s' % request.path)
  655. # ...
  656. ...or display an error message::
  657. def my_view(request):
  658. if not request.user.is_authenticated():
  659. return render_to_response('myapp/login_error.html')
  660. # ...
  661. The login_required decorator
  662. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  663. .. function:: decorators.login_required([redirect_field_name=REDIRECT_FIELD_NAME, login_url=None])
  664. As a shortcut, you can use the convenient
  665. :func:`~django.contrib.auth.decorators.login_required` decorator::
  666. from django.contrib.auth.decorators import login_required
  667. @login_required
  668. def my_view(request):
  669. ...
  670. :func:`~django.contrib.auth.decorators.login_required` does the following:
  671. * If the user isn't logged in, redirect to
  672. :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
  673. path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
  674. * If the user is logged in, execute the view normally. The view code is
  675. free to assume the user is logged in.
  676. By default, the path that the user should be redirected to upon
  677. successful authentication is stored in a query string parameter called
  678. ``"next"``. If you would prefer to use a different name for this parameter,
  679. :func:`~django.contrib.auth.decorators.login_required` takes an
  680. optional ``redirect_field_name`` parameter::
  681. from django.contrib.auth.decorators import login_required
  682. @login_required(redirect_field_name='my_redirect_field')
  683. def my_view(request):
  684. ...
  685. Note that if you provide a value to ``redirect_field_name``, you will most
  686. likely need to customize your login template as well, since the template
  687. context variable which stores the redirect path will use the value of
  688. ``redirect_field_name`` as its key rather than ``"next"`` (the default).
  689. .. versionadded:: 1.3
  690. :func:`~django.contrib.auth.decorators.login_required` also takes an
  691. optional ``login_url`` parameter. Example::
  692. from django.contrib.auth.decorators import login_required
  693. @login_required(login_url='/accounts/login/')
  694. def my_view(request):
  695. ...
  696. Note that if you don't specify the ``login_url`` parameter, you'll need to map
  697. the appropriate Django view to :setting:`settings.LOGIN_URL <LOGIN_URL>`. For
  698. example, using the defaults, add the following line to your URLconf::
  699. (r'^accounts/login/$', 'django.contrib.auth.views.login'),
  700. .. function:: views.login(request, [template_name, redirect_field_name, authentication_form])
  701. **URL name:** ``login``
  702. See :doc:`the URL documentation </topics/http/urls>` for details on using
  703. named URL patterns.
  704. Here's what ``django.contrib.auth.views.login`` does:
  705. * If called via ``GET``, it displays a login form that POSTs to the
  706. same URL. More on this in a bit.
  707. * If called via ``POST``, it tries to log the user in. If login is
  708. successful, the view redirects to the URL specified in ``next``. If
  709. ``next`` isn't provided, it redirects to
  710. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  711. defaults to ``/accounts/profile/``). If login isn't successful, it
  712. redisplays the login form.
  713. It's your responsibility to provide the login form in a template called
  714. ``registration/login.html`` by default. This template gets passed four
  715. template context variables:
  716. * ``form``: A :class:`~django.forms.Form` object representing the login
  717. form. See the :doc:`forms documentation </topics/forms/index>` for
  718. more on ``Form`` objects.
  719. * ``next``: The URL to redirect to after successful login. This may
  720. contain a query string, too.
  721. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  722. according to the :setting:`SITE_ID` setting. If you don't have the
  723. site framework installed, this will be set to an instance of
  724. :class:`~django.contrib.sites.models.RequestSite`, which derives the
  725. site name and domain from the current
  726. :class:`~django.http.HttpRequest`.
  727. * ``site_name``: An alias for ``site.name``. If you don't have the site
  728. framework installed, this will be set to the value of
  729. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  730. For more on sites, see :doc:`/ref/contrib/sites`.
  731. If you'd prefer not to call the template :file:`registration/login.html`,
  732. you can pass the ``template_name`` parameter via the extra arguments to
  733. the view in your URLconf. For example, this URLconf line would use
  734. :file:`myapp/login.html` instead::
  735. (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
  736. You can also specify the name of the ``GET`` field which contains the URL
  737. to redirect to after login by passing ``redirect_field_name`` to the view.
  738. By default, the field is called ``next``.
  739. Here's a sample :file:`registration/login.html` template you can use as a
  740. starting point. It assumes you have a :file:`base.html` template that
  741. defines a ``content`` block:
  742. .. code-block:: html+django
  743. {% extends "base.html" %}
  744. {% block content %}
  745. {% if form.errors %}
  746. <p>Your username and password didn't match. Please try again.</p>
  747. {% endif %}
  748. <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
  749. {% csrf_token %}
  750. <table>
  751. <tr>
  752. <td>{{ form.username.label_tag }}</td>
  753. <td>{{ form.username }}</td>
  754. </tr>
  755. <tr>
  756. <td>{{ form.password.label_tag }}</td>
  757. <td>{{ form.password }}</td>
  758. </tr>
  759. </table>
  760. <input type="submit" value="login" />
  761. <input type="hidden" name="next" value="{{ next }}" />
  762. </form>
  763. {% endblock %}
  764. .. versionadded:: 1.2
  765. If you are using alternate authentication (see
  766. :ref:`authentication-backends`) you can pass a custom authentication form
  767. to the login view via the ``authentication_form`` parameter. This form must
  768. accept a ``request`` keyword argument in its ``__init__`` method, and
  769. provide a ``get_user`` method which returns the authenticated user object
  770. (this method is only ever called after successful form validation).
  771. .. _forms documentation: ../forms/
  772. .. _site framework docs: ../sites/
  773. .. versionadded:: 1.4
  774. The :func:`~views.login` view and the :ref:`other-built-in-views` now all
  775. return a :class:`~django.template.response.TemplateResponse` instance,
  776. which allows you to easily customize the response data before rendering.
  777. For more details, see the
  778. :doc:`TemplateResponse documentation </ref/template-response>`.
  779. .. _other-built-in-views:
  780. Other built-in views
  781. --------------------
  782. .. module:: django.contrib.auth.views
  783. In addition to the :func:`~views.login` view, the authentication system
  784. includes a few other useful built-in views located in
  785. :mod:`django.contrib.auth.views`:
  786. .. function:: logout(request, [next_page, template_name, redirect_field_name])
  787. Logs a user out.
  788. **URL name:** ``logout``
  789. See :doc:`the URL documentation </topics/http/urls>` for details on using
  790. named URL patterns.
  791. **Optional arguments:**
  792. * ``next_page``: The URL to redirect to after logout.
  793. * ``template_name``: The full name of a template to display after
  794. logging the user out. Defaults to
  795. :file:`registration/logged_out.html` if no argument is supplied.
  796. * ``redirect_field_name``: The name of a ``GET`` field containing the
  797. URL to redirect to after log out. Overrides ``next_page`` if the given
  798. ``GET`` parameter is passed.
  799. **Template context:**
  800. * ``title``: The string "Logged out", localized.
  801. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  802. according to the :setting:`SITE_ID` setting. If you don't have the
  803. site framework installed, this will be set to an instance of
  804. :class:`~django.contrib.sites.models.RequestSite`, which derives the
  805. site name and domain from the current
  806. :class:`~django.http.HttpRequest`.
  807. * ``site_name``: An alias for ``site.name``. If you don't have the site
  808. framework installed, this will be set to the value of
  809. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  810. For more on sites, see :doc:`/ref/contrib/sites`.
  811. .. function:: logout_then_login(request[, login_url])
  812. Logs a user out, then redirects to the login page.
  813. **URL name:** No default URL provided
  814. **Optional arguments:**
  815. * ``login_url``: The URL of the login page to redirect to.
  816. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  817. .. function:: password_change(request[, template_name, post_change_redirect, password_change_form])
  818. Allows a user to change their password.
  819. **URL name:** ``password_change``
  820. **Optional arguments:**
  821. * ``template_name``: The full name of a template to use for
  822. displaying the password change form. Defaults to
  823. :file:`registration/password_change_form.html` if not supplied.
  824. * ``post_change_redirect``: The URL to redirect to after a successful
  825. password change.
  826. .. versionadded:: 1.2
  827. * ``password_change_form``: A custom "change password" form which must
  828. accept a ``user`` keyword argument. The form is responsible for
  829. actually changing the user's password. Defaults to
  830. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  831. **Template context:**
  832. * ``form``: The password change form (see ``password_change_form`` above).
  833. .. function:: password_change_done(request[, template_name])
  834. The page shown after a user has changed their password.
  835. **URL name:** ``password_change_done``
  836. **Optional arguments:**
  837. * ``template_name``: The full name of a template to use.
  838. Defaults to :file:`registration/password_change_done.html` if not
  839. supplied.
  840. .. function:: password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect, from_email])
  841. Allows a user to reset their password by generating a one-time use link
  842. that can be used to reset the password, and sending that link to the
  843. user's registered email address.
  844. .. versionchanged:: 1.3
  845. The ``from_email`` argument was added.
  846. .. versionchanged:: 1.4
  847. Users flagged with an unusable password (see
  848. :meth:`~django.contrib.auth.models.User.set_unusable_password()`
  849. will not be able to request a password reset to prevent misuse
  850. when using an external authentication source like LDAP.
  851. **URL name:** ``password_reset``
  852. **Optional arguments:**
  853. * ``template_name``: The full name of a template to use for
  854. displaying the password reset form. Defaults to
  855. :file:`registration/password_reset_form.html` if not supplied.
  856. * ``email_template_name``: The full name of a template to use for
  857. generating the email with the new password. Defaults to
  858. :file:`registration/password_reset_email.html` if not supplied.
  859. * ``subject_template_name``: The full name of a template to use for
  860. the subject of the email with the new password. Defaults
  861. to :file:`registration/password_reset_subject.txt` if not supplied.
  862. .. versionadded:: 1.4
  863. * ``password_reset_form``: Form that will be used to set the password.
  864. Defaults to :class:`~django.contrib.auth.forms.PasswordResetForm`.
  865. * ``token_generator``: Instance of the class to check the password. This
  866. will default to ``default_token_generator``, it's an instance of
  867. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  868. * ``post_reset_redirect``: The URL to redirect to after a successful
  869. password change.
  870. * ``from_email``: A valid email address. By default Django uses
  871. the :setting:`DEFAULT_FROM_EMAIL`.
  872. **Template context:**
  873. * ``form``: The form (see ``password_reset_form`` above) for resetting
  874. the user's password.
  875. **Email template context:**
  876. * ``email``: An alias for ``user.email``
  877. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  878. according to the ``email`` form field. Only active users are able to
  879. reset their passwords (``User.is_active is True``).
  880. * ``site_name``: An alias for ``site.name``. If you don't have the site
  881. framework installed, this will be set to the value of
  882. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  883. For more on sites, see :doc:`/ref/contrib/sites`.
  884. * ``domain``: An alias for ``site.domain``. If you don't have the site
  885. framework installed, this will be set to the value of
  886. ``request.get_host()``.
  887. * ``protocol``: http or https
  888. * ``uid``: The user's id encoded in base 36.
  889. * ``token``: Token to check that the password is valid.
  890. Sample ``registration/password_reset_email.html`` (email body template):
  891. .. code-block:: html+django
  892. Someone asked for password reset for email {{ email }}. Follow the link below:
  893. {{ protocol}}://{{ site_name }}{% url 'auth_password_reset_confirm' uidb36=uid token=token %}
  894. The same template context is used for subject template. Subject must be
  895. single line plain text string.
  896. .. function:: password_reset_done(request[, template_name])
  897. The page shown after a user has been emailed a link to reset their
  898. password. This view is called by default if the :func:`password_reset` view
  899. doesn't have an explicit ``post_reset_redirect`` URL set.
  900. **URL name:** ``password_reset_done``
  901. **Optional arguments:**
  902. * ``template_name``: The full name of a template to use.
  903. Defaults to :file:`registration/password_reset_done.html` if not
  904. supplied.
  905. .. function:: password_reset_confirm(request[, uidb36, token, template_name, token_generator, set_password_form, post_reset_redirect])
  906. Presents a form for entering a new password.
  907. **URL name:** ``password_reset_confirm``
  908. **Optional arguments:**
  909. * ``uidb36``: The user's id encoded in base 36. Defaults to ``None``.
  910. * ``token``: Token to check that the password is valid. Defaults to
  911. ``None``.
  912. * ``template_name``: The full name of a template to display the confirm
  913. password view. Default value is :file:`registration/password_reset_confirm.html`.
  914. * ``token_generator``: Instance of the class to check the password. This
  915. will default to ``default_token_generator``, it's an instance of
  916. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  917. * ``set_password_form``: Form that will be used to set the password.
  918. Defaults to :class:`~django.contrib.auth.forms.SetPasswordForm`
  919. * ``post_reset_redirect``: URL to redirect after the password reset
  920. done. Defaults to ``None``.
  921. **Template context:**
  922. * ``form``: The form (see ``set_password_form`` above) for setting the
  923. new user's password.
  924. * ``validlink``: Boolean, True if the link (combination of uidb36 and
  925. token) is valid or unused yet.
  926. .. function:: password_reset_complete(request[,template_name])
  927. Presents a view which informs the user that the password has been
  928. successfully changed.
  929. **URL name:** ``password_reset_complete``
  930. **Optional arguments:**
  931. * ``template_name``: The full name of a template to display the view.
  932. Defaults to :file:`registration/password_reset_complete.html`.
  933. Helper functions
  934. ----------------
  935. .. currentmodule:: django.contrib.auth.views
  936. .. function:: redirect_to_login(next[, login_url, redirect_field_name])
  937. Redirects to the login page, and then back to another URL after a
  938. successful login.
  939. **Required arguments:**
  940. * ``next``: The URL to redirect to after a successful login.
  941. **Optional arguments:**
  942. * ``login_url``: The URL of the login page to redirect to.
  943. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  944. * ``redirect_field_name``: The name of a ``GET`` field containing the
  945. URL to redirect to after log out. Overrides ``next`` if the given
  946. ``GET`` parameter is passed.
  947. Built-in forms
  948. --------------
  949. .. module:: django.contrib.auth.forms
  950. If you don't want to use the built-in views, but want the convenience of not
  951. having to write forms for this functionality, the authentication system
  952. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  953. .. class:: AdminPasswordChangeForm
  954. A form used in the admin interface to change a user's password.
  955. .. class:: AuthenticationForm
  956. A form for logging a user in.
  957. .. class:: PasswordChangeForm
  958. A form for allowing a user to change their password.
  959. .. class:: PasswordResetForm
  960. A form for generating and emailing a one-time use link to reset a
  961. user's password.
  962. .. class:: SetPasswordForm
  963. A form that lets a user change his/her password without entering the old
  964. password.
  965. .. class:: UserChangeForm
  966. A form used in the admin interface to change a user's information and
  967. permissions.
  968. .. class:: UserCreationForm
  969. A form for creating a new user.
  970. Limiting access to logged-in users that pass a test
  971. ---------------------------------------------------
  972. .. currentmodule:: django.contrib.auth.decorators
  973. To limit access based on certain permissions or some other test, you'd do
  974. essentially the same thing as described in the previous section.
  975. The simple way is to run your test on :attr:`request.user
  976. <django.http.HttpRequest.user>` in the view directly. For example, this view
  977. checks to make sure the user is logged in and has the permission
  978. ``polls.can_vote``::
  979. def my_view(request):
  980. if not request.user.has_perm('polls.can_vote'):
  981. return HttpResponse("You can't vote in this poll.")
  982. # ...
  983. .. function:: user_passes_test(func, [login_url=None])
  984. As a shortcut, you can use the convenient ``user_passes_test`` decorator::
  985. from django.contrib.auth.decorators import user_passes_test
  986. @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
  987. def my_view(request):
  988. ...
  989. We're using this particular test as a relatively simple example. However,
  990. if you just want to test whether a permission is available to a user, you
  991. can use the :func:`~django.contrib.auth.decorators.permission_required()`
  992. decorator, described later in this document.
  993. :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
  994. argument: a callable that takes a
  995. :class:`~django.contrib.auth.models.User` object and returns ``True`` if
  996. the user is allowed to view the page. Note that
  997. :func:`~django.contrib.auth.decorators.user_passes_test` does not
  998. automatically check that the :class:`~django.contrib.auth.models.User` is
  999. not anonymous.
  1000. :func:`~django.contrib.auth.decorators.user_passes_test()` takes an
  1001. optional ``login_url`` argument, which lets you specify the URL for your
  1002. login page (:setting:`settings.LOGIN_URL <LOGIN_URL>` by default).
  1003. For example::
  1004. from django.contrib.auth.decorators import user_passes_test
  1005. @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
  1006. def my_view(request):
  1007. ...
  1008. The permission_required decorator
  1009. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1010. .. function:: permission_required([login_url=None, raise_exception=False])
  1011. It's a relatively common task to check whether a user has a particular
  1012. permission. For that reason, Django provides a shortcut for that case: the
  1013. :func:`~django.contrib.auth.decorators.permission_required()` decorator.
  1014. Using this decorator, the earlier example can be written as::
  1015. from django.contrib.auth.decorators import permission_required
  1016. @permission_required('polls.can_vote')
  1017. def my_view(request):
  1018. ...
  1019. As for the :meth:`User.has_perm` method, permission names take the form
  1020. ``"<app label>.<permission codename>"`` (i.e. ``polls.can_vote`` for a
  1021. permission on a model in the ``polls`` application).
  1022. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  1023. also takes an optional ``login_url`` parameter. Example::
  1024. from django.contrib.auth.decorators import permission_required
  1025. @permission_required('polls.can_vote', login_url='/loginpage/')
  1026. def my_view(request):
  1027. ...
  1028. As in the :func:`~decorators.login_required` decorator, ``login_url``
  1029. defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  1030. .. versionchanged:: 1.4
  1031. Added ``raise_exception`` parameter. If given, the decorator will raise
  1032. :exc:`~django.core.exceptions.PermissionDenied`, prompting
  1033. :ref:`the 403 (HTTP Forbidden) view<http_forbidden_view>` instead of
  1034. redirecting to the login page.
  1035. .. currentmodule:: django.contrib.auth
  1036. Limiting access to generic views
  1037. --------------------------------
  1038. To limit access to a :doc:`class-based generic view </ref/class-based-views>`,
  1039. decorate the :meth:`View.dispatch <django.views.generic.base.View.dispatch>`
  1040. method on the class. See :ref:`decorating-class-based-views` for details.
  1041. .. _permissions:
  1042. Permissions
  1043. ===========
  1044. Django comes with a simple permissions system. It provides a way to assign
  1045. permissions to specific users and groups of users.
  1046. It's used by the Django admin site, but you're welcome to use it in your own
  1047. code.
  1048. The Django admin site uses permissions as follows:
  1049. * Access to view the "add" form and add an object is limited to users with
  1050. the "add" permission for that type of object.
  1051. * Access to view the change list, view the "change" form and change an
  1052. object is limited to users with the "change" permission for that type of
  1053. object.
  1054. * Access to delete an object is limited to users with the "delete"
  1055. permission for that type of object.
  1056. Permissions are set globally per type of object, not per specific object
  1057. instance. For example, it's possible to say "Mary may change news stories," but
  1058. it's not currently possible to say "Mary may change news stories, but only the
  1059. ones she created herself" or "Mary may only change news stories that have a
  1060. certain status, publication date or ID." The latter functionality is something
  1061. Django developers are currently discussing.
  1062. Default permissions
  1063. -------------------
  1064. When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
  1065. setting, it will ensure that three default permissions -- add, change and
  1066. delete -- are created for each Django model defined in one of your installed
  1067. applications.
  1068. These permissions will be created when you run :djadmin:`manage.py syncdb
  1069. <syncdb>`; the first time you run ``syncdb`` after adding
  1070. ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions
  1071. will be created for all previously-installed models, as well as for any new
  1072. models being installed at that time. Afterward, it will create default
  1073. permissions for new models each time you run :djadmin:`manage.py syncdb
  1074. <syncdb>`.
  1075. Assuming you have an application with an
  1076. :attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``,
  1077. to test for basic permissions you should use:
  1078. * add: ``user.has_perm('foo.add_bar')``
  1079. * change: ``user.has_perm('foo.change_bar')``
  1080. * delete: ``user.has_perm('foo.delete_bar')``
  1081. .. _custom-permissions:
  1082. Custom permissions
  1083. ------------------
  1084. To create custom permissions for a given model object, use the ``permissions``
  1085. :ref:`model Meta attribute <meta-options>`.
  1086. This example Task model creates three custom permissions, i.e., actions users
  1087. can or cannot do with Task instances, specific to your application::
  1088. class Task(models.Model):
  1089. ...
  1090. class Meta:
  1091. permissions = (
  1092. ("view_task", "Can see available tasks"),
  1093. ("change_task_status", "Can change the status of tasks"),
  1094. ("close_task", "Can remove a task by setting its status as closed"),
  1095. )
  1096. The only thing this does is create those extra permissions when you run
  1097. :djadmin:`manage.py syncdb <syncdb>`. Your code is in charge of checking the
  1098. value of these permissions when an user is trying to access the functionality
  1099. provided by the application (viewing tasks, changing the status of tasks,
  1100. closing tasks.) Continuing the above example, the following checks if a user may
  1101. view tasks::
  1102. user.has_perm('app.view_task')
  1103. API reference
  1104. -------------
  1105. .. currentmodule:: django.contrib.auth.models
  1106. .. class:: models.Permission
  1107. Fields
  1108. ~~~~~~
  1109. :class:`~django.contrib.auth.models.Permission` objects have the following
  1110. fields:
  1111. .. attribute:: Permission.name
  1112. Required. 50 characters or fewer. Example: ``'Can vote'``.
  1113. .. attribute:: Permission.content_type
  1114. Required. A reference to the ``django_content_type`` database table, which
  1115. contains a record for each installed Django model.
  1116. .. attribute:: Permission.codename
  1117. Required. 100 characters or fewer. Example: ``'can_vote'``.
  1118. Methods
  1119. ~~~~~~~
  1120. :class:`~django.contrib.auth.models.Permission` objects have the standard
  1121. data-access methods like any other :doc:`Django model </ref/models/instances>`.
  1122. .. currentmodule:: django.contrib.auth
  1123. Programmatically creating permissions
  1124. -------------------------------------
  1125. While custom permissions can be defined within a model's ``Meta`` class, you
  1126. can also create permissions directly. For example, you can create the
  1127. ``can_publish`` permission for a ``BlogPost`` model in ``myapp``::
  1128. from django.contrib.auth.models import Group, Permission
  1129. from django.contrib.contenttypes.models import ContentType
  1130. content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
  1131. permission = Permission.objects.create(codename='can_publish',
  1132. name='Can Publish Posts',
  1133. content_type=content_type)
  1134. The permission can then be assigned to a
  1135. :class:`~django.contrib.auth.models.User` via its ``user_permissions``
  1136. attribute or to a :class:`~django.contrib.auth.models.Group` via its
  1137. ``permissions`` attribute.
  1138. Authentication data in templates
  1139. ================================
  1140. The currently logged-in user and his/her permissions are made available in the
  1141. :doc:`template context </ref/templates/api>` when you use
  1142. :class:`~django.template.context.RequestContext`.
  1143. .. admonition:: Technicality
  1144. Technically, these variables are only made available in the template context
  1145. if you use :class:`~django.template.context.RequestContext` *and* your
  1146. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
  1147. ``"django.contrib.auth.context_processors.auth"``, which is default. For
  1148. more, see the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  1149. Users
  1150. -----
  1151. When rendering a template :class:`~django.template.context.RequestContext`, the
  1152. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  1153. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  1154. stored in the template variable ``{{ user }}``:
  1155. .. code-block:: html+django
  1156. {% if user.is_authenticated %}
  1157. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  1158. {% else %}
  1159. <p>Welcome, new user. Please log in.</p>
  1160. {% endif %}
  1161. This template context variable is not available if a ``RequestContext`` is not
  1162. being used.
  1163. Permissions
  1164. -----------
  1165. The currently logged-in user's permissions are stored in the template variable
  1166. ``{{ perms }}``. This is an instance of
  1167. :class:`django.contrib.auth.context_processors.PermWrapper`, which is a
  1168. template-friendly proxy of permissions.
  1169. .. versionchanged:: 1.3
  1170. Prior to version 1.3, ``PermWrapper`` was located in
  1171. ``django.core.context_processors``.
  1172. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  1173. :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
  1174. This example would display ``True`` if the logged-in user had any permissions
  1175. in the ``foo`` app::
  1176. {{ perms.foo }}
  1177. Two-level-attribute lookup is a proxy to
  1178. :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
  1179. would display ``True`` if the logged-in user had the permission
  1180. ``foo.can_vote``::
  1181. {{ perms.foo.can_vote }}
  1182. Thus, you can check permissions in template ``{% if %}`` statements:
  1183. .. code-block:: html+django
  1184. {% if perms.foo %}
  1185. <p>You have permission to do something in the foo app.</p>
  1186. {% if perms.foo.can_vote %}
  1187. <p>You can vote!</p>
  1188. {% endif %}
  1189. {% if perms.foo.can_drive %}
  1190. <p>You can drive!</p>
  1191. {% endif %}
  1192. {% else %}
  1193. <p>You don't have permission to do anything in the foo app.</p>
  1194. {% endif %}
  1195. Groups
  1196. ======
  1197. Groups are a generic way of categorizing users so you can apply permissions, or
  1198. some other label, to those users. A user can belong to any number of groups.
  1199. A user in a group automatically has the permissions granted to that group. For
  1200. example, if the group ``Site editors`` has the permission
  1201. ``can_edit_home_page``, any user in that group will have that permission.
  1202. Beyond permissions, groups are a convenient way to categorize users to give
  1203. them some label, or extended functionality. For example, you could create a
  1204. group ``'Special users'``, and you could write code that could, say, give them
  1205. access to a members-only portion of your site, or send them members-only email
  1206. messages.
  1207. API reference
  1208. -------------
  1209. .. class:: models.Group
  1210. Fields
  1211. ~~~~~~
  1212. :class:`~django.contrib.auth.models.Group` objects have the following fields:
  1213. .. attribute:: Group.name
  1214. Required. 80 characters or fewer. Any characters are permitted. Example:
  1215. ``'Awesome Users'``.
  1216. .. attribute:: Group.permissions
  1217. Many-to-many field to :class:`~django.contrib.auth.models.Permissions`::
  1218. group.permissions = [permission_list]
  1219. group.permissions.add(permission, permission, ...)
  1220. group.permissions.remove(permission, permission, ...)
  1221. group.permissions.clear()
  1222. .. _authentication-backends:
  1223. Other authentication sources
  1224. ============================
  1225. The authentication that comes with Django is good enough for most common cases,
  1226. but you may have the need to hook into another authentication source -- that
  1227. is, another source of usernames and passwords or authentication methods.
  1228. For example, your company may already have an LDAP setup that stores a username
  1229. and password for every employee. It'd be a hassle for both the network
  1230. administrator and the users themselves if users had separate accounts in LDAP
  1231. and the Django-based applications.
  1232. So, to handle situations like this, the Django authentication system lets you
  1233. plug in other authentication sources. You can override Django's default
  1234. database-based scheme, or you can use the default system in tandem with other
  1235. systems.
  1236. See the :doc:`authentication backend reference </ref/authbackends>`
  1237. for information on the authentication backends included with Django.
  1238. Specifying authentication backends
  1239. ----------------------------------
  1240. Behind the scenes, Django maintains a list of "authentication backends" that it
  1241. checks for authentication. When somebody calls
  1242. :func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log
  1243. a user in <how-to-log-a-user-in>` above -- Django tries authenticating across
  1244. all of its authentication backends. If the first authentication method fails,
  1245. Django tries the second one, and so on, until all backends have been attempted.
  1246. The list of authentication backends to use is specified in the
  1247. :setting:`AUTHENTICATION_BACKENDS` setting. This should be a tuple of Python
  1248. path names that point to Python classes that know how to authenticate. These
  1249. classes can be anywhere on your Python path.
  1250. By default, :setting:`AUTHENTICATION_BACKENDS` is set to::
  1251. ('django.contrib.auth.backends.ModelBackend',)
  1252. That's the basic authentication scheme that checks the Django users database.
  1253. The order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same
  1254. username and password is valid in multiple backends, Django will stop
  1255. processing at the first positive match.
  1256. .. note::
  1257. Once a user has authenticated, Django stores which backend was used to
  1258. authenticate the user in the user's session, and re-uses the same backend
  1259. for the duration of that session whenever access to the currently
  1260. authenticated user is needed. This effectively means that authentication
  1261. sources are cached on a per-session basis, so if you change
  1262. :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if
  1263. you need to force users to re-authenticate using different methods. A simple
  1264. way to do that is simply to execute ``Session.objects.all().delete()``.
  1265. Writing an authentication backend
  1266. ---------------------------------
  1267. An authentication backend is a class that implements two methods:
  1268. ``get_user(user_id)`` and ``authenticate(**credentials)``.
  1269. The ``get_user`` method takes a ``user_id`` -- which could be a username,
  1270. database ID or whatever -- and returns a ``User`` object.
  1271. The ``authenticate`` method takes credentials as keyword arguments. Most of
  1272. the time, it'll just look like this::
  1273. class MyBackend(object):
  1274. def authenticate(self, username=None, password=None):
  1275. # Check the username/password and return a User.
  1276. But it could also authenticate a token, like so::
  1277. class MyBackend(object):
  1278. def authenticate(self, token=None):
  1279. # Check the token and return a User.
  1280. Either way, ``authenticate`` should check the credentials it gets, and it
  1281. should return a ``User`` object that matches those credentials, if the
  1282. credentials are valid. If they're not valid, it should return ``None``.
  1283. The Django admin system is tightly coupled to the Django ``User`` object
  1284. described at the beginning of this document. For now, the best way to deal with
  1285. this is to create a Django ``User`` object for each user that exists for your
  1286. backend (e.g., in your LDAP directory, your external SQL database, etc.) You
  1287. can either write a script to do this in advance, or your ``authenticate``
  1288. method can do it the first time a user logs in.
  1289. Here's an example backend that authenticates against a username and password
  1290. variable defined in your ``settings.py`` file and creates a Django ``User``
  1291. object the first time a user authenticates::
  1292. from django.conf import settings
  1293. from django.contrib.auth.models import User, check_password
  1294. class SettingsBackend(object):
  1295. """
  1296. Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
  1297. Use the login name, and a hash of the password. For example:
  1298. ADMIN_LOGIN = 'admin'
  1299. ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
  1300. """
  1301. def authenticate(self, username=None, password=None):
  1302. login_valid = (settings.ADMIN_LOGIN == username)
  1303. pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
  1304. if login_valid and pwd_valid:
  1305. try:
  1306. user = User.objects.get(username=username)
  1307. except User.DoesNotExist:
  1308. # Create a new user. Note that we can set password
  1309. # to anything, because it won't be checked; the password
  1310. # from settings.py will.
  1311. user = User(username=username, password='get from settings.py')
  1312. user.is_staff = True
  1313. user.is_superuser = True
  1314. user.save()
  1315. return user
  1316. return None
  1317. def get_user(self, user_id):
  1318. try:
  1319. return User.objects.get(pk=user_id)
  1320. except User.DoesNotExist:
  1321. return None
  1322. Handling authorization in custom backends
  1323. -----------------------------------------
  1324. Custom auth backends can provide their own permissions.
  1325. The user model will delegate permission lookup functions
  1326. (:meth:`~django.contrib.auth.models.User.get_group_permissions()`,
  1327. :meth:`~django.contrib.auth.models.User.get_all_permissions()`,
  1328. :meth:`~django.contrib.auth.models.User.has_perm()`, and
  1329. :meth:`~django.contrib.auth.models.User.has_module_perms()`) to any
  1330. authentication backend that implements these functions.
  1331. The permissions given to the user will be the superset of all permissions
  1332. returned by all backends. That is, Django grants a permission to a user that
  1333. any one backend grants.
  1334. The simple backend above could implement permissions for the magic admin
  1335. fairly simply::
  1336. class SettingsBackend(object):
  1337. # ...
  1338. def has_perm(self, user_obj, perm, obj=None):
  1339. if user_obj.username == settings.ADMIN_LOGIN:
  1340. return True
  1341. else:
  1342. return False
  1343. This gives full permissions to the user granted access in the above example.
  1344. Notice that the backend auth functions all take the user object as an argument,
  1345. and they also accept the same arguments given to the associated
  1346. :class:`django.contrib.auth.models.User` functions.
  1347. A full authorization implementation can be found in
  1348. `django/contrib/auth/backends.py`_, which is the default backend and queries
  1349. the ``auth_permission`` table most of the time.
  1350. .. _django/contrib/auth/backends.py: https://github.com/django/django/blob/master/django/contrib/auth/backends.py
  1351. .. _anonymous_auth:
  1352. Authorization for anonymous users
  1353. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1354. .. versionchanged:: 1.2
  1355. An anonymous user is one that is not authenticated i.e. they have provided no
  1356. valid authentication details. However, that does not necessarily mean they are
  1357. not authorized to do anything. At the most basic level, most Web sites
  1358. authorize anonymous users to browse most of the site, and many allow anonymous
  1359. posting of comments etc.
  1360. Django's permission framework does not have a place to store permissions for
  1361. anonymous users. However, it has a foundation that allows custom authentication
  1362. backends to specify authorization for anonymous users. This is especially useful
  1363. for the authors of re-usable apps, who can delegate all questions of authorization
  1364. to the auth backend, rather than needing settings, for example, to control
  1365. anonymous access.
  1366. Authorization for inactive users
  1367. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1368. .. versionadded:: 1.3
  1369. An inactive user is a one that is authenticated but has its attribute
  1370. ``is_active`` set to ``False``. However this does not mean they are not
  1371. authorized to do anything. For example they are allowed to activate their
  1372. account.
  1373. The support for anonymous users in the permission system allows for
  1374. anonymous users to have permissions to do something while inactive
  1375. authenticated users do not.
  1376. Do not forget to test for the ``is_active`` attribute of the user in your own
  1377. backend permission methods.
  1378. Handling object permissions
  1379. ---------------------------
  1380. Django's permission framework has a foundation for object permissions, though
  1381. there is no implementation for it in the core. That means that checking for
  1382. object permissions will always return ``False`` or an empty list (depending on
  1383. the check performed).