auth.txt 73 KB

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