auth.txt 72 KB

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